SpringMVC框架学习笔记
SpringMVC概念引入
B/S架构:浏览器-服务器
服务器分为三层:表现层,业务层,持久层
SpringMVC是一个表现层的框架。
表现层功能核心:
1.接收客户端(浏览器)发过来的请求
2.把业务层传过来的数据响应给客户端(浏览器)
MVC概念:
M——>model:指javabean对象
V——>view:指JSP技术
C——>controller:指servlet
工作流程:
浏览器向服务器发送请求——>控制器接收请求——>用javabean将数据封装起来——>与业务层交互
从业务层获得了返回的数据——>将数据封装至javabean——>程序转发至JSP,并显示结果,生成html——>响应给浏览器
SpringMVC入门
需求:制作一个index.jsp网页,点击上面的超链接标签,即浏览器向服务器发送请求。我们编写一个类,并定义相关的方法来处理该请求,并跳转到一个指示成功的jsp页面。
环境搭建:
步骤1:创建一个maven工程,选择使用webapp骨架搭建,需要一定的时间
步骤2:配置pom.xml文件,导入依赖,包括spring-context,spring-web,spring-webmvc,servlet,jsp
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>org.example</groupId> 8 <artifactId>springMVC</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>springMVC 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.8</maven.compiler.source> 19 <maven.compiler.target>1.8</maven.compiler.target> 20 <spring.version>5.0.2.RELEASE</spring.version> 21 </properties> 22 23 <dependencies> 24 <dependency> 25 <groupId>org.springframework</groupId> 26 <artifactId>spring-context</artifactId> 27 <version>${spring.version}</version> 28 </dependency> 29 <dependency> 30 <groupId>org.springframework</groupId> 31 <artifactId>spring-web</artifactId> 32 <version>${spring.version}</version> 33 </dependency> 34 <dependency> 35 <groupId>org.springframework</groupId> 36 <artifactId>spring-webmvc</artifactId> 37 <version>${spring.version}</version> 38 </dependency> 39 <dependency> 40 <groupId>javax.servlet</groupId> 41 <artifactId>servlet-api</artifactId> 42 <version>2.5</version> 43 <scope>provided</scope> 44 </dependency> 45 <dependency> 46 <groupId>javax.servlet.jsp</groupId> 47 <artifactId>jsp-api</artifactId> 48 <version>2.0</version> 49 <scope>provided</scope> 50 </dependency> 51 </dependencies> 52 53 <build> 54 <finalName>springMVC</finalName> 55 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 56 <plugins> 57 <plugin> 58 <artifactId>maven-clean-plugin</artifactId> 59 <version>3.1.0</version> 60 </plugin> 61 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 62 <plugin> 63 <artifactId>maven-resources-plugin</artifactId> 64 <version>3.0.2</version> 65 </plugin> 66 <plugin> 67 <artifactId>maven-compiler-plugin</artifactId> 68 <version>3.8.0</version> 69 </plugin> 70 <plugin> 71 <artifactId>maven-surefire-plugin</artifactId> 72 <version>2.22.1</version> 73 </plugin> 74 <plugin> 75 <artifactId>maven-war-plugin</artifactId> 76 <version>3.2.2</version> 77 </plugin> 78 <plugin> 79 <artifactId>maven-install-plugin</artifactId> 80 <version>2.5.2</version> 81 </plugin> 82 <plugin> 83 <artifactId>maven-deploy-plugin</artifactId> 84 <version>2.8.2</version> 85 </plugin> 86 </plugins> 87 </pluginManagement> 88 </build> 89 </project>
步骤3:补全目录:src/main/java(设置为source root),src/main/resource(设置为resource root)
步骤4:配置前端控制器,src/main/webapp/WEB-INF/web.xml,指定servlet为DispatcherServlet,具体代码如下:
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 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 </servlet> 12 <servlet-mapping> 13 <servlet-name>dispatcherServlet</servlet-name> 14 <!--表示发任何请求都会经过servlet--> 15 <url-pattern>/</url-pattern> 16 </servlet-mapping> 17 </web-app>
步骤5:在src/main/resource目录下新建一个springmvc.xml文件(选择spring config)
步骤6:部署服务器:
右上方add configuration左上方templates,选择tomcat server-local。
server菜单中:browser选默认,update action选Redepoly,URL设置为:http://localhost:8080//springMVC/index.jsp
Deployment菜单中,加号,选Artifact,选SpringMVC:war。Application context:/springMVC.最后Apply。
代码编写:
步骤1:重新创建一个主页面文件index.jsp。打印文字:入门程序,创建超链接:入门程序。href设为hello。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <h3>入门程序</h3> 8 <a href="hello">入门程序</a> 9 </body> 10 </html>
步骤2:src/main/java下创建一个controller包,创建一个HelloController的java文件。设置path为hello。核心:写一个方法,返回success(即跳转的页面)。
1 package controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 public class HelloController { 8 @RequestMapping(path="/hello") 9 public String sayHello(){ 10 System.out.println("Hello SpringMVC"); 11 return "success"; 12 } 13 }
步骤3:webapp/WEB-INF下创建一个pages包,创建一个名为sccess的java文件。打印:入门成功。
1 <%@ page contentType="text/html;charset=UTF-8" language="java"%> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 8 <h3>入门成功</h3> 9 10 11 </body> 12 </html>
步骤4:配置springmvc.xml文件:开启注解扫描,视图解析器,指定index.jsp。最后开启SpingMVC注解支持(后面要用到)。
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="controller"/> 15 <!--视图解析器--> 16 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 17 <property name="prefix" value="/WEB-INF/pages/"/> 18 <property name="suffix" value=".jsp"/> 19 </bean> 20 <!--开启SpringMVC注解支持--> 21 <mvc:annotation-driven/> 22 23 </beans>
步骤5:webapp/WEB-INF下创建一个web.xml配置文件。在其中进行前端控制器的配置,导入配置文件springmvc.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 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!--导入配置文件springmvc.xml--> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc.xml</param-value> 15 </init-param> 16 <load-on-startup>1</load-on-startup> 17 </servlet> 18 <servlet-mapping> 19 <servlet-name>dispatcherServlet</servlet-name> 20 <!--表示发任何请求都会经过servlet--> 21 <url-pattern>/</url-pattern> 22 </servlet-mapping> 23 </web-app>
注意:springmvc.xml中的base-package不能写java,只能写子目录。
请求参数的绑定
客户端发送请求时包含一些参数,服务器获得这些参数并进行绑定。
入门版本:绑定用户名与密码
在上面入门版本程序的基础上:
步骤1:webapp中创建一个param.jsp,制作超链接:请求参数绑定。href写为:param/testParam?username=fdx&password=123。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="param/testParam?username=fdx&password=123">请求参数绑定</a> 8 </body> 9 </html>
步骤2:src/main/java/controller包下创建一个ParamController的java文件。方法参数传入username与password。打印username与password,并返回sccess。
1 package controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 @RequestMapping("/param") 8 public class ParamController { 9 @RequestMapping("/testParam") 10 public String testParam(String username,String password){ 11 System.out.println("执行参数绑定"); 12 System.out.println("用户名:"+username); 13 System.out.println("密码:"+password); 14 return "success"; 15 } 16 }
运行后,访问http://localhost:8080//springMVC/param.jsp,可以看到控制台会输出:
执行参数绑定
用户名:fdx
密码:123
绑定实体类型:
步骤1:src/main/java下创建一个domain包,写一个Account类,一个User类。其中,Account类中包含user类的对象user。
Account类代码:(记得要生成所有属性包括user的get&set方法)
1 package domain; 2 3 import java.io.Serializable; 4 5 public class Account implements Serializable { 6 private String username; 7 private String password; 8 private Double money; 9 private User user; 10 11 public String getUsername() { 12 return username; 13 } 14 15 public void setUsername(String username) { 16 this.username = username; 17 } 18 19 public String getPassword() { 20 return password; 21 } 22 23 public void setPassword(String password) { 24 this.password = password; 25 } 26 27 public Double getMoney() { 28 return money; 29 } 30 31 public void setMoney(Double money) { 32 this.money = money; 33 } 34 35 public User getUser() { 36 return user; 37 } 38 39 public void setUser(User user) { 40 this.user = user; 41 } 42 43 @Override 44 public String toString() { 45 return "Account{" + 46 "username='" + username + '\'' + 47 ", password='" + password + '\'' + 48 ", money=" + money + 49 ", user=" + user + 50 '}'; 51 } 52 }
User类代码:
1 package domain; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable { 6 private String name; 7 private Integer age; 8 9 public String getName() { 10 return name; 11 } 12 13 public void setName(String name) { 14 this.name = name; 15 } 16 17 public Integer getAge() { 18 return age; 19 } 20 21 public void setAge(Integer age) { 22 this.age = age; 23 } 24 25 @Override 26 public String toString() { 27 return "User{" + 28 "name='" + name + '\'' + 29 ", age=" + age + 30 '}'; 31 } 32 }
步骤2:在param.jsp网页中写关于javabean里属性的输入框,注意写User类的属性时,要先指定user对象,再写属性名。最后写一个提交按钮。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <!--a href="param/testParam?username=fdx&password=123">请求参数绑定</a--> 8 <form action="param/saveAccount" method="post"> 9 姓名:<input type="text" name="username"/><br/> 10 密码:<input type="text" name="password"/><br/> 11 金额:<input type="text" name="money"/><br/> 12 用户-姓名:<input type="text" name="user.name"/><br/> 13 用户-年龄:<input type="text" name="user.age"/><br/> 14 <input type="submit" value="提交"/> 15 </form> 16 </body> 17 </html>
步骤3:在ParamController类中新定义一个方法,参数传入(Account account),方法体中打印account对象,这样做的目的是将运行时输入的参数保存到account对象中,并打印到控制台。
1 package controller; 2 3 import domain.Account; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @Controller 8 @RequestMapping("/param") 9 public class ParamController { 10 @RequestMapping("/testParam") 11 public String testParam(String username,String password){ 12 System.out.println("执行参数绑定"); 13 System.out.println("用户名:"+username); 14 System.out.println("密码:"+password); 15 return "success"; 16 } 17 //将数据封装到javabean 18 @RequestMapping("/saveAccount") 19 public String saveAccount(Account account){ 20 System.out.println("JavaBean参数绑定"); 21 System.out.println(account); 22 23 return "success"; 24 } 25 }
运行效果:
控制台输出:
细节改进:解决中文乱码问题
在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 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!--导入配置文件springmvc.xml--> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc.xml</param-value> 15 </init-param> 16 <load-on-startup>1</load-on-startup> 17 </servlet> 18 <servlet-mapping> 19 <servlet-name>dispatcherServlet</servlet-name> 20 <!--表示发任何请求都会经过servlet--> 21 <url-pattern>/</url-pattern> 22 </servlet-mapping> 23 <!--过滤器,解决中文乱码问题--> 24 <filter> 25 <filter-name>characterEncodingFilter</filter-name> 26 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 27 <init-param> 28 <param-name>encoding</param-name> 29 <param-value>UTF-8</param-value> 30 </init-param> 31 </filter> 32 <filter-mapping> 33 <filter-name>characterEncodingFilter</filter-name> 34 <url-pattern>/*</url-pattern> 35 </filter-mapping> 36 </web-app>
响应数据与结果视图
响应数据指:表现层把数据封装到JavaBean中,再转发到jsp,生成html,最后响应给客户端,浏览器显示数据的过程。
基本环境搭建:
java:controller(存放控制器类),domain(存放JavaBean)
resource: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="controller"/> 15 <!--视图解析器--> 16 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 17 <property name="prefix" value="/WEB-INF/pages/"/> 18 <property name="suffix" value=".jsp"/> 19 </bean> 20 <!--开启SpringMVC注解支持--> 21 <mvc:annotation-driven/> 22 23 </beans>
webapp:
主页面jsp文件
WEB-INF包:web.xml(配置控制器,导入SpringMVC.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 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!--导入配置文件springmvc02.xml--> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc02.xml</param-value> 15 </init-param> 16 <load-on-startup>1</load-on-startup> 17 </servlet> 18 <servlet-mapping> 19 <servlet-name>dispatcherServlet</servlet-name> 20 <!--表示发任何请求都会经过servlet--> 21 <url-pattern>/</url-pattern> 22 </servlet-mapping> 23 <!--过滤器,解决中文乱码问题--> 24 <filter> 25 <filter-name>characterEncodingFilter</filter-name> 26 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 27 <init-param> 28 <param-name>encoding</param-name> 29 <param-value>UTF-8</param-value> 30 </init-param> 31 </filter> 32 <filter-mapping> 33 <filter-name>characterEncodingFilter</filter-name> 34 <url-pattern>/*</url-pattern> 35 </filter-mapping> 36 </web-app>
pages包(存放其他jsp页面)
入门版本:返回字符串
步骤1:domain包中创建一个名为User的javabean,其中定义一些属性,并提供get和set方法。
1 package domain; 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 }
步骤2:controller包中创建一个UserController类,写上@Controller注解与@RequestMapping注解。写一个方法,在方法体中模拟从数据库中查询出user对象。
1 package controller; 2 3 import domain.User; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 8 @Controller 9 @RequestMapping("/user") 10 public class UserController { 11 @RequestMapping("/testString") 12 public String testString(Model model){ 13 System.out.println("testString方法执行了"); 14 //模拟从数据库中查询出user对象 15 User user = new User(); 16 user.setUsername("樊德馨"); 17 user.setPassword("123"); 18 user.setAge(24); 19 model.addAttribute("user",user); 20 return "success"; 21 22 } 23 }
步骤3:主页面命名为response.jsp,在其中写一个指向controller中方法的超链接。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="user/testString">testString</a> 8 </body> 9 </html>
步骤4:在pages中写一个跳转页面,命名为success.jsp,打印“执行成功”,并取出javabean中的数据。
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <h3>执行成功</h3> 8 <!--把值取出来--> 9 ${user.username} 10 ${user.password} 11 </body> 12 </html>
实际操作中,在主页面上点击超链接,跳转页面就会显示取出来的数据,如图所示:
返回值为void:
步骤1:在主页面response中重新写一个指向testVoid的超链接
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="user/testString">testString</a> 8 <br/> 9 <a href="user/testVoid">testVoid</a> 10 11 12 </body> 13 </html>
步骤2:在UserController类中新写一个testVoid方法,返回值为无返回void
1 package controller; 2 3 import domain.User; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 @Controller 14 @RequestMapping("/user") 15 public class UserController { 16 @RequestMapping("/testString") 17 public String testString(Model model){ 18 System.out.println("testString方法执行了"); 19 //模拟从数据库中查询出user对象 20 User user = new User(); 21 user.setUsername("樊德馨"); 22 user.setPassword("123"); 23 user.setAge(24); 24 model.addAttribute("user",user); 25 return "success"; 26 27 } 28 29 @RequestMapping("/testVoid") 30 public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception{ 31 System.out.println("testVoid方法执行了"); 32 //编写请求转发的程序 33 request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); 34 return; 35 36 } 37 }
也可进行重定向,直接响应,代码略。
返回值为ModelAndView:
步骤1:在主页面response中重新写一个指向testModelAndView的超链接
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="user/testString">testString</a> 8 <br/> 9 <a href="user/testVoid">testVoid</a> 10 <br/> 11 <a href="user/testModelAndView">testModelAndView</a> 12 13 14 </body> 15 </html>
步骤2:在UserController类中新写一个testVoid方法,返回值为ModelAndView
1 package controller; 2 3 import domain.User; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.servlet.ModelAndView; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import java.io.IOException; 13 14 @Controller 15 @RequestMapping("/user") 16 public class UserController { 17 @RequestMapping("/testString") 18 public String testString(Model model){ 19 System.out.println("testString方法执行了"); 20 //模拟从数据库中查询出user对象 21 User user = new User(); 22 user.setUsername("樊德馨"); 23 user.setPassword("123"); 24 user.setAge(24); 25 model.addAttribute("user",user); 26 return "success"; 27 } 28 29 @RequestMapping("/testVoid") 30 public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception{ 31 System.out.println("testVoid方法执行了"); 32 //编写请求转发的程序 33 request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); 34 return; 35 } 36 37 @RequestMapping("/testModelAndView") 38 public ModelAndView testModelAndView(){ 39 //创建ModelAndView对象 40 ModelAndView mv = new ModelAndView(); 41 System.out.println("testModelAndView方法执行了"); 42 //模拟从数据库中查询出user对象 43 User user = new User(); 44 user.setUsername("樊德馨"); 45 user.setPassword("456"); 46 user.setAge(24); 47 mv.addObject("user",user); 48 mv.setViewName("success"); 49 return mv; 50 51 } 52 }
其实,入门版本中的返回String类型本质上就是ModelAndView。
还可以用forward,redict关键字进行页面跳转,代码略。
上传文件
搭建环境的过程与之前类似,略。
步骤1: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>org.example</groupId> 8 <artifactId>SpringMVC03</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>springMVC03 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.8</maven.compiler.source> 19 <maven.compiler.target>1.8</maven.compiler.target> 20 <spring.version>5.0.2.RELEASE</spring.version> 21 </properties> 22 23 <dependencies> 24 <dependency> 25 <groupId>org.springframework</groupId> 26 <artifactId>spring-context</artifactId> 27 <version>${spring.version}</version> 28 </dependency> 29 30 <dependency> 31 <groupId>org.springframework</groupId> 32 <artifactId>spring-web</artifactId> 33 <version>${spring.version}</version> 34 </dependency> 35 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-webmvc</artifactId> 39 <version>${spring.version}</version> 40 </dependency> 41 42 <dependency> 43 <groupId>javax.servlet</groupId> 44 <artifactId>servlet-api</artifactId> 45 <version>2.5</version> 46 <scope>provided</scope> 47 </dependency> 48 49 <dependency> 50 <groupId>javax.servlet.jsp</groupId> 51 <artifactId>jsp-api</artifactId> 52 <version>2.0</version> 53 <scope>provided</scope> 54 </dependency> 55 56 <dependency> 57 <groupId>commons-fileupload</groupId> 58 <artifactId>commons-fileupload</artifactId> 59 <version>1.3.1</version> 60 </dependency> 61 <dependency> 62 <groupId>commons-io</groupId> 63 <artifactId>commons-io</artifactId> 64 <version>2.4</version> 65 </dependency> 66 67 <dependency> 68 <groupId>com.sun.jersey</groupId> 69 <artifactId>jersey-core</artifactId> 70 <version>1.18.1</version> 71 </dependency> 72 <dependency> 73 <groupId>com.sun.jersey</groupId> 74 <artifactId>jersey-client</artifactId> 75 <version>1.18.1</version> 76 </dependency> 77 78 </dependencies> 79 80 <build> 81 <finalName>springMVC03</finalName> 82 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 83 <plugins> 84 <plugin> 85 <artifactId>maven-clean-plugin</artifactId> 86 <version>3.1.0</version> 87 </plugin> 88 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 89 <plugin> 90 <artifactId>maven-resources-plugin</artifactId> 91 <version>3.0.2</version> 92 </plugin> 93 <plugin> 94 <artifactId>maven-compiler-plugin</artifactId> 95 <version>3.8.0</version> 96 </plugin> 97 <plugin> 98 <artifactId>maven-surefire-plugin</artifactId> 99 <version>2.22.1</version> 100 </plugin> 101 <plugin> 102 <artifactId>maven-war-plugin</artifactId> 103 <version>3.2.2</version> 104 </plugin> 105 <plugin> 106 <artifactId>maven-install-plugin</artifactId> 107 <version>2.5.2</version> 108 </plugin> 109 <plugin> 110 <artifactId>maven-deploy-plugin</artifactId> 111 <version>2.8.2</version> 112 </plugin> 113 </plugins> 114 </pluginManagement> 115 </build> 116 </project>
步骤2:index.jsp中写一个选择文件的input标签,再写一个上传按钮
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 8 <h3>文件上传</h3> 9 <form action="user/fileUpload01" method="post" enctype="multipart/form-data"> 10 选择文件:<input type="file" name="upload"> 11 <br/> 12 <input type="submit" value="上传 "/> 13 </form> 14 15 16 </body> 17 </html>
步骤3:在UserController中创建接收文件的路径,判断路径是否存在,获取上传文件的名称,并将文件名唯一化
1 package controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.multipart.MultipartFile; 6 7 import javax.servlet.http.HttpServletRequest; 8 import java.io.File; 9 import java.util.UUID; 10 11 @Controller 12 @RequestMapping("/user") 13 public class UserController { 14 @RequestMapping("/fileUpload01") 15 public String fileUpload01(HttpServletRequest request, MultipartFile upload) throws Exception { 16 System.out.println("文件上传"); 17 //创建接收文件的路径 18 String path = request.getSession().getServletContext().getRealPath("/uploads"); 19 File file = new File(path); 20 //判断路径是否存在 21 if(!file.exists()){ 22 file.mkdirs(); 23 } 24 //获取上传文件的名称,并将文件名唯一化(一串唯一的随机生成字符串_上传文件名) 25 String filename = upload.getOriginalFilename(); 26 String uuid = UUID.randomUUID().toString().replace("_","").toUpperCase(); 27 filename = uuid+"_"+filename; 28 //上传文件 29 upload.transferTo(new File(file,filename)); 30 31 return "success"; 32 } 33 34 }
异常处理
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。
实现思路:
1.自定义一个异常处理器,实现HandlerExceptionResolver接口,跳转至指定的error,jsp
2.写一个error.jsp,打印异常处理器给出的异常原因
2.写一个异常类,继承Exception类,给一个message属性以及它的getters&setters,构造方法。
3.在Usercontroller类中模拟异常,在catch中throw new 异常处理器对象
4.在springmvc.xml中写一个bean,配置异常处理器。
拦截器
Spring MVC 的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。 用户可以自己定义一些拦截器来实现特定的功能。
拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能用。
拦截器它只会拦截访问的控制器方法,如果访问的是jsp,html,css,image或者js是不会进行拦截的。 它也是AOP思想的具体应用。
我们要想自定义拦截器, 要求必须实现:HandlerInterceptor接口。