一、目录结构
1、目录
2、原理图
3、知识点
1 一、执行流程: 2 1. 当启动Tomcat服务器的时候,因为配置了load-on-startup标签,所以会创建DispatcherServlet对象,就会加载springmvc.xml配置文件 3 2. 开启了注解扫描,那么HelloController对象就会被创建 4 3. 从index.jsp发送请求,请求会先到达DispatcherServlet核心控制器,根据配置@RequestMapping注解找到执行的具体方法 5 4. 根据执行方法的返回值,再根据配置的视图解析器,去指定的目录下查找指定名称的JSP文件 6 5. Tomcat服务器渲染页面,做出响应 7 二、组件分析:在SpringMVC的各个组件中,处理器映射器、处理器适配器、视图解析器称为SpringMVC的三大组件。 8 1. 前端控制器(DispatcherServlet):用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心, 9 由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。 10 2. 处理器映射器(HandlerMapping):HandlerMapping负责根据用户请求找到Handler即处理器,SpringMVC提供了不同的映射器实现 11 不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。 12 3. 处理器(Handler):开发中要编写的具体业务控制器。由DispatcherServlet把用户请求转发到Handler。由Handler对具体的用户请求进行处理。 13 4. 处理器适配器(HandlAdapter):通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行 14 执行。 15 5. 视图解析器(View Resolver):View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名 16 即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。 17 6. 视图(View)
二、代码
1、HelloController
package cn.bijian.controller; import cn.bijian.model.Account; import cn.bijian.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.Map; @Controller @RequestMapping("/param") @SessionAttributes(value = {"username","password","age"},types = {String.class,Integer.class}) public class HelloController { @RequestMapping(value = "/hello",method = RequestMethod.GET) public String sayHello(){ System.out.println("Hello SpringMVC!"); return "success"; } /* 基本类型 */ @RequestMapping("/findAccount") public String findAccount(Integer accountId,String accountName) { System.out.println("findAccount......"+accountId+","+accountName); return "success"; } /* 封装到JavaBean的类当中 */ @RequestMapping("/saveAccount") public String saveAccount(Account account){ System.out.println("saveAccount......"); System.out.println(account); return "success"; } /* 自定义类型转换器 */ @RequestMapping("/saveUser") public String saveUser(User user){ System.out.println("saveUser......"); System.out.println(user); return "success"; } /* 原生的ServletAPI */ @RequestMapping("/testServlet") public String testServlet(HttpServletRequest request, HttpServletResponse response, HttpSession session){ System.out.println("testServlet......"); System.out.println(request); System.out.println(response); System.out.println(session); return "success"; } /* RequestParam:把请求中指定名称的参数给控制器中的形参赋值。 属性: value:请求参数中的名称。 required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错. */ @RequestMapping("/testRequestParam") public String testRequestParam(@RequestParam("name") String username, @RequestParam(value = "age",required = false) Integer age){ System.out.println("testRequestParam......"); System.out.println(username+"-"+age); return "success"; } /* RequestBody:用于获取请求体内容。直接使用得到是key=value&key=value...结构的数据。get请求方式不适用。 属性:required:是否必须有请求体。默认值是:true。当取值为 true 时,get请求方式会报错。如果取值为false,get请求得到是null。 */ @RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody(required = false) String body){ System.out.println("testRequestBody......"); System.out.println(body); return "success"; } /* PathVaribale:用于绑定url中的占位符。例如:请求url中/delete/{id},这个{id}就是url占位符。 属性: value:用于指定url中占位符名称。 required:是否必须提供占位符。 */ @RequestMapping("/testPathVaribale/{id}") public String testPathVaribale(@PathVariable(value = "id",required = false) Integer id){ System.out.println("testPathVaribale......"); System.out.println(id); return "success"; } /* RequestHeader:用于获取请求消息头。 属性: value:提供消息头名称 required:是否必须有此消息头 */ @RequestMapping("/testRequestHeader") public String testRequestHeader(@RequestHeader(value = "Accept") String header){ System.out.println("testRequestHeader......"); System.out.println(header); return "success"; } /* CookieValue:用于获取请求消息头。 属性: value:指定cookie的名称。 required:是否必须有此cookie。 */ @RequestMapping("/testCookieValue") public String testCookieValue(@CookieValue(value="JSESSIONID",required = false) String cookie){ System.out.println("testCookieValue......"); System.out.println(cookie); return "success"; } /* ModelAttribute: 出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。 出现在参数上,获取指定的数据给参数赋值。 属性: value:用于获取数据的key。key可以是POJO的属性名称,也可以是map结构的key。 */ @ModelAttribute public void showModel(User user){ System.out.println("执行了showModel方法"+user.getUname()); } @RequestMapping("/testModelAttribute") public String testModelAttribute(User user){ System.out.println("testModelAttribute......"); System.out.println(user.getUname()); return "success"; } @ModelAttribute public void showModel2(Map<String,User> map){ System.out.println("执行了showModel2方法"); User user = new User(); user.setUname("aaa"); user.setAge(13); user.setDate(new Date()); map.put("abc",user); } @RequestMapping("/testModelAttribute2") public String testModelAttribute2(@ModelAttribute(value = "abc") User user){ System.out.println("testModelAttribute2......"); System.out.println(user); return "success"; } /* SessionAttribute:用于多次执行控制器方法间的参数共享。 属性: value:用于指定存入的属性名称 type:用于指定存入的数据类型。 */ @RequestMapping("/save") public String save(Model model){ System.out.println("向session域中保存数据......"); model.addAttribute("username","root"); model.addAttribute("password","123456"); model.addAttribute("age",24); return "success"; } @RequestMapping("/find") public String find(ModelMap modelMap){ System.out.println("向session域中读取数据......"); String username = (String) modelMap.get("username"); String password = (String) modelMap.get("password"); Integer age = (Integer) modelMap.get("age"); System.out.println(username+"-"+password+"-"+age); return "success"; } @RequestMapping("/delete") public String delete(SessionStatus status){ System.out.println("清除session域中数据......"); status.setComplete(); return "success"; } }
2、Account
1 package cn.bijian.model; 2 3 import java.io.Serializable; 4 import java.util.List; 5 6 public class Account implements Serializable { 7 private String username; 8 private String password; 9 private Double money; 10 11 private User user; 12 private List<User> users; 13 14 public String getUsername() { 15 return username; 16 } 17 18 public void setUsername(String username) { 19 this.username = username; 20 } 21 22 public String getPassword() { 23 return password; 24 } 25 26 public void setPassword(String password) { 27 this.password = password; 28 } 29 30 public Double getMoney() { 31 return money; 32 } 33 34 public void setMoney(Double money) { 35 this.money = money; 36 } 37 38 public User getUser() { 39 return user; 40 } 41 42 public void setUser(User user) { 43 this.user = user; 44 } 45 46 public List<User> getUsers() { 47 return users; 48 } 49 50 public void setUsers(List<User> users) { 51 this.users = users; 52 } 53 54 @Override 55 public String toString() { 56 return "Account{" + 57 "username='" + username + '\'' + 58 ", password='" + password + '\'' + 59 ", money=" + money + 60 ", user=" + user + 61 ", users=" + users + 62 '}'; 63 } 64 }
3、User
1 package cn.bijian.model; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 6 public class User implements Serializable { 7 private String uname; 8 private Integer age; 9 private Date date; 10 11 public String getUname() { 12 return uname; 13 } 14 15 public void setUname(String uname) { 16 this.uname = uname; 17 } 18 19 public Integer getAge() { 20 return age; 21 } 22 23 public void setAge(Integer age) { 24 this.age = age; 25 } 26 27 public Date getDate() { 28 return date; 29 } 30 31 public void setDate(Date date) { 32 this.date = date; 33 } 34 35 @Override 36 public String toString() { 37 return "User{" + 38 "uname='" + uname + '\'' + 39 ", age=" + age + 40 ", date=" + date + 41 '}'; 42 } 43 }
4、StringToDateConverter
1 package cn.bijian.utils; 2 3 import org.springframework.core.convert.converter.Converter; 4 5 import java.text.DateFormat; 6 import java.text.ParseException; 7 import java.text.SimpleDateFormat; 8 import java.util.Date; 9 10 /* 11 字符串转换为日期格式 12 */ 13 public class StringToDateConverter implements Converter<String,Date> { 14 15 @Override 16 public Date convert(String source) { 17 if (source==null){ 18 throw new RuntimeException("参数不能为空!"); 19 } 20 try { 21 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 22 Date date = dateFormat.parse(source); 23 return date; 24 } catch (Exception e) { 25 throw new RuntimeException("类型转换错误!"); 26 } 27 } 28 }
5、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 <!--自定义类型转换器--> 22 <!--1、配置类型转换器工厂--> 23 <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> 24 <!--2、给工厂注入一个新的类型转换器--> 25 <property name="converters"> 26 <set> 27 <!--3、配置自定义类型转换器--> 28 <bean class="cn.bijian.utils.StringToDateConverter"></bean> 29 </set> 30 </property> 31 </bean> 32 <!--配置spring开启注解MVC的支持--> 33 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> 34 <!--使用<mvc:annotation-driven> 自动加载RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter(处理适配器)--> 35 36 </beans>
6、success
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <html> 3 <head> 4 <title>入门</title> 5 </head> 6 <body> 7 <h3>入门成功!</h3> 8 ${sessionScope} 9 </body> 10 </html>
7、web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE web-app PUBLIC 3 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 4 "http://java.sun.com/dtd/web-app_2_3.dtd" > 5 6 <web-app> 7 <display-name>Archetype Created Web Application</display-name> 8 <!-- 配置过滤器--> 9 <filter> 10 <filter-name>characterEncodingFilter</filter-name> 11 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 12 <init-param> 13 <param-name>encoding</param-name> 14 <param-value>utf-8</param-value> 15 </init-param> 16 </filter> 17 <filter-mapping> 18 <filter-name>characterEncodingFilter</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 22 <!--SpringMVC的核心配置器--> 23 <servlet> 24 <servlet-name>dispatcherServlet</servlet-name> 25 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 26 <!--配置Servlet的初始化参数,读取springmvc的配置文件,创建Spring容器--> 27 <init-param> 28 <param-name>contextConfigLocation</param-name> 29 <param-value>classpath:SpringMVC.xml</param-value> 30 </init-param> 31 <!--配置servlet启动时加载对象--> 32 <load-on-startup>1</load-on-startup> 33 </servlet> 34 <servlet-mapping> 35 <servlet-name>dispatcherServlet</servlet-name> 36 <url-pattern>/</url-pattern> 37 </servlet-mapping> 38 39 </web-app>
8、index
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <body> 4 <a href="param/hello">hello</a> 5 6 <a href="param/findAccount?accountId=10&accountName=zhangsan">findAccount</a> 7 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.uname"><br/> 13 用户年龄:<input type="text" name="user.age"><br/> 14 用户1姓名:<input type="text" name="users[0].uname"><br/> 15 用户1年龄:<input type="text" name="users[0].age"><br/> 16 用户2姓名:<input type="text" name="users[1].uname"><br/> 17 用户2年龄:<input type="text" name="users[1].age"><br/> 18 <input type="submit" value="提交"><br/> 19 </form> 20 21 <form action="param/saveUser" method="post"> 22 23 用户姓名:<input type="text" name="uname"><br/> 24 用户年龄:<input type="text" name="age"><br/> 25 用户生日:<input type="text" name="date"><br/> 26 <input type="submit" value="提交"><br/> 27 </form> 28 29 <a href="param/testServlet">testServlet</a> 30 31 <a href="param/testRequestParam?name=aaa">testRequestParam</a> 32 33 <form action="param/testRequestBody" method="post"> 34 35 姓名:<input type="text" name="uname"><br/> 36 年龄:<input type="text" name="age"><br/> 37 生日:<input type="text" name="date"><br/> 38 <input type="submit" value="提交"><br/> 39 </form> 40 41 <a href="param/testPathVaribale/100">testPathVaribale</a> 42 43 <a href="param/testRequestHeader">testRequestHeader</a> 44 45 <a href="param/testCookieValue">testCookieValue</a> 46 47 <a href="param/testModelAttribute?uname=aaa">testModelAttribute</a> 48 49 <a href="param/testModelAttribute2">testModelAttribute2</a> 50 51 <a href="param/save">save</a> 52 <a href="param/find">find</a> 53 <a href="param/delete">delete</a> 54 55 </body> 56 </html>
9、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_1</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 13 <properties> 14 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 15 <maven.compiler.source>1.7</maven.compiler.source> 16 <maven.compiler.target>1.7</maven.compiler.target> 17 </properties> 18 19 <dependencies> 20 <dependency> 21 <groupId>junit</groupId> 22 <artifactId>junit</artifactId> 23 <version>4.11</version> 24 <scope>test</scope> 25 </dependency> 26 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-context</artifactId> 30 <version>5.0.3.RELEASE</version> 31 </dependency> 32 33 <dependency> 34 <groupId>org.springframework</groupId> 35 <artifactId>spring-web</artifactId> 36 <version>5.0.3.RELEASE</version> 37 </dependency> 38 39 <dependency> 40 <groupId>org.springframework</groupId> 41 <artifactId>spring-webmvc</artifactId> 42 <version>5.0.4.RELEASE</version> 43 </dependency> 44 45 <dependency> 46 <groupId>javax.servlet</groupId> 47 <artifactId>servlet-api</artifactId> 48 <version>2.5</version> 49 </dependency> 50 51 <dependency> 52 <groupId>javax.servlet</groupId> 53 <artifactId>jsp-api</artifactId> 54 <version>2.0</version> 55 </dependency> 56 </dependencies> 57 58 <build> 59 <finalName>SpringMVC_review_1</finalName> 60 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 61 <plugins> 62 <plugin> 63 <artifactId>maven-clean-plugin</artifactId> 64 <version>3.1.0</version> 65 </plugin> 66 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 67 <plugin> 68 <artifactId>maven-resources-plugin</artifactId> 69 <version>3.0.2</version> 70 </plugin> 71 <plugin> 72 <artifactId>maven-compiler-plugin</artifactId> 73 <version>3.8.0</version> 74 </plugin> 75 <plugin> 76 <artifactId>maven-surefire-plugin</artifactId> 77 <version>2.22.1</version> 78 </plugin> 79 <plugin> 80 <artifactId>maven-war-plugin</artifactId> 81 <version>3.2.2</version> 82 </plugin> 83 <plugin> 84 <artifactId>maven-install-plugin</artifactId> 85 <version>2.5.2</version> 86 </plugin> 87 <plugin> 88 <artifactId>maven-deploy-plugin</artifactId> 89 <version>2.8.2</version> 90 </plugin> 91 </plugins> 92 </pluginManagement> 93 </build> 94 </project>