🍤Spring之SpringMVC
一、拦截器
?什么是拦截器: 简单说就是对客户页面发送的请求进行拦截,进行一系列的处理。
?两种实现方式:
- 实现接口:org.springframework.web.servlet.HandlerInterceptor
- 继承适配器:org.springframework.web.servlet.handler.HandlerInterceptorAdapter
- 使用登录小案例练习拦截器
- 当用户没登陆成功, 则无法访问后台以及其他页面
①、创建web项目引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency> <groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
</dependencies>
②、web.xml文件配置
<web-app>
<display-name>Archetype Created Web Application</display-name>
<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>
<servlet>
<servlet-name>helloMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
③、spring.xml文件配置
<context:component-scan base-package="com.yjxxt.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/js/**"/>
<bean class="com.yjxxt.interceptor.Interceptor2"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
④、项目的大致结构
controller/Login.java登录的简单处理
@Controller
public class Login {
@RequestMapping("islogin")
public String isLogin(User user, HttpServletRequest req) {
System.out.println("123".equals(user.getName()));
if("123".equals(user.getName())&&"123".equals(user.getPwd())){
req.getSession().setAttribute("user",user);
return "hello";
}else{
return "redirect:login.jsp?msg=is false";
}
}
}
interceptor/interceptor1.java拦截器
public class Interceptor2 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(request.getRequestURI().contains("login")){
return true;
}
User user=(User) request.getSession().getAttribute("user");
System.out.println(request.getSession().getAttribute("user"));
if(user!=null){
return true;
}
request.getRequestDispatcher("login.jsp").forward(request,response);
return false;
}
}
bean/User.java
public class User {
private String name;
public void setName(String name) {
this.name = name;
}
public User(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public String getName() {
return name;
}
public User() {
}
private String pwd;
}
前端页面的编写:webapp/
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>登录</title>
</head>
<body>
${param.msg}
<hr>
<form action="islogin" method="get">
用户名:<input type="text" name="name" value="123">
密码:<input type="text" name="pwd" value="123">
<input type="submit" value="提交"/>
</form>
</body>
</html>
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<hr>
${sessionScope.user}
</body>
</html>
正确密码 错误密码会被拦截
二、文件上传
代码演示:
1、创建web项目引入依赖
<dependency> <groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
2、web.xml文件配置
<web-app>
<display-name>Archetype Created Web Application</display-name>
<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>
<servlet>
<servlet-name>helloMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>helloMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3、spring.xml文件配置
<context:component-scan base-package="com.yjxxt"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
</mvc:annotation-driven>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
4、项目的大致结构
①、UserController.java
@Controller
public class UploadController {
@RequestMapping("upload")
public String upload(@RequestParam("myfile") MultipartFile file, HttpServletRequest req) throws IOException {
if(!file.isEmpty()){
String filename= file.getOriginalFilename();
String last=filename.substring(filename.lastIndexOf("."));
Long tim=System.currentTimeMillis();
filename=tim+last;
String load=req.getServletContext().getRealPath("/");
File loadfile=new File(load+"/onload");
if(!loadfile.exists()){
loadfile.mkdirs();
}
File srcfile=new File(loadfile,filename);
file.transferTo(srcfile);
req.setAttribute("msg","上传成功~");
}else{
req.setAttribute("msg","文件不能为空");
}
return "msg";
}
}
②视图文件内容
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
文件<input type="file" name="myfile">
<input type="submit" value="提交">
</form>
</body>
</html>
跳转信息页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${requestScope.msg}
</body>
</html>
结果
三、SpringSSM整合
- SSM:Spring+SpringMVC+Mybatis
- 轻量级框架,重量级配置
1、依赖的导入
pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
2、web.xml配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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:spring-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>
3、resources下的文件配置
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: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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.yjxxt.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties"/>
<aop:aspectj-autoproxy/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yjxxt.ssm.mapper"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="servicePointcut"
expression="execution(* com.yjxxt.ssm.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
</aop:config>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis.xml"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
</bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yjxxt.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
spring-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
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="com.yjxxt.ssm.controller" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
mybatis.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.yjxxt.ssm.bean"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
jdbc.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user_msg?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=java51
log4j.properties
log4j.rootLogger=DEBUG, Console
# Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStat
4、三层结构内容?
UserMapper.java接口
public interface UserMapper {
public User selectOne(Integer useId);
int insert(User user);
int updata(User user);
int delete(Integer userId);
}
UserService.java接口:
public interface UserService {
User selectOne(Integer userId);
int insert(User user);
int updata(User user);
int delete(int userId);
}
UserServiceImp.java
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User selectOne(Integer userId){
return userMapper.selectOne(userId);
}
@Override
public int insert(User user) {
return userMapper.insert(user);
}
@Override
public int updata(User user) {
return userMapper.updata(user);
}
@Override
public int delete(int userId) {
return userMapper.delete(userId);
}
}
- controller层
UserController.java:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("select")
@ResponseBody
public User select(Integer userId){
return userService.selectOne(userId);
}
@RequestMapping("insert")
@ResponseBody
public int insert(User user){
return userService.insert(user);
}
@RequestMapping("updata")
@ResponseBody
public String updata(User user){
int num=userService.updata(user);
if(num>0){
return "updata is true";
}
return "updata is false";
}
@RequestMapping("delete")
@ResponseBody
public String delete(User user) {
int num = userService.updata(user);
if (num > 0) {
return "delete is true";
}
return "delete is false";
}
}
User.java:
public class User {
private Integer userId;
private String userName;
public User() {
}
public User(Integer userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
'}';
}
}
- mappers映射文件(resource/mappers)
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yjxxt.ssm.mapper.UserMapper">
<insert id="insert">
insert into user values (#{userId},#{userName})
</insert>
<update id="updata">
update user set userName=#{userName} where userId=#{userId}
</update>
<delete id="delete">
delete from user where userId=#{userId}
</delete>
<select id="selectOne" resultType="com.yjxxt.ssm.bean.User">
select * from user where userId = #{userId}
</select>
</mapper>
启动tomcat测试结果: 查询:
插入:
修改
删除
四、RestFul URL
概念: ????Restful 风格的 API 是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 在Restful 风格中,用户请求的 url 使用同一个 url,用请求方式:get,post,delete,put…等方式对请求的处理方法进行区分,这样可以在前后台分离式的开发中使得前端开发人员不会对请求的资源地址产生混淆和大量的检查方法名的麻烦,形成一个统一的接口。
在 Restful 风格中,现有规定如下:
GET(SELECT) :从服务器查询,可以在服务器通过请求的参数区分查询的方式。POST(CREATE) :在服务器端新建一个资源,调用 insert 操作。PUT(UPDATE) :在服务器端更新资源,调用 update 操作。PATCH(UPDATE) :在服务器端更新资源(客户端提供改变的属性)。(目前jdk7 未实现,tomcat7 不支持)。DELETE(DELETE) :从服务器端删除资源,调用 delete 语句。
在原有SSM基础上添加:Controller层/RestUserController.java
public class RestUserController {
@Autowired
private UserService userService;
@GetMapping("ones/{userId}")
public User select(@PathVariable Integer userId){
User user= userService.selectOne(userId);
return user;
}
@PostMapping("insert/{user}")
public int insert(User user){
int num=userService.insert(user);
return num;
}
}
此处使用了Postman软件————》方便查询
五、全局异常统一处理
?????概念:SpringMVC 对于异常处理这块提供了支持,通过 SpringMVC 提供的全局异常处理机制,能够将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
?全局异常实现方式 Spring MVC 处理异常有 3 种方式:
- 使用 Spring MVC 提供的简单异常处理器 SimpleMappingExceptionResolver
- 实现 Spring 的异常处理接口 HandlerExceptionResolver 自定义自己的异常处理器
- 使用 @ExceptionHandler 注解实现异常处理
1、简单异常处理器SimpleMappingExceptionResolver
- 在上面代码的原基础上增加配置
spring-servilet.xml:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"></property>
<property name="exceptionAttribute" value="ex"></property>
</bean>
创建错误响应页面:error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${ex}--->异常处理......
</body>
</html>
修改UserController.java
@RequestMapping("select")
@ResponseBody
public User select(Integer userId){
userId=userId/0;
return userService.selectOne(userId);
}
2、自定义异常
- 增加包exceptions/ParamException.java
public class ParamException extends RuntimeException {
private String msg;
private int code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public ParamException() {
super("参数异常");
}
public ParamException(String msg){
super("参数异常");
this.msg=msg;
}
public ParamException(int code){
super("参数异常");
this.code=code;
}
public ParamException(String msg,int code){
super("参数异常");
this.code=code;
this.msg=msg;
}
}
修改controller/UserController.java
@RequestMapping("select")
@ResponseBody
public User select(Integer userId){
if(userId == 0){
throw new ParamException("参数异常");
}
return userService.selectOne(userId);
}
结果:
自定义映射可以映射专门的处理页面
<!-- 自定义 异常的映射-->
<property name="exceptionMappings">
<props>
<prop >
key="com.yjxxt.ssm.exceptions.ParamException">param_error</prop>
</props>
</property>
3、实现HandlerExceptionResolver接口?
- 直接编写一个实现类GlobleException,省去了在spring-servlet.xml文件种配置
@Component
public class GlobleException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) {
ModelAndView mav=new ModelAndView("error");
mav.addObject("ex",ex);
if(ex instanceof ParamException){
ParamException e=(ParamException) ex;
mav.addObject("code",e.getCode());
mav.addObject("msg",e.getMsg());
mav.setViewName("param_error");
}
return mav;
}
}
创建异常接受页面param_error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}---->erro异常
</body>
</html>
使用实现 HandlerExceptionResolver 接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。
第三种方法略,平时推荐使用第二种方法~~~完!
|