SpringMVC
1.Servlet映射路径回顾
先提一个Servlet映射路径问题
@WebServlet("/")
@WebServlet("/*")
都是接受任何请求
区别: / 不包括访问jsp的请求,/* 真的所有请求,包含jsp
2.front 设计模式
所有的请求都经过一个类,具体需要哪一个controller处理,需要靠它去分发,这是比较专业的前端设计模式,而这一需求SpringMVC可以完美解决
3.SpringMVC简介
####Spring重要组件
3.1中央控制器DispatcherServlet(前端控制器)
它可以接收所有请求(不要包含jsp)
3.2处理器映射器HandlerMapping
解析请求格式的
3.3处理器适配器HandlerAdapter
负责调用请求方法
3.4视图解析器ViewResovler
解析结果,并决定跳转的具体哪一个视图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LMW24Q79-1573125858997)(/77VnAf.jpeg)]
4.SpringMVC环境搭建
新建maven项目,引入依赖,这次我们将web部分的依赖也引进来
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.neuedu</groupId>
<artifactId>springmvc</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
</dependencies>
</project>
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">
<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.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.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解扫描,老版本需要添加注解驱动,现在省略了-->
<context:component-scan base-package="org.neuedu.controller"></context:component-scan>
</beans>
controller
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
// @RequestMapping 默认对应get,post请求
// @GetMapping 对应get请求
// @PostMapping 对应post请求
@GetMapping("/hello")
public String hello() {
// 默认是转发
return "Test.jsp";
}
}
启动,在浏览器访问hello,成功跳转
4.1静态资源放行
mapping
当请求中有指定映射格式时,到 location
下去找,这就是静态资源的放行
<?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
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解扫描-->
<context:component-scan base-package="org.neuedu.controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
</beans>
4.2参数绑定
4.2.1基本数据类型和字符串
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Test Page</h1>
<form action="${pageContext.servletContext.contextPath}/hello1" method="get">
<p><input type="text" name="username"></p>
<p><input type="text" name="age"></p>
<button>submit</button>
</form>
</body>
</html>
@Controller
public class HelloController {
@GetMapping("/hello1")
public String hello1(HttpRequestServlet req) {
req.getParameter("name");// 依然有效,但有更便捷的方式
return "/Test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1")
public String hello1(String name,int age) { // 自动进行类型绑定和转换,需要保证参数名一致
System.out.println(name+","+age);
return "/Test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1")
// 不一致,需要@RequestParam注解绑定
public String hello1(@@RequestParam("name")String name1,int age) {
System.out.println(name+","+age);
return "/Test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1")
// defaultValue 若没有获取到name,采用默认值aa
public String hello1(@@RequestParam(defaultValue="aa")String name,int age) {
System.out.println(name+","+age);
return "/Test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1")
// required=true,要求必须获取到该参数,否则抛异常
public String hello1(@@RequestParam(required=true)S tring name,int age) {
System.out.println(name+","+age);
return "/Test.jsp";
}
}
4.2.2复杂参数
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class HelloController {
// 比如复选框,传过来是数组,可以像下面这么写
@GetMapping("/hello1")
public String hello1(@RequestParam("hobby") List<String> hobby) {
System.out.println(hobby);
return "/Test.jsp";
}
}
package org.neuedu.controller;
public class Student {
private Integer stuno;
private String stuname;
@Override
public String toString() {
return "Student{" +
"stuno=" + stuno +
", stuname='" + stuname + '\'' +
'}';
}
public Integer getStuno() {
return stuno;
}
public void setStuno(Integer stuno) {
this.stuno = stuno;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
}
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
// 参数中只要和对象属性同名,会进行自动绑定
@GetMapping("/hello1")
public String hello1(Student student) {
System.out.println(student.toString());
return "/Test.jsp";
}
}
4.2.3restful风格参数
<a href="xxxxxx/hello1/13/tom"></a>
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class HelloController {
// {} 意思是这是路径传过来的参数,使用@PathVariable可以指定绑定的变量,如果同名可以省略
@GetMapping("/hello1/{id}/{name}")
public String hello1(@PathVariable("id") int id,@PathVariable("name") String name) {
System.out.println(id+","+name);
return "/Test.jsp";
}
}
4.3三种返回值
4.3.1字符串
@Controller
public class HelloController {
@GetMapping("/hello1/{id}/{name}")
public String hello1() {
// 默认是转发
return "/test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1/{id}/{name}")
public String hello1() {
// 也是转发
return "forward:/test.jsp";
}
}
@Controller
public class HelloController {
@GetMapping("/hello1/{id}/{name}")
public String hello1() {
// 重定向
return "redirect:/test.jsp";
}
}
注意:字符串中不要出现空格
4.3.2void
使用void有两种情况
第一种情况就是采取servlet的方式进行转发或重定向
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class HelloController {
@GetMapping("/hello1")
public void hello1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/Test.jsp").forward(request,response);
}
@GetMapping("/hello2")
public void hello2(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect(request.getContextPath()+"/Test.jsp");
}
}
第二种情况是响应ajax字符串时返回json或返回的字符串直接要在页面打印,使用 @ResponseBody
注解,该注解默认是采取 jackson
完成的
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@GetMapping(value = "/hello1",produces = "text/html;charset=utf-8") // 返回值如果中文防乱码
@ResponseBody
public String hello1(){
return "hello";// 此处返回的字符串会在页面打印,并不代表跳转
}
@GetMapping("/hello2")
@ResponseBody
public Student hello2() {
Student student = new Student();
student.setStuno(1001);
student.setStuname("TOM");
return student;
}
}
4.3.3ModelAndView
package org.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@GetMapping("/hello3")
public ModelAndView hello3() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "hello");
modelAndView.setViewName("/Test.jsp");
return modelAndView;
}
@GetMapping("/hello4")
public String hello4(Model model) {
model.addAttribute("msg", "hello");
return "/Test.jsp";
}
}
4.4 处理中文乱码
<?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">
<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.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>
<!-- 处理请求中中文乱码的过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.5视图资源解析器
<?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
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解扫描-->
<context:component-scan base-package="org.neuedu.controller"></context:component-scan>
<mvc:resources mapping="/js/" location="/js/**"></mvc:resources>
<!-- 视图资源解析器,当controller返回是字符串时默认会在字符串前后添加前缀后缀,方便编程 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/src"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
4.6文件的上传和下载(了解)
4.6.1上传
引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.neuedu</groupId>
<artifactId>springmvc</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- spring相关jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<!-- serlvet和jsp依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- 文件上传下载需要的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
上传页面jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>上传页面</h1>
<form action="${pageContext.servletContext.contextPath}/upload"
method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button>submit</button>
</form>
</body>
</html>
springmvc配置文件配置multipart类型解析器
<?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
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解扫描-->
<context:component-scan base-package="org.neuedu.controller"></context:component-scan>
<!-- multipart类型解析器 -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="80000"></property>
<property name="defaultEncoding" value="UFT-8"></property>
</bean>
</beans>
@Controller
public class HelloController {
@PostMapping("upload")
@ResponseBody
public void upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// 判断是否有上传文件
if(!file.isEmpty()){
String strFolder = request.getServletContext().getRealPath("/image")+ File.separator;
File folder = new File(strFolder);
if(!folder.exists()){
folder.mkdir();
}
// 此处未使用UUID来生成唯一标识,用日期做为标识
String strNewFilePath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String strFinalPath = strFolder + strNewFilePath;
//把文件上传至path的路径
File localFile = new File(strFinalPath);
file.transferTo(localFile);
}
}
}
4.6.2下载
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>下载页面</h1>
<a href="${pageContext.servletContext.contextPath}/download?fileName=test.txt">下载</a>
</body>
</html>
package org.neuedu.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@Controller
public class HelloController {
@GetMapping("/download")
public void downLoad(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
// 下载文件一定要添加一个响应头
response.setHeader("Content-Disposition","attachment;filename="+fileName);
ServletOutputStream outputStream = response.getOutputStream();
String path = request.getServletContext().getRealPath("files");
System.out.println(path);
File file = new File(path, fileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
5.拦截器Interceptor
拦截器与过滤器比较相似,当发送请求时,会被拦截器拦截,从而在controller前后添加额外功能
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lAafLXLG-1573125859001)(/468490-5cf009d12dcf778c.png)]
xml需要配置:两种配置方式
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/demo" />
<bean class="com.neuedu.interceptor.CheckInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class CheckInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if(request.getSession().getAttribute("login_user") == null) {
request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
return false;
}else {
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println(456);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println(789);
}
}
###SSM总结:
- 1.环境搭建(最重要)
ervletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if(request.getSession().getAttribute(“login_user”) == null) {
request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
return false;
}else {
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println(456);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println(789);
}
}
###SSM总结:
+ 1.环境搭建(最重要)