SpringMVC基本内容
MVC三大组件:处理器映射器、处理器适配器、视图解析器。
SpringMVC的特点
- 轻量级、简单易学
- 高效,基于请求响应的MVC框架
- 与Spring兼容性好
- 约定优于配置
- 功能强大:RESTful风格、数据验证、格式化、本地化、主题等。
- 简洁灵活
SpringMVC的组件
-
DispatcherServlet表示前置控制器,是整个springMVC的控制中心。用户发出请求,DispatcherServlet 接收请求并拦截请求。它的存在降低了组件之间的耦合性。
-
HandlerMapping(处理器映射器)负责根据用户请求找到Handler(处理器),SpringMVC提供了不同的映射器实现不同的映射方式。例如:配置文件方式,实现接口方式,注解方式。
-
Handler (处理器)是我们开发要编写的具体业务控制器,即Controller。由DispatcherServlet把用户的请求转发到Handler 对具体的用户请求进行处理。
-
HandlerAdapter (处理器适配器),对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。(把Controller 转换为适配器,都可以去执行。)
-
View Resolver (视图解析器),负责将处理结果生成view视图。首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成view视图对象,最后对view进行渲染,将处理结果通过页面展示给用户。(跳转到某某页面)
-View (视图)。页面显示数据,渲染。
MVC 内容说明
SpringMVC 环境搭建
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置解决中文乱码的过滤器-->
<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>
<!--配置前端控制器-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- springmvc-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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包-->
<context:component-scan base-package="com.wei.controller" />
<!--让springMVC 不处理静态资源 .css .js . html .mp3 等等 -->
<mvc:default-servlet-handler />
<!--
告诉前端控制器,哪些资源不拦截
<mvc:resources mapping="/js/**" location="/js/" ></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/" ></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/" ></mvc:resources>
-->
<!--支持MVC注解驱动 并且解决json乱码问题-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller 基本写法
package com.wei.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("hello")
public class HelloController {
@RequestMapping("/h1")
public String hello1(Model model){
model.addAttribute("msg","hello,mvc1");
return "hello";
}
@RequestMapping("h2")
public ModelAndView hello2(){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg", "hello,mvc2");
return mv;
}
}
请求参数的绑定
- 自动封装到javaBean,需要表单属性的name对应实体类属性。
@RequestMapping(value = "/saveUser" )
public String testSaveUser(User user){
System.out.println(user);
return "success";
}
- 包含引用对象,封装Account
public class Account implements Serializable {
private String username;
private String password;
private Double money;
private User user;
}
<form action="param/testParam" METHOD="post">
姓名:<input type="text" name="username" /><br/>
密码:<input type="text" name="password" /><br/>
金额:<input type="text" name="money" /><br/>
用户姓名:<input type="text" name="user.uname" /><br/>
用户年龄:<input type="text" name="user.age" /><br/>
<input type="submit" value="提交">
- 包含集合对象
public class Account implements Serializable {
private String username;
private String password;
private Double money;
private List<User> userList;
private Map<String,User> userMap;
}
<form action="param/testParam" METHOD="post">
姓名:<input type="text" name="username" /><br/>
密码:<input type="text" name="password" /><br/>
金额:<input type="text" name="money" /><br/>
用户姓名1:<input type="text" name="userList[0].uname" /><br/>
用户年龄:<input type="text" name="userList[0].age" /><br/>
用户姓名2:<input type="text" name="userMap['one'].uname" /><br/>
用户年龄:<input type="text" name="userMap['one'].age" /><br/>
<input type="submit" value="提交">
list集合第一个元素封装了一个User
Map添加了一个键值对{ one :User}
SpringMVC 常用注解
- @Controller
- @RequestMapper(path = “”)
可以使用path或者value,
可以使用method,这个方法必须是get/post/put…请求方法
@RequestMapping(path = "/add" ,method = RequestMethod.GET)
@GetMapping(path = "/add") //与上等同。
- @RequestParam
写在函数的参数前,使页面的input name属性与之对应。
public String testRequestParam(@RequestParam("name") String username){
System.out.println(username);
return "success";
}
- @RequestBody
使用异步时,较好用。
@RequestMapping(value = "/testRequestBody" )
public String testRequestBody(@RequestBody String body){
System.out.println(body);
return "success";
}
- @RequestHeader 获取头值
@RequestMapping(value = "/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept") String head){
System.out.println(head);
return "success";
}
- @CookieValue 获取cookie的值
@RequestMapping(value = "/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue){
System.out.println(cookieValue);
return "success";
}
- @ModelAttribute 放方法上,该方法先于控制器方法执行。
- 有返回值,testModelAttribute 就会拿到fun1设置的 date.
@ModelAttribute
public User fun1(String uname,Integer age){
User user = new User();user.setAge(age);user.setDate(new Date());user.setUname(uname);
return user;
}
@RequestMapping(value = "/testModelAttribute")
public String testModelAttribute(User user){
System.out.println(user);
return "success";
}
- @ModelAttribute 放参数前
- 没有返回值,存在map里,取map里的user
@ModelAttribute
public void fun1(String uname, Integer age, Map<String,User> map){
User user = new User();user.setAge(age);user.setDate(new Date());user.setUname(uname);
map.put("user1", user);
}
@RequestMapping(value = "/testModelAttribute")
public voidtestModelAttribute(@ModelAttribute("user1") User user){
System.out.println(user);
return "success";
}
- @SessionAttributes
- 用于方法之间参数的共享
把model存的东西,存到session里
写在类上
@SessionAttributes(value = "msg")
public class AnnoController {
//设置session存储的信息
@RequestMapping(value = "/testSessionAttributes")
public String testSessionAttributes(Model model){
model.addAttribute("msg","mm");
return "success";
}
//获取session存储的信息
@RequestMapping(value = "/getSessionAttributes")
public String testSessionAttributes(ModelMap modelMap){
Object msg = modelMap.get("msg");
System.out.println(msg);
return "success";
}
//清除session
@RequestMapping(value = "/deleteSessionAttributes")
public String deleteSessionAttributes(SessionStatus status){
status.setComplete();
return "success";
}
}
RESTful
- 不是标准,不适合协议,是一种风格。
- 更简介,更有层次,更易实现缓存。相同的请求地址,但是使用不同的请求方法。
https://blog.csdn.net/qq_27026603/article/details/82012277
- @PathVariable
RESTful风格。更利于缓存。
@RequestMapping(value = "/testPathVariable/{sid}" , method = RequestMethod.GET )
public String testPathVariable(@PathVariable(name = "sid") String id){
System.out.println(id);
return "success";
}
- 可以通过相同的请求路径,但是请求方式不同,得到不同的访问结果。
@Controller
@RequestMapping("/rest")
public class RestController {
//传统
//http://localhost:8080/springmvc/rest/add?a=1&b=1
//RESTful
//@PathVariable 和 @RequestMapping("/add/{a}/{b}")
@RequestMapping(path = "/add/{a}/{b}" ,method = RequestMethod.GET)
//@DeleteMapping(path = "/add/{a}/{b}")
public String hello1(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","运算结果:"+res);
return "hello";
}
@RequestMapping(path = "/add/{a}/{b}" ,method = RequestMethod.POST)
public String hello2(@PathVariable int a, @PathVariable int b, Model model){
int res = (a+b)*(a+b);
model.addAttribute("msg","运算结果:"+res);
return "hello";
}
}
自定义类型转换器
- springmvc-servlet.xml
<!--配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.utils.StringToDateConverter"/>
</set>
</property>
</bean>
<!--让自定义类型转换器生效.
conversion-service="conversionService"
-->
<!--开启springMVC注解支持-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
package cn.itcast.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
DateFormat df = null ;
if(s == null || s.trim().isEmpty()){
throw new RuntimeException("请输入日期");
}
if(s.contains("-")){
df = new SimpleDateFormat("yyyy-MM-dd");
}
if(s.contains("/")){
df = new SimpleDateFormat("yyyy/MM/dd");
}
if(df == null){
throw new RuntimeException("请输入正确的日期格式,yyyy-MM-dd或者yyyy/MM/dd");
}
try {
return df.parse(s);
} catch (ParseException e) {
throw new RuntimeException("解析异常!");
}
}
}
原生Servlet-API
@RequestMapping(value = "/testServlet" )
public String testServlet(HttpServletRequest request, HttpServletResponse response){
System.out.println("执行原生Servlet-api/");
System.out.println(request);
System.out.println(response);
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
return "success";
}
乱码问题的解决
- web.xml 中添加springmvc自带的过滤器。
<!--配置解决中文乱码的过滤器-->
<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>
- tomcat 的编码设置
- 自定义过滤器
https://www.cnblogs.com/dflmg/p/6278434.html
补充知识点
在spirngMVC中 /和/*的区别
- /:只匹配所有的请求,不会去匹配jsp页面
- /*:匹配所有的请求,包括jsp页面
可能遇到404(确定不是代码和路径问题时)的解决方法
- 查看控制台输出,看一下是不是缺少什么jar包
- 如果jar包存在,显示无法输出,就是项目结构的Artifacts项目的WEB-INF目录下添加一个lib,并 + 上 lib依赖
- 重启Tomcat解决
响应数据和结果视图
- 返回String 经过视图解析器
@RequestMapping("/testString")
public String testString(Model model){
model.addAttribute("user","return String");
return "success";
}
- 无返回值,使用转发和重定向
@RequestMapping("/testServlet")
public void testServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid()....");
// 转发
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//重定向
response.sendRedirect(request.getContextPath()+"/index.jsp");
// response.setContentType("application/html;charset=UTF-8");
// response.getOutputStream().print("sxxx");
return;
}
- 返回ModelAndView
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mv = new ModelAndView();
System.out.println("testModelAndView()....");
User user = new User();user.setAge(34);user.setPassword("21321");user.setUsername("小美");
//把user对象存储到mv对象中,也会把user对象存到request域
mv.addObject("user",user);
//跳转到哪个页面-会使用视图解析器! /WEB-INF/pages/success.jsp
mv.setViewName("success");
return mv;
}
- 使用关键字进行转发和重定向
@RequestMapping("/testForward")
public String testForward() {
return "forward:/WEB-INF/pages/success.jsp";
}
@RequestMapping("/testRedirect")
public String testRedirect() {
//springMVC自动加上项目名称,所以不需要自己添加。
return "redirect:/index.jsp";
}
JSON
实现方式一:不使用第三方的方法,使用注解
· @ResponseBody和@RequestBody 的使用
<script>
$(function () {
$("#btn").click(function () {
//发送ajax请求
$.ajax({
//编写json格式,设置属性和值.
url:"user/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"zhangSan","password":"123456","age":30}',
dataType:"json",
type:"post",
success:function (data) {
alert(data.username);//结果为;haha
}
});
});
});
</script>
- @RequestBody 接收封装到user 和 @ResponseBody 响应为json串
@RequestMapping("/testAjax")
// 导入jackson坐标,属性名对应即可直接封装
public @ResponseBody User testAjax(@RequestBody User user) {
System.out.println(user);user.setUsername("haha");user.setAge(40);
//{"username":"haha","password":"123456","age":40}
return user;
}
实现方法二: JackSon
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
- 如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
- 使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面
若返回json等内容到页面,则需要加@ResponseBody注解
- 可以解析user,也可以解析列表,解析时间。
@RequestMapping("/j1")
@ResponseBody // 视图解析器失效,返回JSON字符串
public String test4() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user = new User(1,"张三",23);
String str = mapper.writeValueAsString(user);
return str;
}
- @ResponseBody表示当前方法回返回字符串
- @RestController 则是该类下全部方法返回字符串被视图解析器解析。
实现方法三:FastJson
- JSON和java对象的转换
//java 对象转为JSON字符串
String strUsers = JSON.toJSONString(users);
String strUser = JSON.toJSONString(user);
//JSON字符串转JAVA对象
User u = JSON.parseObject(strUser,User.class);
List<User> us = JSON.parseObject(strUsers,List.class);
System.out.println(us);
//JAVA对象 转为 JSON对象
JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
- 视图解析返回
@RequestMapping("/j2")
public String test5(Model model) {
List<User> users = new ArrayList<>();
User user = new User(1,"w矮矮",77);
User user2 = new User(1,"w矮矮",77);
User user3 = new User(1,"w矮矮",77);
users.add(user);users.add(user2);users.add(user3);
model.addAttribute("msg",JSON.toJSONString(users));
return "hello";
}
- 字符串返回(把返回值作为响应体内容。)
@RequestMapping("/j2")
@ResponseBody
public String test5() {
List<User> users = new ArrayList<>();
User user = new User(1,"w矮矮",77);
User user2 = new User(1,"w矮矮",77);
User user3 = new User(1,"w矮矮",77);
users.add(user);users.add(user2);users.add(user3);
return JSON.toJSONString(users);
}
JS对象与JSON的转换
var jsObj = {
name:'zhangSan',
age:'18'
};
var jsonStr = '{"name":"zhangSan","age","18"}';
// JSON字符串转换为JS对象
var JsObject = JSON.parse(jsonStr);
// JS对象转换为JSON字符串
var jsonString = JSON.stringify(jsObj);
//浏览器控制台查看输出
console.log(jsonObject);
JSON乱码解决
- springmvc-servlet里配置- 解决json乱码
```xml
<!--解决json乱码-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
上传下载
传统的上传下载
pow.xml 和表单写法
<!--传统文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<form action="user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /> <br/>
<input type="submit" value="上传" />
</form>
@RequestMapping("/fileupload")
public String fileupload(HttpServletRequest request) throws Exception {
//先获取到要上传的文件目录
String path = request.getSession().getServletContext().getRealPath("/uploads");
//创建File对象,一会向该路径下上传文件
File file = new File(path);
// 判断路径是否存在,如果不存在,创建该路径
if (!file.exists()) {
file.mkdirs();
}
// 创建磁盘文件项工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// 解析request对象
List<FileItem> list = fileUpload.parseRequest(request);
// 遍历
for (FileItem fileItem : list) {
// 判断文件项是普通字段,还是上传的文件
if (fileItem.isFormField()) {
} else {
// 上传文件项
// 获取到上传文件的名称
String filename = fileItem.getName();
// 上传文件
fileItem.write(new File(file, filename));
// 删除临时文件
fileItem.delete();
}
}
return "success";
}
SpringMVC方式上传
- springmvc框架文件上传原理
- springmvc.xml
<!--配置文件解析器对象,上传。id值必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" ></property>
</bean>
@RequestMapping("/fileupload2")
// upload2 应与表单的input的name属性一致。
public String fileupload1(HttpServletRequest request, MultipartFile upload2) throws Exception {
System.out.println("文件上传...");
String path = request.getSession().getServletContext().getRealPath("/upload/");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
String fileName = upload2.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid + "_" + fileName;
upload2.transferTo(new File(path, fileName));
return "success";
}
SpringMVC跨服务器方式文件上传
- 在实际开发中,我们会有很多处理不同功能的服务器。
- 应用服务器、数据库服务器、缓存
<!--跨服务器文件上传-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
<h3>跨服务器文件上传</h3>
<form action="user/fileupload3" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload3" /> <br/>
<input type="submit" value="上传" />
</form>
/**
* 跨服务器文件上传
* @param upload3 需与input name属性一致
*/
@RequestMapping("/fileupload3")
public String fileupload3(MultipartFile upload3) throws Exception {
//定义上传文件服务器路径路径
String path = "http://localhost:9090/fileuploadserver/uploads/";
String fileName = upload3.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid + "_" + fileName;
//完成文件跨服务器上传
//1.创建客户端的对象
Client client = Client.create();
//2.连接图片服务器
WebResource resource = client.resource(path + fileName);
//3.上传文件
resource.put(upload3.getBytes());
return "success";
}
- 需要注意的地方:HTTP端口和JMX 端口不能被占用。
- 可能会出现的异常:路径不存在、tomcat为只读。
https://sihai.blog.csdn.net/article/details/56845475
SpringMVC的异常处理
- 出现异常,出现友好的异常一面,而不是下面这样子!
- 异常处理的原理:配置异常处理器
- 1.编写自定义异常类SysException(提示错误信息)
package cn.itcast.exception;
public class SysException extends Exception{
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String msg){
this.message=msg;
}
}
- 2.编写异常处理器HandlerExceptionResolver
package cn.itcast.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.SysexMessage;
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常的业务逻辑
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//获取异常对象
SysException e = null;
if(ex instanceof SysException){
e = (SysException)ex;
}else {
e = new SysException("系统正在维护");
}
//创建ModelAndView
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",e.getMessage());
mv.setViewName("error");
return mv;
}
}
---
- 3.配置异常处理器(跳转到提示页面)springmvc.xml
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>
- 上面的异常处理器。非sysException即输出系统正在维护。
@RequestMapping("/testException2")
public String testException2() throws Exception{
try{
int i=1/0;
}catch (Exception e){
throw new Exception(e);//系统正在维护
}
return "success";
}
SpringMVC拦截器
单拦截器的执行顺序:
双拦截器的执行顺序:
拦截器的应用:
前处理可以查看使用是否登录,没有登录跳转到登录页面。
后处理可以释放一些资源。
- 1.编写拦截器类,实现HandlerInterceptor接口
package cn.itcast.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor1 implements HandlerInterceptor {
/**
* 预处理:controller之前
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor1...preHandler..执行了..前111");
// request.getRequestDispatcher("/WEB-INF/pages/test.jsp").forward(request,response);
return true;
}
/**
* 后处理方法:controller之后,success,jsp之前。
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor1...postHandle..执行了..后111");
request.getRequestDispatcher("/WEB-INF/pages/test.jsp").forward(request,response);
}
/**
* jsp页面执行之后,该方法会执行,是最后会执行的方法。
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor1...afterCompletion..执行了..最后111");
}
}
- 2.配置拦截器类
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--要拦截的具体方法-->
<mvc:mapping path="/user/*"/>
<!--不拦截-->
<!--<mvc:exclude-mapping path=""/>-->
<bean id="MyInterceptor1" class="cn.itcast.interceptor.MyInterceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!--拦截-->
<mvc:mapping path="/user/*"/>
<bean id="MyInterceptor2" class="cn.itcast.interceptor.MyInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>