一、目录结构
二、代码
1、UserController
1 package cn.bijian.controller; 2 3 import cn.bijian.exception.SysException; 4 import cn.bijian.model.User; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springframework.web.bind.annotation.RequestBody; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 import org.springframework.web.multipart.MultipartFile; 11 import org.springframework.web.servlet.ModelAndView; 12 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 import java.io.File; 16 import java.io.IOException; 17 import java.util.ArrayList; 18 import java.util.List; 19 import java.util.UUID; 20 21 @Controller 22 @RequestMapping("/user") 23 public class UserController { 24 @RequestMapping("/testString") 25 public String testString(Model model){ 26 User user = new User(); 27 user.setUsername("aaa"); 28 user.setPassword("123"); 29 user.setAge(18); 30 model.addAttribute("user",user); 31 return "success"; 32 } 33 34 @RequestMapping("/testVoid") 35 public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception { 36 //1、转发 37 //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); 38 //2、重定向 39 //response.sendRedirect(request.getContextPath()+"/res.jsp"); 40 //3、直接响应数据 41 response.setCharacterEncoding("utf-8"); 42 response.setContentType("text/html;charset=utf-8"); 43 response.getWriter().print("您好"); 44 return; 45 } 46 47 @RequestMapping("/testModelAndView") 48 public ModelAndView testModelAndView(){ 49 ModelAndView mv = new ModelAndView(); 50 mv.setViewName("list"); 51 List<User> users = new ArrayList<>(); 52 User user1 = new User(); 53 user1.setUsername("aaa"); 54 user1.setPassword("123"); 55 user1.setAge(12); 56 User user2 = new User(); 57 user2.setUsername("bbb"); 58 user2.setPassword("456"); 59 user2.setAge(18); 60 users.add(user1); 61 users.add(user2); 62 mv.addObject("users",users); 63 return mv; 64 } 65 66 @RequestMapping("/testForward") 67 public String testForward(){ 68 System.out.println("testForward"); 69 return "forward:/user/testString"; 70 } 71 72 @RequestMapping("/testRedirect") 73 public String testRedirect(){ 74 System.out.println("testRedirect"); 75 return "forward:/user/testString"; 76 } 77 78 /* 79 ResponseBody响应json数据 80 */ 81 @RequestMapping("/testResponseBody") 82 public @ResponseBody User testResponseBody(@RequestBody User user){ 83 //将json字符串封装到user对象中 84 System.out.println(user); 85 //模拟查询数据库 86 user.setUsername("bbb"); 87 user.setAge(20); 88 //响应(@ResponseBody将user转换为json) 89 return user; 90 } 91 92 /* 93 SpringMVC的文件上传 94 */ 95 @RequestMapping("/fileUpload") 96 public String testFileUpload(HttpServletRequest request,MultipartFile upload) throws IOException { 97 //upload必须和<input type="file" name="upload"/>中的name属性一样 98 System.out.println("SpringMVC的文件上传方式"); 99 //1、上传文件目录 100 String path = request.getSession().getServletContext().getRealPath("/uploads"); 101 // System.out.println(path); 102 //D:\\IdeaProjects\\apache-tomcat-9.0.40\\webapps\\ROOT\\uploads 103 File file = new File(path); 104 if (!file.exists()){ 105 file.mkdirs(); 106 } 107 //2、获取上传文件名称 108 String filename = upload.getOriginalFilename(); 109 String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); 110 filename = uuid + "_" + filename; 111 //3、上传文件 112 upload.transferTo(new File(path,filename)); 113 return "success"; 114 } 115 116 /* 117 异常处理 118 */ 119 @RequestMapping("/testException") 120 public String testException() throws SysException { 121 try { 122 int a = 10/0; 123 } catch (Exception e) { 124 e.printStackTrace(); 125 //向上抛出自定义异常 126 throw new SysException("查询出错了"); 127 } 128 return "success"; 129 } 130 131 /* 132 拦截器:Spring MVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。 133 1、过滤器是servlet规范中的一部分,任何java web工程都可以使用。拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能用。 134 2、过滤器在url-pattern中配置了/*之后,可以对所有要访问的资源拦截。拦截器它是只会拦截访问的控制器方法,如果访问的是jsp,html,css, 135 image或者js是不会进行拦截的。 136 */ 137 @RequestMapping("/testInterceptor") 138 public String testInterceptor(){ 139 System.out.println("testInterceptor..."); 140 return "success"; 141 } 142 143 }
2、SysException
1 package cn.bijian.exception; 2 3 public class SysException extends Exception{ 4 private String message; 5 6 public SysException(String message) { 7 this.message = message; 8 } 9 10 @Override 11 public String getMessage() { 12 return message; 13 } 14 15 public void setMessage(String message) { 16 this.message = message; 17 } 18 }
3、SysExceptionResolver
1 package cn.bijian.exception; 2 3 import org.springframework.web.servlet.HandlerExceptionResolver; 4 import org.springframework.web.servlet.ModelAndView; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 public class SysExceptionResolver implements HandlerExceptionResolver { 10 @Override 11 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 12 SysException e = null; 13 if (ex instanceof SysException){ 14 e = (SysException) ex; 15 }else { 16 e = new SysException("请联系管理员"); 17 } 18 ModelAndView mv = new ModelAndView(); 19 mv.setViewName("error"); 20 mv.addObject("message",e.getMessage()); 21 return mv; 22 } 23 }
4、MyInterceptor1
1 package cn.bijian.Interceptor; 2 3 import org.springframework.web.servlet.HandlerInterceptor; 4 import org.springframework.web.servlet.ModelAndView; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 /* 10 自定义拦截器 11 */ 12 public class MyInterceptor1 implements HandlerInterceptor { 13 /* 14 预处理,Controller方法执行前。 15 */ 16 @Override 17 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 18 System.out.println("MyInterceptor1方法执行了"); 19 System.out.println("preHandle1执行了"); 20 return true; 21 } 22 /* 23 Controller方法执行后,JSP视图执行前。 24 */ 25 @Override 26 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 27 System.out.println("postHandle1执行了"); 28 } 29 /* 30 JSP视图执行后。 31 */ 32 @Override 33 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 34 System.out.println("afterCompletion1执行了"); 35 } 36 }
5、MyInterceptor2
1 package cn.bijian.Interceptor; 2 3 import org.springframework.web.servlet.HandlerInterceptor; 4 import org.springframework.web.servlet.ModelAndView; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 /* 10 自定义拦截器2 11 */ 12 public class MyInterceptor2 implements HandlerInterceptor { 13 /* 14 预处理,Controller方法执行前。 15 */ 16 @Override 17 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 18 System.out.println("MyInterceptor2方法执行了"); 19 System.out.println("preHandle2执行了"); 20 return true; 21 } 22 /* 23 Controller方法执行后,JSP视图执行前。 24 */ 25 @Override 26 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 27 System.out.println("postHandle2执行了"); 28 } 29 /* 30 JSP视图执行后。 31 */ 32 @Override 33 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 34 System.out.println("afterCompletion2执行了"); 35 } 36 }
6、User
1 package cn.bijian.model; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable { 6 private String username; 7 private String password; 8 private Integer age; 9 10 public String getUsername() { 11 return username; 12 } 13 14 public void setUsername(String username) { 15 this.username = username; 16 } 17 18 public String getPassword() { 19 return password; 20 } 21 22 public void setPassword(String password) { 23 this.password = password; 24 } 25 26 public Integer getAge() { 27 return age; 28 } 29 30 public void setAge(Integer age) { 31 this.age = age; 32 } 33 34 @Override 35 public String toString() { 36 return "User{" + 37 "username='" + username + '\'' + 38 ", password='" + password + '\'' + 39 ", age=" + age + 40 '}'; 41 } 42 }
7、SpringMVC.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context.xsd"> 13 14 <context:component-scan base-package="cn.bijian"></context:component-scan> 15 <!--配置视图解析器--> 16 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 17 <property name="prefix" value="/WEB-INF/pages/"></property> 18 <property name="suffix" value=".jsp"></property> 19 </bean> 20 <!--前端控制器,哪些静态资源不拦截--> 21 <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> 22 <mvc:resources mapping="/images/**" location="/images/"></mvc:resources> 23 <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> 24 <!--配置spring开启注解MVC的支持--> 25 <mvc:annotation-driven></mvc:annotation-driven> 26 <!--文件解析器,id必须为multipartResolver--> 27 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 28 <property name="maxUploadSize" value="10485760"></property> 29 </bean> 30 <!--配置异常处理器--> 31 <bean id="sysExceptionResolver" class="cn.bijian.exception.SysExceptionResolver"></bean> 32 <!--配置拦截器--> 33 <mvc:interceptors> 34 <mvc:interceptor> 35 <!--哪些方法拦截--> 36 <mvc:mapping path="/user/*"/> 37 <!--哪些方法不拦截--> 38 <!-- <mvc:exclude-mapping path=""/>--> 39 <!--注册拦截器对象--> 40 <bean id="myInterceptor1" class="cn.bijian.Interceptor.MyInterceptor1"></bean> 41 </mvc:interceptor> 42 <mvc:interceptor> 43 <mvc:mapping path="/**"/> 44 <bean id="myInterceptor2" class="cn.bijian.Interceptor.MyInterceptor2"></bean> 45 </mvc:interceptor> 46 </mvc:interceptors> 47 48 </beans>
8、web.xml
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- 配置过滤器--> 8 <filter> 9 <filter-name>characterEncodingFilter</filter-name> 10 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 11 <init-param> 12 <param-name>encoding</param-name> 13 <param-value>utf-8</param-value> 14 </init-param> 15 </filter> 16 <filter-mapping> 17 <filter-name>characterEncodingFilter</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 21 <!--SpringMVC的核心配置器--> 22 <servlet> 23 <servlet-name>dispatcherServlet</servlet-name> 24 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 25 <!--配置Servlet的初始化参数,读取springmvc的配置文件,创建Spring容器--> 26 <init-param> 27 <param-name>contextConfigLocation</param-name> 28 <param-value>classpath:SpringMVC.xml</param-value> 29 </init-param> 30 <!--配置servlet启动时加载对象--> 31 <load-on-startup>1</load-on-startup> 32 </servlet> 33 <servlet-mapping> 34 <servlet-name>dispatcherServlet</servlet-name> 35 <url-pattern>/</url-pattern> 36 </servlet-mapping> 37 </web-app>
9、index.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <html> 3 <head> 4 <title>index</title> 5 <script src="js/jquery.min.js"></script> 6 <script> 7 <%--页面加载--%> 8 $(function (){ 9 $("#btn").click(function (){ 10 $.ajax({ 11 url:"user/testResponseBody", 12 contentType:"application/json;charset=utf-8", 13 data:'{"username":"aa","password":"100","age":18}', 14 dataType:"json", 15 type:"post", 16 success:function (data) { 17 alert(data); 18 alert(data.username); 19 alert(data.password); 20 alert(data.age); 21 } 22 }); 23 }); 24 }); 25 </script> 26 </head> 27 <body> 28 <h2>Hello World!</h2> 29 <a href="/user/testString">testString</a> 30 <h2>Hello World!</h2> 31 <a href="/user/testVoid">testVoid</a> 32 <h2>Hello World!</h2> 33 <a href="/user/testModelAndView">testModelAndView</a> 34 <h2>Hello World!</h2> 35 <a href="/user/testForward">testForward</a> 36 <h2>Hello World!</h2> 37 <a href="/user/testRedirect">testRedirect</a> 38 <h2>Hello World!</h2> 39 40 <button id="btn">发送AJAX请求</button> 41 42 <h3>文件上传</h3> 43 <form action="/user/fileUpload" method="post" enctype="multipart/form-data"> 44 选择文件:<input type="file" name="upload"/><br/> 45 <input type="submit" value="上传"> 46 </form> 47 <h2>Hello World!</h2> 48 <a href="/user/testException">testException</a> 49 <h2>Hello World!</h2> 50 <a href="/user/testInterceptor">testInterceptor</a> 51 </body> 52 </html>
10、error.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <html> 4 <head> 5 <title>执行失败</title> 6 </head> 7 <body> 8 <h3>执行失败!</h3> 9 <h2>${message}</h2> 10 </body> 11 </html>
11、list.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <html> 4 <head> 5 <title>list</title> 6 </head> 7 <body> 8 <h3>查询所有数据</h3> 9 <c:forEach items="${users}" var="user"> 10 ${user.username} 11 ${user.password} 12 ${user.age} 13 </c:forEach> 14 </body> 15 </html>
12、success.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <html> 3 <head> 4 <title>success</title> 5 </head> 6 <body> 7 <h3>success</h3> 8 ${user.username} 9 ${user.password} 10 ${user.age} 11 <h3>success</h3> 12 </body> 13 </html>
13、res.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <body> 4 <h3>res</h3> 5 6 </body> 7 </html>
14、pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>cn.bijian</groupId> 8 <artifactId>SpringMVC_review_2</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>SpringMVC_review_2 Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 18 <maven.compiler.source>1.7</maven.compiler.source> 19 <maven.compiler.target>1.7</maven.compiler.target> 20 </properties> 21 22 <dependencies> 23 <dependency> 24 <groupId>junit</groupId> 25 <artifactId>junit</artifactId> 26 <version>4.11</version> 27 <scope>test</scope> 28 </dependency> 29 30 <dependency> 31 <groupId>org.springframework</groupId> 32 <artifactId>spring-context</artifactId> 33 <version>5.0.3.RELEASE</version> 34 </dependency> 35 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-web</artifactId> 39 <version>5.0.3.RELEASE</version> 40 </dependency> 41 42 <dependency> 43 <groupId>org.springframework</groupId> 44 <artifactId>spring-webmvc</artifactId> 45 <version>5.0.4.RELEASE</version> 46 </dependency> 47 48 <dependency> 49 <groupId>javax.servlet</groupId> 50 <artifactId>servlet-api</artifactId> 51 <version>2.5</version> 52 </dependency> 53 54 <dependency> 55 <groupId>javax.servlet</groupId> 56 <artifactId>jsp-api</artifactId> 57 <version>2.0</version> 58 </dependency> 59 60 <dependency> 61 <groupId>javax.servlet</groupId> 62 <artifactId>jstl</artifactId> 63 <version>1.2</version> 64 </dependency> 65 66 <dependency> 67 <groupId>com.fasterxml.jackson.core</groupId> 68 <artifactId>jackson-annotations</artifactId> 69 <version>2.9.2</version> 70 </dependency> 71 72 <dependency> 73 <groupId>com.fasterxml.jackson.core</groupId> 74 <artifactId>jackson-databind</artifactId> 75 <version>2.9.2</version> 76 </dependency> 77 78 <dependency> 79 <groupId>com.fasterxml.jackson.core</groupId> 80 <artifactId>jackson-core</artifactId> 81 <version>2.9.2</version> 82 </dependency> 83 84 <dependency> 85 <groupId>commons-io</groupId> 86 <artifactId>commons-io</artifactId> 87 <version>2.6</version> 88 </dependency> 89 90 <dependency> 91 <groupId>commons-fileupload</groupId> 92 <artifactId>commons-fileupload</artifactId> 93 <version>1.3.1</version> 94 </dependency> 95 </dependencies> 96 97 <build> 98 <finalName>SpringMVC_review_2</finalName> 99 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 100 <plugins> 101 <plugin> 102 <artifactId>maven-clean-plugin</artifactId> 103 <version>3.1.0</version> 104 </plugin> 105 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 106 <plugin> 107 <artifactId>maven-resources-plugin</artifactId> 108 <version>3.0.2</version> 109 </plugin> 110 <plugin> 111 <artifactId>maven-compiler-plugin</artifactId> 112 <version>3.8.0</version> 113 </plugin> 114 <plugin> 115 <artifactId>maven-surefire-plugin</artifactId> 116 <version>2.22.1</version> 117 </plugin> 118 <plugin> 119 <artifactId>maven-war-plugin</artifactId> 120 <version>3.2.2</version> 121 </plugin> 122 <plugin> 123 <artifactId>maven-install-plugin</artifactId> 124 <version>2.5.2</version> 125 </plugin> 126 <plugin> 127 <artifactId>maven-deploy-plugin</artifactId> 128 <version>2.8.2</version> 129 </plugin> 130 </plugins> 131 </pluginManagement> 132 </build> 133 </project>