SpringMVC
MVC设计模式介绍
- MVC全名是Model View Controller 模型视图控制器,每个部分各司其职。
-
- Model:数据模型,JavaBean的类,用来进行数据封装。
- View:指JSP、HTML用来展示数据给用户
-
- Controller:用来接收用户的请求,整个流程的控制器。用来进行数据校验等
MVC全名是 Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面 显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于 映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
Model-View-Controller 这种设计模式的最主要的目的就是解耦合又叫松 耦合(不一样的功能,最好占用不同的模块,和别的模块之间的直接关系越少越好,越少越利于二次开发、扩展和维护)。
Model 层与数据库直接交互,负责读写数据;
View 层直接与用户交互,负责向用户展示数据(使用不同的样式)或者接收用户的输入;
Controller 层则根据 View 层的用户输入调用Model 层的逻辑读写相关数据,并将数据选择适当的视图模板生成对应的 View 层展示效果。
根据 MVC 模式开发的程序结构清晰易于维护,如果需要修改数据的展示样式时,只需要修改View 层对应的代码就可以了,比起不使用 MVC 的程序,在改动时被牵一发动全身恐惧所支配,实在是方便了不少。
3 SpringMVC简介
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的Spring MVC框架或集成其他MVC开发框架,如Struts1(现在一般不用),Struts 2(一般老项目使用)等。
4 请求流程
- 用户发送请求至前端控制器DispatcherServlet
- DispatcherServlet收到请求调用HandlerMapping处理器映射器。
- 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
- DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
- 执行处理器(Controller,也叫后端控制器)。
- Controller执行完成返回ModelAndView
- HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
- DispatcherServlet将ModelAndView传给ViewReslover视图解析器
- ViewReslover解析后返回具体View
- DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
- DispatcherServlet响应用户
以上流程是以DispatcherServlet为核心轴,并且DispatcherServlet就是一个Servlet
5 XML方式
5.1 创建项目并导包
创建web项目,已经非常熟悉,不再多说
需要导入的包
5.2 配置文件
5.2.1 web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC_01_Basic</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <!-- 设置所有请求拦截到分发器 第一种 如果SpringMVC的配置文件,和web.xml在同一个目录 比如 MVC配置文件名字叫 basic-servlet.xml 只需要把servlet-name的值 设置为basic就可以, 但是 MVC配置文件的名字必须是xxx-servlet.xml的格式 --> <servlet-name>basic</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定配置文件--> <!-- <init-param> --> <!-- <param-name>contextConfigLocation</param-name> --> <!-- 可以放在任何地方 --> <!-- <param-value>/a/b/c/d/xxxxxxxxx.xml</param-value> --> <!-- 放在src下 --> <!-- <param-value>classpath:xxxxxxxxx.xml</param-value> --> <!-- </init-param> --> <!-- 项目启动就会加载这个servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>basic</servlet-name> <url-pattern>/</url-pattern> <!-- /* 会拦截jsp文件 / 不会拦截jsp --> </servlet-mapping> </web-app>
5.2.2 basic-servlet.xml
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 使用XML进行映射 MVC框架基本两个点 1 url怎么映射进去进行处理 2 处理完如何找到视图 --> <!-- 处理映射器配置--> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- 创建映射,配置映射器,name必须是 / 打头--> <bean name="/w" class="com.tledu.controller.XmlMappingController"/> <!-- 视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
5.3 控制器类
package com.tledu.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class XmlMappingController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { System.out.println("Welcome~"); return new ModelAndView("welcome"); } }
5.4 jsp页面
视图解析器这里,我们指定了文件的目录和后缀
当controller返回了welcome的时候 就会去找WEB-INF/jsp/welcome.jsp
需要创建对应的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 欢迎来到天亮教育 </body> </html>
5.5 运行测试
运行web程序,浏览器输入
http://localhost:8080/SpringMVC_demo01/w
5.6 小结
- 创建项目,引入依赖
- 配置web.xml
-
- 因为现在,所有请求,我们都希望通过spring mvc进行管理
- 配置servlet
-
-
- name
- class:对应的路径(DispatchServlet)
-
-
- 配置了servletMapping
-
-
- servlet-name: 对应到上面的名字
- 地址 /
-
- 配置Spring
-
- 文件的位置要和web.xml同级
- 文件名字和servlet中servlet的名字对应上
-
-
- servlet名字-servlet.xml
-
-
- 配置MappingHandle的实例
-
-
- 配置映射关系
-
-
-
- 配置 视图解析器
-
- 实现Controller
-
- extends AbstractController
- 实现一个抽象方法
-
-
- 返回一个ModelAndView
-
6 注解方式
6.1 配置文件
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <context:component-scan base-package="com.tledu.controller"/> <!-- 这是该注解的主要功能,添加< mvc:annotation-driven/>注解后,容器中会<自动注册HandlerMapping与HandlerAdapter 两个bean。省去手动注册HandlerMapping和HandlerAdapter的步骤。 当配置了< mvc:annotation-driven/>后,Spring就知道了我们启用注解驱动。然后Spring通过< context:component-scan/>标签的配置,会自动为我们将扫描到的@Component,@Controller,@Service,@Repository等注解标记的组件注册到工厂中,来处理我们的请求。 HandlerMapping的实现类的作用:将请求映射到带@RequestMapping注释的控制器方法,将URL路径映射到控制器bean名称。 HandlerAdapter的实现类的作用:实现类RequestMappingHandlerAdapter,处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值。 --> <mvc:annotation-driven /> <!--视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"value="/WEB-INF/jsp/"/> <property name="suffix"value=".jsp"/> </bean> </beans>
- 配置包扫描,需要能把controller放到spring容器管理
- 添加一个Controller类,并加上Controller注解
- 类上加@RequestMapping(""),配置地址和controller的映射关系
- 在方法上加@RequestMapping(""),配置地址和方法的映射关系
- 执行方法,并返回一个字符串,这个字符串就是view-name
6.2 常用注解
1. @Controller
使用Controller注解之后,在方法上可以通过return的jsp或者html页面的名字,通过视图解析器,就能跳转到指定页面
如果没有Controller注解,这个类中的方法是不会被请求过去的
所对应的层也是controller层,表现层
2. @RestController
RestController注解相当于Controller和ResponseBody一起使用
这个类中的方法可以被请求过来,但是方法中无法jsp和html页面,视图解析器就不会起到作用,返回的内容就是return后面的内容
3. @RequestMapping
是Spring Web应用中最常用到的注解之一,这个注解会将http请求映射到MVC和Controller控制器的处理方法上
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
4. @RequestBody
@RequestBody 主要用于接收前端通过 请求体 传递给后端的JSON字符串中的数据
GET方式无请求体,所以使用@RequestBody的时候不能使用GET方式,而应该使用POST形式
jsp页面 <script> var userList = new Array(); userList.push(username:"beijing"),age:30); $.ajax({ url:"${pageContext.request.contextPath}/bike", type:"post", data:JSON.stringify(userList), contentType:"application/json;charset=utf-8", success:function(result){ alert(result); } }) </script> controller @RequestMapping("/bike") @ResponseBody public String bike(@RequestBody List<User> userList){ for(User user:userList){ System.out.printn(user.getUserName()); } return "ok"; }
5. @RequestParam
用于接收前端传递过来的url中的参数(key=value)的形式
主要用于接收前后端key不一致的时候,使用@RequestParm来指定获取
@RequestMapping("/test") public String test(@RequestParam(value="name",required=false,default="tom")String name)
6. @PathVaraible
@PathVaraible主要用于获取url请求中的动态参数的
如
@RequestMapping("/delete/{id}") public String delete(@PathVaraible(“id”) int id){}
当RequestMapping中需要动态传递过来参数的时候,需要通过@PathVaraible来接收
7. @ResponseBody
如果方法需要返回JSON或者XML或者自定义内容到页面中去,就需要再方法上加上ResponseBody,这个时候,返回的数据就会不被视图解析器所解析
@RequestMapping("/login") @ResponseBody public User login(User user){ return user; } User字段:userName pwd; 那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}' 效果等同于如下代码: @RequestMapping("/login") public void login(User user, HttpServletResponse response){ //通过response对象输出指定格式的数据 response.getWriter.write(JSONObject.fromObject(user).toString()); }
8. SessionAttributes注解
用于多次执行控制器方法间的参数,可以通过value指定存入属性的名字
若希望在多个请求之间共用数据,则可以在控制器类上标注一个 @SessionAttributes,配置需要在session中存放的数据范围,Spring MVC将存放在model中对应的数据暂存到
HttpSession 中。
@SessionAttributes只能使用在类定义上。
@SessionAttributes 除了可以通过属性名指定需要放到会 话中的属性外,还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中 例如:
@SessionAttributes(types=User.class)会将model中所有类型为 User的属性添加到会话中。
@SessionAttributes(value={“user1”, “user2”}) 会将model中属性名为user1和user2的属性添加到会话中。
@SessionAttributes(types={User.class, Dept.class}) 会将model中所有类型为 User和Dept的属性添加到会话中。
@SessionAttributes(value={“user1”,“user2”},types={Dept.class})会将model中属性名为user1和user2以及类型为Dept的属性添加到会话中。
value和type之间是并集关系
比如 :
package com.tledu.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; @Controller @RequestMapping(path="/hello") @SessionAttributes(value= {"username","password","age"},types= {String.class,Integer.class}) public class HelloController { /** * 向session中存入值 * @return */ @RequestMapping(path="/save") public String save(Model model) { System.out.println("向session域中保存数据"); model.addAttribute("username", "root"); model.addAttribute("password", "123"); model.addAttribute("age", 20); return "success"; } /** * 从session中获取值 * @return */ @RequestMapping(path="/find") public String find(ModelMap modelMap) { 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"; } /** * 清除值 * @return */ @RequestMapping(path="/delete") public String delete(SessionStatus status) { status.setComplete(); return "success"; } }
作用
可以多个请求之间共享数据,作用域是session作用域
怎么用
@SessionAttributes注解声明有哪些数据需要放在SessionAttributes中
通过model.addAttribute进行添加
通过model.getAttribute获取
通过SessionStatus status中status.setComplete();进行清除
6.3 控制器类和参数绑定
6.3.1 RequestMapping详解
1. RequestMapping注解的作用是建立请求URL和处理方法之间的对应关系
2. RequestMapping注解可以作用在方法和类上
-
- 作用在类上:第一级的访问目录
- 作用在方法上:第二级的访问目录
-
- 细节:路径可以不编写 / 表示应用的根目录开始
- 细节:${ pageContext.request.contextPath }也可以省略不写,但是路径上不能写 /
3. RequestMapping的属性
-
- path 指定请求路径的url
- value value属性和path属性是一样的
-
- method 指定该方法的请求方式
-
-
- GetMapping
- PostMapping
-
-
-
- PutMapping
- DeleteMapping
-
@RequestMapping(value = "/list" , method = RequestMethod.POST) public BaseDTO list(@PathVariable String communityId) { // TODO }
-
- consumes :指定处理请求的 提交内容类型 (Content-Type),例如 application/json, text/html
//方法仅处理request Content-Type为“application/json”类型的请求 @RequestMapping(value = "/list" , method = RequestMethod.POST,consumes="application/json") public void list(@PathVariable String communityId) { // TODO }
-
- produces: 指定 返回的内容类型 ,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
@RequestMapping(value = "/list" , method = RequestMethod.POST,produces="application/json") public JSONObject list(@PathVariable String communityId) { JSONObject object = new JSONObject(); object.put("communityId",communityId); return object; }
-
- params: 指定request中必须包含某些参数值时,才让该方法处理。
//设定必须包含username 和age两个参数,且age参数不为10 (可以有多个参数) @RequestMapping(value = "/list" , method = RequestMethod.POST,params = { "username","age!=10" }) public JSONObject list(@PathVariable String communityId) { JSONObject object = new JSONObject(); object.put("communityId",communityId); return object; }
-
- headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
//仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求; @RequestMapping(value = "/list" , method = RequestMethod.POST,headers="Referer=http://www.ifeng.com/") public JSONObject list(@PathVariable String communityId) { JSONObject object = new JSONObject(); object.put("communityId",communityId); return object; }
6.3.2 参数绑定说明
6.3.2.1. 请求参数的绑定说明
1. 1 绑定机制
1. 表单提交的数据都是k=v格式的username=haha&password=123
2. SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器中方法的参数进行绑定的
3. 要求:提交表单的name和参数的名称是相同的
2.1 支持的数据类型
1. 基本数据类型和字符串类型
2. 实体类型(JavaBean)
3.集合数据类型(List、map集合等)
6.3.2.2. 基本数据类型和字符串类型
- 提交表单的name和参数的名称是相同的
- 区分大小写
- 如果名称不相同可以通过@RequestParam("user"),指定参数名字
- 如果参数是必传的@RequestParam(required = true)
6.3.2.3. 实体类型(JavaBean)
- 提交表单的name和JavaBean中的属性名称需要一致
- 如果一个JavaBean类中包含其他的引用类型,那么表单的name属性需要编写成:对象.属性 例如:address.name
6.3.2.4 给集合属性数据封装
- 表单提提交
-
- list:多个同名属性设置list
- 获取通过json的方式进行提交
-
- 需要设置注解@RequestBody
6.3.2.5 请求参数中文乱码的解决
1. 在web.xml中配置Spring提供的过滤器类
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 指定字符集 --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
6.3.2.6 自定义类型转换器
1. 表单提交的任何数据类型全部都是字符串类型,但是后台定义Integer类型,数据也可以封装上,说明Spring框架内部会默认进行数据类型转换。
2. 如果想自定义数据类型转换,可以实现Converter的接口
1.自定义类型转换器
package com.tledu.spring_mvc_basic.utils; import org.springframework.core.convert.converter.Converter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateConverter implements Converter<String, Date> { @Override public Date convert(String source) { // 判断 if(source == null) { throw new RuntimeException("参数不能为空"); } try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 解析字符串 Date date = df.parse(source); return date; } catch (Exception e) { throw new RuntimeException("类型转换错误"); } } }
2. 注册自定义类型转换器,在springmvc.xml配置文件中编写配置
<!-- 注册自定义类型转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.tledu.utils.StringToDateConverter"/> </set> </property> </bean> <!-- 开启Spring对MVC注解的支持 --> <mvc:annotation-driven conversion-service="conversionService"/>
json里日期参数格式化可以使用@JsonFormat(pattern = "yyyy/MM/dd")注解进行配置
6.3.2.7 在控制器中使用原生的ServletAPI对象
- 只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象
- 通过注入的方式也可以获取
6.3.3 参数绑定使用
5 为了方便向视图层传值,提供了 Model 专门向视图层传递数据
请求为 http://localhost:8080/SpringMVC_01_Basic/hello?username=root
@RequestMapping("/hello") public String hello(String username,Model model) { // 键值对,页面可以通过username获取对应的值 model.addAttribute("username", "Hello : "+username); // 参数是值,页面需要根据值的类型的首字母小写获取 model.addAttribute(username); // 如果 类名前两个字母都是大写,就不会把首字母转换为小写了 return "hello"; } <body> Hello~ <br> ${username } <br> ${string } </body>
6 多个Url映射到同一个方法上
请求为 http://localhost:8080/SpringMVC_01_Basic/hello?username=root
@RequestMapping({"/hello","/h","/hi"}) public String hello(String username,Model model) { model.addAttribute("username", "Hello : "+username); return "hello"; }
这时候/hello 和/h 以及 /hi 请求 都会来执行这个方法
知识点补充
import
import resource="classpath:applicationContext.xml" />
可以通过 导入别的配置文件
重定向
返回"redirect:地址"。就可以重定向到指定地址
怎么给前端返回json数据
加入接口不希望跳转界面,希望返回一个json格式的数据,可以在这个接口上加@ResponseBody
如果我们希望一个Controller所有的方法都返回json格式的数据,这个时候可以使用@RestController代替@Controller
1、地址参数
在resful风格的接口中,会直接通过地址进行参数的传递,如,在进行详情查询的时候,我们需要传递参数id,这个时候id这个参数就可以放在地址中进行传递。
@GetMapping("/detail/{id}/{name}") public String userDetailPage(@PathVariable Integer id, @PathVariable("name") String name) { System.out.println(id); System.out.println(name); return "user-detail"; }
使用步骤:
- 定义参数
-
- 会在地址上通过{参数名}指定参数
- 获取参数
-
- 请求方法的参数中加上@PathVariable
- 传递参数,参数直接写在url里面
-
- /detail/id参数/name参数