SpringMVC构建
一.SpringMVC简介
Model数据模型
View视图
Controller控制器
MVC是一种web应用架构,是一种代码设计思想
思想:将所有客户端请求全部交由控制器,由控制器将其分发并将结果响应给客户端
2.常见MVC框架
使用原生Servlet实现MVC,
*配置比较复杂
*数据处理太麻烦
实际开发中一般都会使用MVC框架,如Struts1,struts2,SpringMVC等
对比:
*效率方面:Struts1>SpringMVC>Struts2
struts2是多例的,效率低
Struts1和SpringMVC是单例的,两者效率基本差不多
*配置方面:SpringMVC>Struts2>Struts1
3为什么要使用SpringMVC
*使用注解配置替代xml配置,更简单
*效率高,单例的
*跨站好,用户自定义
*SpringMVC和Spring无缝衔接
二SpringMVC工作原理
1.流程图
2.执行过程
分为六步:
*DispatcherServlet
它是SpringMVC核心控制器,前端控制器,主要作用是用来分发
*HandleMapping
叫做映射处理器,根据请求url映射到具体的处理Handler
Handler就是Controller层的实现类,也称为Action或Controller
*HandlerAdapter
适配器,用来适配不同的处理器Handler
处理器有两种实现方式:实现接口,基于注解,所以执行之前需要先适配
*Handler
处理器:执行处理具体业务,并产出数据模型Model和视图View
Handler会将数据模型Model和视图View封装ModelAndView对象并返回
*ViewResolve
视图解析器:根据视图名解析为具体的视图,一般多为jsp页面,然后封装为View对象
*View
视图:使用具体的视图技术进行渲染,结合Model展示数据
视图有很多种形式:jsp,freemarker,velocity,excel,pdf等
三.第一个SpringMVC程序
1.添加jar包
springMVC包:1个,spring-webmvc
Ioc包:4个,sprng-core,spring-beans,spring-context,spring-expression
aop包 :3个,spring-aop,sping-aspects
javaee包:3个,jsp-api,jstl,javax.servlet-api
web包:spring-web
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yyp</groupId> <artifactId>springMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springMVC Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.20</version> </dependency> <!--整合spring-ioc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.20</version> </dependency> <!-- spring-aop的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.19</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.20</version> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合java EE的包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>springMVC</finalName> </build> </project>
2配置过程(总共6个步骤):
1.配置DispatcherServlet核心控制器(在web.xml中配置,这个是第一个步骤,其余几个步骤配置在springMVC-servlet.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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 1.配置DispatcherServlet:核心控制器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.Handler核心配置文件
两种定义方式:
*使用默认位置;默认在WEB-INF目录下,名称:核心servlet名称-servlet.xml
*自定义位置:名称自定义
根据Controller实现方式的不同,配置方式也有所不同,有两种方式定义Controller
*实现接口
*基于注解
在spring的配置文件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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 2.配置HandlerMapping --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- 3配置HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- 4配置Handler --> <bean name="/hello" class="com.yyp.controller.HelloController"/> <!-- 5配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"/> <property name="suffix" value=".jsp"/> <!-- 6配置View,使用jsp视图技术渲染页面 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> </bean> </beans>
把tomcat插件加入到pom中,并配置在pom.xml中启动
<build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> <finalName>springMVC</finalName> </build>
springMVC配置:总共6步()
3.2基于注解的Controller
1.配置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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 1.配置DispatcherServlet:核心控制器 --> <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:springmvcannotion.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>
2.配置springmvcannotion.xml(后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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <!-- 3.配置HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"/> <property name="suffix" value=".jsp"/> <!-- 6.配置View --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans>
也可以使用mvc注解驱动完成
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,注解驱动就是用来简化配置的 --> <mvc:annotation-driven /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans>
四.案例
1.用户登陆
2.关于静态资源的登陆
当配置DispatcherServlet为<url-pattern>/</url-pattern>时,会拦截所有请求(包括静态资源),导致所有静态资源都无法访问
两种处理方式:
解决方法一.使用tomcat提供的默认Servlet
tomcat提供了默认的Servlet来处理静态资源,在springannotation.xml配置文件里面加入<mvc:default-servlet-handler/>
这种处理的静态资源必须在webapp下面,不能是WEB-INF下面的目录,所以这种有局限性
缺点:1如果使用的不是tomcat,则不生效,它依赖于tomcat
2.只能读取webapp下的资源,不能读取/WEB-INF下的资源
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 --> <mvc:annotation-driven /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <mvc:default-servlet-handler/> </beans>
解决方式二.
三.直接访问jsp页面
可以在spring的配置文件,也就是springmvcannotation增加下面一行即可
<mvc:view-controller path="/userLogin" view-name="login"/>
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 --> <mvc:annotation-driven /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- mvc:resources mapping="/img/**" location="/WEB-INF/img/" /--> <mvc:default-servlet-handler /> <mvc:view-controller path="/userLogin" view-name="login"/> </beans>
五.Controller详解
1.方法的返回值
有四种类型:
*ModelAndView表示返回的为数据模型和视图
*String 表示返回的是视图
三种写法(形式):
普通字符串-------->表示视图名称
"forward"+url-------->转发
"rediect"+url---------->重定向
*void将请求的url作为视图名称,很少使用
*Object表示返回的是数据模型(一般返回的是json数据)
2.SpringMVC注解
注解 | 解释 |
@Controller |
将类映射为Controller,添加到Ioc容器中 |
@RequestMapping | 配置请求映射路径,即URL |
@RequestParam | 表示参数来源请求参数 |
@PathVariable | 表示参数来源于URL |
@RequestHeader | 表示参数来源于请求头 |
@CookieValue | 表示参数来源于Cookie |
@ReuqestBody | 表示参数来源请求体 |
@ModelAttribute | 将请求数据转换为对象 |
@Vaiid | 后台校验 |
@InitBinder | 类型转换,注册属性编辑器 |
@ControllerAdvice | 统一异常处理,处理全局异常 |
@ExceptionHandler | 异常处理器,处理特定异常的方法 |
@ResponseBody | 结合返回值Object的方法使用,用来返回JSON |
@RestController | 将类映射为Controller层,默认为所有的方法添加了@ResponseBody注解 |
3.@RequestMapping
3.1基本用法:
该注解可以定义在方法上,也可以定义在类上,定义在类上表示层级关系的
配置URL时以/开头和不以/开头的区别
*添加时表示从项目根路径开始查找
*不加时表示从当前方法所在层级开始查找
3.2URL的多种写法
请求映射路径有三种写法
*Ant风格
*星号表示单层目录,可以匹配任意字符,但正斜杠必须有
**2个星号表示多级目录,可以没有字符,正斜杠也可以没有
?表示单个字符,必须有一个字符
*Rest风格
{变量}表示URL中的占位符,可以结合@PathVariable获取值
{变量:正则}表示使用正则表达来限定值得格式
*国定写法
value和path互为别名,值为数组,可以制定多个值
3.3根据请求方式访问
限定请求方式: GET,POST,PUT,DELETE等
注解:1.@RequestMapping(path = "/test7", method = RequestMethod.GET)
2.:@PostMapping()或者@GetMapping()(在4.3版本以后有这2个注解)
3.4其他属性
*params
限定请求参数,必须符合制定条件
例子:@RequestMapping(path = "/test8", params = { "id", "username=admin", "password!=123" })
这个例子对请求参数限制,请求参数必须含有id,必须有username=admin的参数,还有password不能等于123
*headers
限定请求的头部,必须符合制定条件
SpringMVC,day02
一.javaEE组件
*HttpServletRequest
*HttpServletResponse
*HttpSession
2.IO流
InputStream/OutputStream
Reader/Writer
3.向界面传递数据
Model.Map.ModelMap
将数据存储到Request作用域中
4.String和基本类型
@RequestParam表示参数来源于请求参数,默认所有参数都添加该注解,参数值来源于同名的请求参数
@PathVariable表示 参数来源于url
@CookieValue 表示参数来源Cookie
@RequestBody表示参数来源于请求体(只有post请求才有请求体)
5.自定义类型
@ModelAtrribute将请求的参数封装为自定义的对象
条件:对象的属性名必须与表单元素的名称一致
@ModelAttribute注解有两种用法:
*在方法参数的前面添加该注解
作用:将请求参数转换为对象
*在方法的上面添加该注解
作用:在调用所有目标方法前都会调用添加@ModelAttribute注解方法,并向模型中添加数据
这个是jsp页面标准标签库jstl的导入命令
6.错误参数
Errors和BindResult
用来接收错误信息,实现服务器的数据校验
在实际开发中,既要做客户端校验,又要做服务端校验
二服务器校验框架
1.简介
JSR303是一个数据验证的标准规范,用于对Java Bean中的属性进行校验,称为Bean Validation
提供了常用的注解
1.2Hibernate Validator
是JSR303的一个参考实现,并提供了一些扩展的注解
2.用法:
添加包hibernate-validator
hibernate-validator-annotation-processor
加这2个包要注意和tomcat容器兼容问题,参考https://blog.csdn.net/Aphadite/article/details/119212961
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yyp</groupId> <artifactId>springMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springMVC Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- 整合hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <!-- 整合Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.20</version> </dependency> <!--整合spring-ioc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.20</version> </dependency> <!-- spring-aop的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.19</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.20</version> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合java EE的包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> <finalName>springMVC</finalName> </build> </project>
2.2为参数对象加注解
表示我要对这个对象进行校验
public String regist(@Validated UserVo userVo, Errors errors) {
2.3为对象的属性加注解
package com.yyp.Vo; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; public class UserVo { // @NotEmpty(message = "用户名不能为空") @NotEmpty(message = "用户名不能为空") @Pattern(regexp = "\\w{6,10}", message = "用户名只能包含数字,字母,下划线,且长度为6-10位") private String username; @Length(min = 6, max = 10, message = "密码必须是6-10位") private String password; @Pattern(regexp = "(139|133|131)\\d{8}", message = "手机号码格式不正确") private String phone; @Email(message = "邮箱格式不正确") private String email; @NotNull(message = "年龄不能为空") @Range(min = 1, max = 120, message = "年龄必须在1-120之间")
三.类型转换
1.简介
数据绑定流程,获取值--->查找转换器---->转换---->后台数据校验----->数据绑定
两种解决方式:
*方式1.使用PropertyEditor
*方式2:使用Converter(推荐)
2.使用PropertyEditor
步骤:
1.定义一个属性编辑器
不过下面这个spring.xml配置方式不起作用
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="com.yyp.entity.Address" value="com.yyp.editor.AddressEditor" /> </map> </property> </bean> </beans>
2.注册属性编辑器
@InitBinder
缺点:
1.代码嵌套在Controller层中
2.只能从字符串转换为对象
3.使用Convertor
步骤:
1.定义转换器,实现Converter接口
2.管理自定义转换器
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 --> <mvc:annotation-driven /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <!-- 管理自定义转换器 --> <bean class="org.spring.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter"/> <bean class="com.yyp.controller.Address2StringConverter"/> </set> </property> </bean> </beans>
3.加载应用自定义转换器,在spring.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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"/> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter"/> <bean class="com.yyp.controller.Address2StringConverter"/> </set> </property> </bean> </beans>
四.@SessionAttributes
作用:将模型中指定名称的数据存储到session中
五统一异常处理
1简介
对异常进行统一处理
两种方式:
*使用web技术提供的统一的异常处理
*
2.使用web的异常处理,在项目的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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 1.配置DispatcherServlet:核心控制器 --> <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:springmvcannotation.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> <!-- 404异常 --> <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> <!-- 500异常 --> <error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page> </web-app>
3.使用SpringMVC的异常处理
步骤:
1.定义一个异常处理类(通知),增加@@ControllerAdvice这个注解,@ControllerAdvice表示是一个异常处理通知
2.定义异常处理的方法,需要在方法上面加@ExceptionHandler
SpringMVC day03
一拦截器:
1.简介
使用拦截器Interceptor对请求进行拦截,类似于过滤器Filter
2.用法
步骤:
1.定义一个类,实现HandlerInterceptor
2.在spring.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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"/> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter"/> <bean class="com.yyp.controller.Address2StringConverter"/> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <bean class="com.yyp.interceptor.HelloInterceptor"/> </mvc:interceptors> </beans>
在spring.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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService" /> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter" /> <bean class="com.yyp.controller.Address2StringConverter" /> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <!-- bean class="com.yyp.interceptor.HelloInterceptor" />--> <!-- 拦截指定的请求 --> <mvc:interceptor> <mvc:mapping path="/user/regist" /> <mvc:mapping path="/path/showLogin" /> <mvc:mapping path="/hello" /> <mvc:exclude-mapping path="/test6"/> <bean class="com.yyp.interceptor.TimerInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
二.处理AJAX
1创建ajax.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script> <script type="text/javascript"> $(function() { $('#btn').on('click', function() { $.post('${pageContext.request.contextPath}/ajax/test1', function(data) { console.log(data); }); }); }); </script> </head> <body> <button id="btn">发送AJAX请求</button> </body> </html>
2.创建AjaxController的类
package com.yyp.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/ajax") public class AjaxController { @RequestMapping("/test1") public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); out.write("success"); } }
在web.xml配置访问ajax的资源
<?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_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 1.配置DispatcherServlet:核心控制器 --> <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:springmvcannotation.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> <!-- 404异常 --> <!-- <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page>--> <!-- 500异常 --> <!-- error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page>--> </web-app>
另外一种方法:springmvc提供了另外一种注解
@ResponseBody
为方法添加啊注解后,会将返回值写到响应体中
2.返回json
三种方式:
1.jackson,springmvc默认支持的
2.gson,springmvc默认支持,google开发
3.fastjson,springmvc默认不支持,alibaba开发
2.1使用jackson
1.添加jar包jackson-databind和jackson-core,版本号是2.9.9.3版本
2.配置消息转换器,在sping.xml文件中(当然也可以不配置,因为springmvc默认是对jason消息转换器支持的,但是在我自己的环境中,不配置会报错的,所以要配置的,报错是对这个@ResponseBody注解无法支持)
配置以后,@ResponseBody这个注解就可以正常执行了
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"> <!-- 配置jason消息转换器 --> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <mvc:view-controller path="/ajax" view-name="ajax" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter" /> <bean class="com.yyp.controller.Address2StringConverter" /> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <!-- bean class="com.yyp.interceptor.HelloInterceptor" /> --> <!-- 拦截指定的请求 --> <mvc:interceptor> <mvc:mapping path="/user/regist" /> <mvc:mapping path="/path/showLogin" /> <mvc:mapping path="/hello" /> <mvc:exclude-mapping path="/test6" /> <bean class="com.yyp.interceptor.TimerInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
2.2使用gson
步骤:
1.添加jar包
<!-- 整合gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency>
2.配置消息转换器,
如果不配置,那么对@ResponseBody注解无法支持
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"> <!-- 配置jason消息转换器 --> <mvc:message-converters> <!-- bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>--> <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <mvc:view-controller path="/ajax" view-name="ajax" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter" /> <bean class="com.yyp.controller.Address2StringConverter" /> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <!-- bean class="com.yyp.interceptor.HelloInterceptor" /> --> <!-- 拦截指定的请求 --> <mvc:interceptor> <mvc:mapping path="/user/regist" /> <mvc:mapping path="/path/showLogin" /> <mvc:mapping path="/hello" /> <mvc:exclude-mapping path="/test6" /> <bean class="com.yyp.interceptor.TimerInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
当然也可以配置多个消息转换器,按照配置顺序进行选择
设置字符集:
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"> <!-- 配置jason消息转换器 --> <mvc:message-converters> <!-- bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>--> <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=utf-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <mvc:view-controller path="/ajax" view-name="ajax" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter" /> <bean class="com.yyp.controller.Address2StringConverter" /> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <!-- bean class="com.yyp.interceptor.HelloInterceptor" /> --> <!-- 拦截指定的请求 --> <mvc:interceptor> <mvc:mapping path="/user/regist" /> <mvc:mapping path="/path/showLogin" /> <mvc:mapping path="/hello" /> <mvc:exclude-mapping path="/test6" /> <bean class="com.yyp.interceptor.TimerInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
三.关于文件的上传和下载
1.文件的上传
springmvc对文武兼上传提供了支持,基于commons-fileupload
1.2用法
步骤:
1.添加jar
commons-fileupload,这个包也依赖于commons-io
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yyp</groupId> <artifactId>springMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springMVC Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- 整合commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- 整合gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency> <!-- 整合jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9.3</version> </dependency> <!-- 整合hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <!-- 整合Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.20</version> </dependency> <!--整合spring-ioc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.3.20</version> </dependency> <!-- spring-aop的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.19</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.20</version> </dependency> <!-- 整合spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.21</version> </dependency> <!-- 整合java EE的包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> <finalName>springMVC</finalName> </build> </project>
2.编写jsp上传页面file.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/file/upload" method="post" encype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> </body> </html>
一次上传多个文件的file.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/file/uploads" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username"><br> <input type="file" name="files"><br> <input type="file" name="files"><br> <input type="file" name="files"><br> <input type="submit" value="上传"> </form> </body> </html>
3.配置文件解析器
<?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:aop="http://www.springframework.org/schema/aop" 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"> <!-- 2.配置HandlerMapping --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 3.配置HandlerAdapter --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 2和3步骤也可以用下面的注解驱动完成,就是用来简化配置的 默认会加载许多内置的类型转换器,如果需要使用自定义的类型转换器,需要自己指定 --> <mvc:annotation-driven conversion-service="conversionService"> <!-- 配置jason消息转换器 --> <mvc:message-converters> <!-- bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>--> <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=utf-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 4配置Handler --> <context:component-scan base-package="com.yyp.controller" /> <!-- 5.配置ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> <!-- 6.配置View,如果使用jsp,默认情况这个步骤也可以省略 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--mvc:resources mapping="/img/**" location="/WEB-INF/img/" / --> <mvc:default-servlet-handler /> <!-- 直接访问jsp页面 --> <mvc:view-controller path="/userLogin" view-name="login" /> <mvc:view-controller path="/register" view-name="register" /> <mvc:view-controller path="/ajax" view-name="ajax" /> <mvc:view-controller path="/file" view-name="file" /> <!-- 管理自定义转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.yyp.controller.String2AddressConverter" /> <bean class="com.yyp.controller.Address2StringConverter" /> </set> </property> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <!-- 拦截所有请求 --> <!-- bean class="com.yyp.interceptor.HelloInterceptor" /> --> <!-- 拦截指定的请求 --> <mvc:interceptor> <mvc:mapping path="/user/regist" /> <mvc:mapping path="/path/showLogin" /> <mvc:mapping path="/hello" /> <mvc:exclude-mapping path="/test6" /> <bean class="com.yyp.interceptor.TimerInterceptor" /> </mvc:interceptor> </mvc:interceptors> <!-- 配置文件解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSizePerFile" value="5000000"></property> </bean> </beans>
4.通过CommonsMultipartFile来接收文件
package com.yyp.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.yyp.util.StringUtils; @Controller @RequestMapping("/file") public class FileController { @RequestMapping("/upload") public String upload(String username, @RequestParam CommonsMultipartFile file, HttpSession session) throws IllegalStateException, IOException { System.out.println("File upload---------------------------------------->"); System.out.println("用户名::" + username); System.out.println("表单名称:" + file.getName()); System.out.println("文件名:" + file.getOriginalFilename()); System.out.println("文件大小" + file.getSize()); String realPath = session.getServletContext().getRealPath("WEB-INF/upload"); System.out.println("磁盘路径:" + realPath); file.transferTo(new File(realPath, StringUtils.rename(file.getOriginalFilename()))); return "success"; } @RequestMapping("/uploads") public String uploads(String username, @RequestParam CommonsMultipartFile[] files, HttpSession session) { String realPath = session.getServletContext().getRealPath("WEB-INF/upload"); System.out.println("磁盘路径:" + realPath); for (CommonsMultipartFile file : files) { try { System.out.println("磁盘路径:" + realPath); System.out.println("文件真实名字:" + file.getOriginalFilename()); System.out.println("文件真实名字:" + file.getSize()); file.transferTo(new File(realPath, StringUtils.rename(file.getOriginalFilename()))); } catch (IllegalStateException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "success"; } }
2.文件的下载
两种方式:
1.使用OutputStream
2.使用@ResponseEntity
2.1使用OutputStream
传递文件名的两种方式:
*使用请求参数传递文件名
*使用rest风格传递文件名
默认情况下,如果url结尾有后缀,自动截取了后缀了
1.解决方法:将文件名放到url中间
2.配置不自动截取后缀
2.2使用@ResponseEntity