# SpringMVC 3/4上課內容 ###### tags: `SpringMVC` [老師云端](https://1drv.ms/u/s!Ans47I9-PkivwH8KqgNszZ8OKcZe) # 77 SpringMVC動態網站開發實務(設計多國語系的網路應用系統) ![](https://i.imgur.com/72775vL.png) *** ![](https://i.imgur.com/Gu8HZmp.png) # 78 SpringMVC動態網站開發實務 ![](https://i.imgur.com/sQsJkby.png) *** ![](https://i.imgur.com/brTujwy.png) # 79 SpringMVC動態網站開發實務 ![](https://i.imgur.com/FRv7xgp.png) [Properties](https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html) # 80 SpringMVC動態網站開發實務(使用靜態資源) ![](https://i.imgur.com/i9FJ9sw.png) * 虛擬路徑 * **DefaultServlet** * ![](https://i.imgur.com/iArsHdy.png) *** ![](https://i.imgur.com/WjjHHTJ.png) ![](https://i.imgur.com/YEwtfrc.png) * 組態設定 ![](https://i.imgur.com/2IRKmye.png) * 虛擬的路徑 * 實際上class放的路徑 # 82 SpringMVC動態網站開發實務 ![](https://i.imgur.com/gZpgdQh.png) ![](https://i.imgur.com/8FcdKF3.png) * location=檔案實際位址 * mapping=網址虛擬位址 #### mvc-servlet.xml 建立圖片檔案 ![](https://i.imgur.com/exhDhgR.png) ![](https://i.imgur.com/gXN4aDQ.png) ```clike= <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:annotation-config/> <context:component-scan base-package="tw.leonchen"/> <mvc:annotation-driven/> <!-- @EnableTransactionManager功能意義相同 --> <tx:annotation-driven transaction-manager="transactionMamager"/> <mvc:resources location="/WEB-INF/pages/images/" mapping="/images/**"/> <bean id="helloControler" name="/hello.controller" class="tw.leonchen.controller.HelloController"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> <property name="order" value="2"/> </bean> </beans> ``` ### 圖片網址&虛擬路徑 ![](https://i.imgur.com/6OQfIXC.png) #### 圖片網站測試 showImages.jsp (圖片自行修改) ![](https://i.imgur.com/7noeAuD.png) ```clike= <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <img src="http://localhost:8080/SpringMvcWebProject/images/cat.jpg" width="350" height="280" /> </body> </html> ``` #### SpringMVCJavaConfig ![](https://i.imgur.com/JgWLxcD.png) ![](https://i.imgur.com/klj77Qv.png) ```clike= package tw.leonchen.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; //設定檔 @Configuration @EnableWebMvc @ComponentScan(basePackages = "tw.leonchen") public class SpringMVCJavaConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(2); return viewResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/pages/images"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } ``` #### 測試 @都註解掉 ![](https://i.imgur.com/HXhvr1P.png) #### 多個檔案路徑 ![](https://i.imgur.com/kck5mP2.png) ![](https://i.imgur.com/cHSS2C4.png) #### mvc-servlet.xml ```clike= <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:annotation-config/> <context:component-scan base-package="tw.leonchen"/> <mvc:annotation-driven/> <!-- @EnableTransactionManager功能意義相同 --> <tx:annotation-driven transaction-manager="transactionManager"/> <mvc:resources location="/WEB-INF/pages/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/pages/css/" mapping="/css/**"/> <mvc:view-controller path="/" view-name="redirect:loginSystemMain.controller"/> <bean id="helloControler" name="/hello.controller" class="tw.leonchen.controller.HelloController"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> <property name="order" value="2"/> </bean> </beans> ``` # 82 SpringMVC動態網站開發實務(為網頁加入能夠顯示圖片的功能) ![](https://i.imgur.com/w9RGgd2.png) # 83 SpringMVC動態網站開發實務 ![](https://i.imgur.com/ukQ8fEg.png) * 狀態碼 *** ![](https://i.imgur.com/tQp7Z7b.png) #### ResponseController ![](https://i.imgur.com/NWX09lK.png) ```clike= package tw.leonchen.controller; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ResponseController { @RequestMapping(path = "/responseMsg.controller", method = RequestMethod.GET) public @ResponseBody String processResponseBody() { return "Message From Server Response"; } @RequestMapping(path = "/response/responseMsgCharset.controller", method = RequestMethod.GET) @ResponseBody public String processResponseBodyCharset() { return "你好, \"hello\""; } @RequestMapping(path = "/response/responseMsgCharsetEncode.controller", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8") @ResponseBody public String processResponseBodyCharsetEncode() { return "你好, \"hello\""; } @RequestMapping(path = "/response/responseStatusCode.controller", method = RequestMethod.GET) public ResponseEntity<String> processResponseStatusCode() { return new ResponseEntity<String>("Custom Status Code Forbidden(403)", HttpStatus.FORBIDDEN); } @RequestMapping(path = "/response/responseHeader.controller", method = RequestMethod.GET) public ResponseEntity<String> processResponseHeader(){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<String>("Custom Content Type text/plain", headers, HttpStatus.OK); } } ``` # 84 SpringMVC動態網站開發實務 ![](https://i.imgur.com/KHt7esN.png) *** ![](https://i.imgur.com/wwvQJFM.png) # 85 SpringMVC動態網站開發實務 ![](https://i.imgur.com/1JwmsRj.png) #### pom.xml ![](https://i.imgur.com/2Ou600z.png) [maver](https://mvnrepository.com/artifact/commons-io/commons-io) ```clike= <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> ``` ![](https://i.imgur.com/8fZWAA8.png) #### ResponseController ```clike= package tw.leonchen.controller; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ResponseController { @RequestMapping(path = "/responseMsg.controller", method = RequestMethod.GET) public @ResponseBody String processResponseBody() { return "Message From Server Response"; } @RequestMapping(path = "/response/responseMsgCharset.controller", method = RequestMethod.GET) @ResponseBody public String processResponseBodyCharset() { return "你好, \"hello\""; } @RequestMapping(path = "/response/responseMsgCharsetEncode.controller", method = RequestMethod.GET,produces = "text/plain;charset=UTF-8") @ResponseBody public String processResponseBodyCharsetEncode() { return "你好, \"hello\""; } @RequestMapping(path = "/response/responseStatusCode.controller",method = RequestMethod.GET) public ResponseEntity<String> processResponseStatusCode(){ return new ResponseEntity<String>("Custom Status Code Forbidden(403)",HttpStatus.FORBIDDEN); } @RequestMapping(path = "/response/responseHeader.controller",method = RequestMethod.GET) public ResponseEntity<String> processResponseHeader(){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<String>("Custom Content Type text/plain",headers, HttpStatus.OK); } @RequestMapping(path = "/response/responseImage.controller",method = RequestMethod.GET) public void processResponseImage(HttpServletRequest request,HttpServletResponse response)throws IOException { InputStream is1 = request.getServletContext().getResourceAsStream("/WEB-INF/pages/images/cat.jpg"); IOUtils.copy(is1, response.getOutputStream()); } @RequestMapping(path = "/response/responseImageByteArray.controller",method = RequestMethod.GET) public @ResponseBody byte[] processResponseImageByteArray(HttpServletRequest request,HttpServletResponse response)throws IOException { InputStream is1 = request.getServletContext().getResourceAsStream("/WEB-INF/pages/images/cat.jpg"); response.setContentType(MediaType.IMAGE_JPEG_VALUE); return IOUtils.toByteArray(is1); } } ``` # 86 SpringMVC動態網站開發實務(檔案上傳) ![](https://i.imgur.com/ugWQErt.png) [commons fileupload](https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.4) *** ![](https://i.imgur.com/HnTwP6b.png) * 加入位置 ![](https://i.imgur.com/rATSge3.png) [CommonsMultipartResolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/multipart/commons/CommonsMultipartResolver.html) * 中文檔名可以上傳 #### pom.xml ```clike= <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> ``` #### mvc-servlet.xml ```clike= <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> </bean> ``` #### SpringMVCJavaConfig ```clike= package tw.leonchen.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; //@Configuration //@EnableWebMvc //@ComponentScan(basePackages = "tw.leonchen") public class SpringMVCJavaConfig implements WebMvcConfigurer { @Bean public CommonsMultipartResolver multipartViewResolver() { CommonsMultipartResolver multipartViewResolver = new CommonsMultipartResolver(); multipartViewResolver.setDefaultEncoding("UTF-8"); return multipartViewResolver; } @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(2); return viewResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/pages/images/"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } ``` # 87 SpringMVC動態網站開發實務 ![](https://i.imgur.com/p9lWyW0.png) *** ![](https://i.imgur.com/E0fGSBb.png) #### uploadFile.jsp ![](https://i.imgur.com/ndFpcpO.png) ```clike= <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>FileUpload</title> </head> <body> <h3>Upload File</h3> <form action="uploadFile.controller" method="post" enctype="multipart/form-data"> Please Select Your Picture to Upload:<br/> <input type="file" name="myFiles"/> <input type="submit" value="upload"/> </form> </body> </html> ``` #### UploadFileController ![](https://i.imgur.com/j8vvYNG.png) ```clike= package tw.leonchen.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadFileController { @RequestMapping(path = "/uploadFileMain.controller", method = RequestMethod.GET) public String processUploadFileMainPage() { return "uploadFile"; } @RequestMapping(path = "/uploadFile.controller", method = RequestMethod.POST) @ResponseBody public ResponseEntity<byte[]> processFileUploadAction(@RequestParam(name = "myFiles") MultipartFile multipartFile, HttpServletRequest request) throws Exception, IOException{ String fileName = multipartFile.getOriginalFilename(); System.out.println("fileName:" + fileName); String saveDir = request.getSession().getServletContext().getRealPath("/") + "uploadTempDir\\"; System.out.println("saveDir:" + saveDir); File saveFileDir = new File(saveDir); saveFileDir.mkdirs(); File saveFilePath = new File(saveFileDir, fileName); multipartFile.transferTo(saveFilePath); System.out.println("saveFilePath:" + saveFilePath); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(saveFilePath), headers, HttpStatus.OK); } } ``` # 87 SpringMVC動態網站開發實務 ![](https://i.imgur.com/7j7ognR.png) *** ![](https://i.imgur.com/QYU0gqi.png) # 88 SpringMVC動態網站開發實務 ![](https://i.imgur.com/SnwYQWq.png) # 89 SpringMVC動態網站開發實務 ![](https://i.imgur.com/gtSlw02.png) #### sql Picture table ```clike= use LeonPower; create table Picture( id int not null primary key identity(1,1), filename nvarchar(50) not null, picture varbinary(max) not null ); select * from Picture; ``` #### Picture ![](https://i.imgur.com/u1Gtnfp.png) ```clike= package tw.leonchen.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.stereotype.Component; @Entity @Table(name = "Picture") @Component public class Picture { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "FILENAME") private String filename; @Column(name = "PICTURE") private byte[] picture; public Picture() { } public Picture(String filename, byte[] picture) { this.filename = filename; this.picture = picture; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public byte[] getPicture() { return picture; } public void setPicture(byte[] picture) { this.picture = picture; } } ``` # 90 SpringMVC動態網站開發實務 ![](https://i.imgur.com/VwlzJQE.png) * 讓他去自動找 就不用在註冊 * ![](https://i.imgur.com/TLOgqWH.png) *** ![](https://i.imgur.com/YZllOfd.png) #### PictureDAO ![](https://i.imgur.com/67YASpx.png) ```clike= package tw.leonchen.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository("pictureDao") @Transactional public class PictureDAO { @Autowired private SessionFactory sessionFactory; public Picture insert(Picture pbean) { Session session = sessionFactory.getCurrentSession(); if(pbean!=null){ session.save(pbean); } return pbean; } } ``` # 91 SpringMVC動態網站開發實務 ![](https://i.imgur.com/KQ1eT1A.png) *** ![](https://i.imgur.com/j52zWoF.png) [FileInputStream](https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html) #### PictureService ![](https://i.imgur.com/4fQfWox.png) ```clike= package tw.leonchen.model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("pictrueService") @Transactional public class PictureService { @Autowired private PictureDao pictureDao; public Picture insert(Picture pbean) { return pictureDao.insert(pbean); } } ``` #### UploadFileController ```clike= package tw.leonchen.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import tw.leonchen.model.Picture; import tw.leonchen.model.PictureService; @Controller public class UploadFileController { @Autowired private PictureService PictureService; @RequestMapping(path = "/uploadFileMain.controller",method = RequestMethod.GET) public String processUploadFileMainPage() { return "uploadFile"; } @RequestMapping(path = "/uploadFile.controller",method = RequestMethod.POST) @ResponseBody public ResponseEntity<byte[]> processFileUploadAction(@RequestParam(name = "myFiles") MultipartFile multipartFile, HttpServletRequest request)throws IOException { String fileName = multipartFile.getOriginalFilename(); System.out.println("fileName:"+fileName); String saveDir = request.getSession().getServletContext().getRealPath("/")+"uploadTempDir\\"; System.out.println("saveDir:"+saveDir); File saveFileDir = new File(saveDir); saveFileDir.mkdirs(); File saveFilePath = new File(saveFileDir,fileName); multipartFile.transferTo(saveFilePath); System.out.println("saveFilePath:"+saveFilePath); if(fileName !=null && fileName.length()!=0) { savePicture(fileName, saveFilePath); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(saveFilePath),headers, HttpStatus.OK); } private void savePicture(String fileName, File saveFilePath) throws IOException { InputStream is1 = new FileInputStream(saveFilePath); byte[] b1 = new byte[is1.available()]; is1.read(b1); is1.close(); Picture picture = new Picture(fileName,b1); PictureService.insert(picture); } } ``` * 重點 ![](https://i.imgur.com/R4ZwWKp.png) * 建構子部分 ![](https://i.imgur.com/q6MVJb9.png) ![](https://i.imgur.com/tIjzFvE.png) # 92 SpringMVC動態網站開發實務(伺服器送出JSON的資料) ![](https://i.imgur.com/6LJeP3u.png) *** ![](https://i.imgur.com/AlG0Dt1.png) #### pom.xml [Jackson Databind](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.12.2) [Jackson Annotations](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.12.2) ```clike= <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMvcWebProject</groupId> <artifactId>SpringMvcWebProject</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>8.4.1.jre11</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.28.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>5.3.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.12.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.12.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>11</release> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> </plugins> </build> </project> ``` * 4個jar檔 ![](https://i.imgur.com/DFuoBXp.png) # 93 SpringMVC動態網站開發實務 ![](https://i.imgur.com/n7tl51j.png) # 94 SpringMVC動態網站開發實務 ![](https://i.imgur.com/aS0Tb0r.png) *** ![](https://i.imgur.com/tkSZu9B.png) # 95 SpringMVC動態網站開發實務 ![](https://i.imgur.com/EqHbNjS.png) *** ![](https://i.imgur.com/EHplKux.png) #### mvc-servlet.xml [MappingJackson2JsonView](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/json/MappingJackson2JsonView.html) [Jaxb2Marshaller](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/oxm/jaxb/Jaxb2Marshaller.html) [ContentNegotiatingViewResolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.html) ```clike= <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:annotation-config/> <context:component-scan base-package="tw.leonchen"/> <mvc:annotation-driven/> <!-- @EnableTransactionManager功能意義相同 --> <tx:annotation-driven transaction-manager="transactionManager"/> <mvc:resources location="/WEB-INF/pages/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/pages/css/" mapping="/css/**"/> <mvc:view-controller path="/" view-name="redirect:loginSystemMain.controller"/> <bean id="helloControler" name="/hello.controller" class="tw.leonchen.controller.HelloController"/> <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> <property name="prettyPrint" value="true"/> </bean> <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="classesToBeBound"> <list> <value>tw.leonchen.model.House</value> </list> </property> </bean> <bean id="contentViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="defaultViews"> <list> <ref bean="jsonView"/> </list> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> <property name="order" value="2"/> </bean> </beans> ``` # 96 SpringMVC動態網站開發實務 ![](https://i.imgur.com/pBqpLgc.png) *** ![](https://i.imgur.com/YXZUrAU.png) #### JSONCreatorController ![](https://i.imgur.com/LFuYQHF.png) ```clike= package tw.leonchen.controller; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.databind.ObjectMapper; import tw.leonchen.model.House; @Controller public class JSONCreatorController { @RequestMapping(path = "/javaBean2Json.controller",method = RequestMethod.GET) @ResponseBody public String processJavaBeanToJson(Model m)throws IOException { House hbean = new House(); hbean.setHouseid(12345); hbean.setHousename("Pretty House"); ObjectMapper mapper = new ObjectMapper(); String jsonStr = mapper.writeValueAsString(hbean); House hbean2 = mapper.readValue(jsonStr, House.class); System.out.println(hbean2.getHouseid()+":"+hbean2.getHousename()); return jsonStr; } } ``` # 97 SpringMVC動態網站開發實務 * 第二種方式 ![](https://i.imgur.com/KHm24eW.png) # 98 SpringMVC動態網站開發實務(例外處理:自訂的例外處理頁面) ![](https://i.imgur.com/IALh8Mb.png) * 掌控 Exception *** ![](https://i.imgur.com/NXjXi8t.png) # 99 SpringMVC動態網站開發實務 ![](https://i.imgur.com/qjfU4UI.png) *** ![](https://i.imgur.com/AY9F898.png) * 拋出會被@Exception抓到 #### MyExceptionHandler ![](https://i.imgur.com/ZjgVc5v.png) ```clike= package tw.leonchen.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(Exception.class) public Object processExceptionHandle(Exception e) { String errMsg1 = "Error: Exception"; return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errMsg1); } } ``` #### MyExceptionHandleController ![](https://i.imgur.com/glQKK54.png) ```clike= package tw.leonchen.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class MyExceptionHandleController { @RequestMapping(path = "/myexceptionHandle.controller",method = RequestMethod.GET) public void processExceptionAction()throws Exception{ throw new Exception(); } }http://localhost:8080/SpringMvcWebProject/uploadFile.controller ```