Spring MVC重定向和转发以及异常处理
SpringMVC核心技术---转发和重定向
当处理器对请求处理完毕后,向其他资源进行跳转时,有两种跳转方式:请求转发与重定向。而根据要跳转的资源类型,又可分为两类:跳转到页面与跳转到其他处理器。
对于请求转发的页面,也可以是WEB-INF中页面;对于重定向的页面,不能为WEB-INF中的页面。因为重定向相当于用户再次发出一次请求,而用户是不能直接访问WEB-INF中资源的


1)重定向到页面
FirstController.java
package cn.controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; /**
*
* @author 景佩佩
*
*/
@Controller
public class FirstController {
@RequestMapping(value="/first.do")
public String doAddOrder(Model model,String uname,int uage){
model.addAttribute("uname", uname);
model.addAttribute("uage",uage); return "redirect:/welcome.jsp";
} }
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<style type="text/css">
form{
margin:0px auto;
/* border:1px solid red; */
width:500px; }
</style>
<title></title>
</head> <body>
<form action="${pageContext.request.contextPath }/first.do" method="post">
姓名:<input name="uname"/><br/><br/>
年龄:<input name="uage"/><br/><br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>欢迎页面</title> </head>
<h1>欢迎访问${uname }${param.uage }</h1> </body>
</html>


2)重定向到控制器:
FirstController.java
package cn.controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; /**
*
* @author 景佩佩
*
*/
@Controller
public class FirstController {
//处理器方法 doFirst==========》doSecond
@RequestMapping(value="/first.do")
public String doAddOrder(Model model,String uname,int uage){
model.addAttribute("uname", uname);
model.addAttribute("uage",uage); return "redirect:second.do";
} @RequestMapping(value="/second.do")
public String doList(Model model,String uname,int uage){
model.addAttribute("uname", uname);
model.addAttribute("uage",uage);
System.out.println(uname+"==================");
return "redirect:/welcome.jsp";
} }
其它与上述相同
转发与重定向一样,就不多做解释
异常处理
描述
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。
分析
Spring MVC处理异常常见有4种方式:
1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
2)实现Spring的异常处理SimpleMappingExceptionResolver自定义自己的异常处理器
3)实现HandlerExceptionResolver 接口自定义异常处理器
4)使用注解@ExceptionHandler实现异常处理
我们先介绍三种:
案例
系统异常处理SimpleMappingExceptionResolver

web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<style type="text/css">
form{
margin:0px auto;
background-color:pink;
width:500px;
}
</style>
<title></title>
</head> <body>
<h1>系统异常处理</h1>
<form action="${pageContext.request.contextPath }/first.do" method="post">
姓名:<input name="name"/><br/><br/>
年龄:<input name="age"/><br/><br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>
errors.jsp(报错是跳转到此页面)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>错误页面</title>
</head> <body>
<h1>我是所有错误消息显示页面</h1>
${ex.message }
</body>
</html>
MyController.java(定义处理器)
package cn.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author 景佩佩
*
*/
@Controller
public class MyController {
//处理器方法
@RequestMapping(value="/first.do")
public String doFirst(){
//构造异常
int result=5/0;
return "/WEB-INF/index.jsp";
} }
applicationContext.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:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan> <!-- 注册系统异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="errors.jsp"></property>
<property name="exceptionAttribute" value="ex"></property> </bean> </beans>
效果:


实现Spring的异常处理接口SimpleMappingExceptionResolver自定义自己的异常处理器

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
error包中是指定错误页面
nameerrors.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>错误页面</title>
</head> <body>
<h1>用户名错误</h1>
${ex.message }
</body>
</html>
ageerrors.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>错误页面</title>
</head> <body>
<h1>年龄错误</h1>
${ex.message }
</body>
</html>
FirstController.java
package cn.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.exceptions.AgeException;
import cn.exceptions.NameException;
import cn.exceptions.UserInfoException; /**
*
* @author 景佩佩
*
*/
@Controller
public class FirstController {
//处理器方法
@RequestMapping(value="/first.do")
public String doFirst(String name,int age) throws UserInfoException{ if (!"hh".equals(name)) {
throw new NameException("用户名错误");
} if (age>40) {
throw new AgeException("年龄太大");
} return "index.jsp";
}
}
exception包下,指定异常类
UserInfoException.java
package cn.exceptions;
/**
*
* @author 景佩佩
*
*/
public class UserInfoException extends Exception{ public UserInfoException() {
super();
// TODO Auto-generated constructor stub
} public UserInfoException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }
NameException.java
package cn.exceptions;
/**
*
* @author 景佩佩
*
*/
public class NameException extends UserInfoException{ public NameException() {
super();
// TODO Auto-generated constructor stub
} public NameException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }
AgeException.java
package cn.exceptions; /**
*
* @author 景佩佩
*
*/
public class AgeException extends UserInfoException{ public AgeException() {
super();
// TODO Auto-generated constructor stub
} public AgeException(String message) {
super(message);
// TODO Auto-generated constructor stub
} }
applicationContext.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:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 配置包扫描器-->
<context:component-scan base-package="cn.controller"></context:component-scan>
<!-- 注册系统异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="errors.jsp"></property>
<property name="exceptionAttribute" value="ex"></property> <property name="exceptionMappings">
<props>
<prop key="cn.exceptions.NameException">error/nameerrors.jsp</prop>
<prop key="cn.exceptions.AgeException">error/ageerrors.jsp</prop>
</props>
</property>
</bean> </beans>
效果:




实现HandlerExceptionResolver 接口自定义异常处理器
使用Springmvc定义好的SimpleMappingExceptionResolver异常处理器,可以实现发生指定异常后的跳转。但是若要实现在捕获到指定异常时,执行一些操作的目的,它是完成不了的。此时,就需要自定义异常处理器。自定义异常处理器,需要实现HandlerExceptionResolver接口,并且该类需要在Springmvc配置文件中进行注册

定义自己的异常处理类
package cn.resolvers; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import cn.exceptions.AgeException;
import cn.exceptions.NameException; /**
*
* @author 景佩佩
*
*/
public class MyHandlerExceptionResolver implements HandlerExceptionResolver{ public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv=new ModelAndView();
mv.addObject("ex",ex); mv.setViewName("/errors.jsp"); //view
if(ex instanceof NameException){
mv.setViewName("/error/nameerrors.jsp");
} if(ex instanceof AgeException){
mv.setViewName("/error/ageerrors.jsp");
} return mv;
} }
applicationContext.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:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan>
<!-- 注册自定义异常处理器 -->
<bean class="cn.resolvers.MyHandlerExceptionResolver"/> </beans>
其它与上述的一样
异常处理注解@ExceptionHandler
1)异常处理注解@ExceptionHandler第一版

其它配置都一样
@ExceptionHandler()可以不写或者顶级异常或者与之指定的异常
package cn.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import cn.exceptions.AgeException;
import cn.exceptions.NameException;
import cn.exceptions.UserInfoException;
/**
*
* @author 景佩佩
*
*/
@Controller
public class MyController extends BaseController{
//处理器方法
@RequestMapping(value="/first.do")
public String doFirst(String name,int age) throws UserInfoException{
if (!"hh".equals(name)) {
throw new NameException("用户名错误");
}
if (age>40) {
throw new AgeException("年龄太大");
}
return "/WEB-INF/jsp/index.jsp";
} @ExceptionHandler
public ModelAndView handlerException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("ex",ex); mv.setViewName("/errors.jsp"); //view
if(ex instanceof NameException){
mv.setViewName("/error/nameerrors.jsp");
} if(ex instanceof AgeException){
mv.setViewName("/error/ageerrors.jsp");
} return mv;
}
}
applicationContext.xml===(只需写一个包扫描器就行)

index.jsp

error.jsp(错误页面)
效果:


Spring MVC重定向和转发以及异常处理的更多相关文章
- Spring MVC重定向和转发及异常处理
SpringMVC核心技术---转发和重定向 当处理器对请求处理完毕后,向其他资源进行跳转时,有两种跳转方式:请求转发与重定向.而根据要跳转的资源类型,又可分为两类:跳转到页面与跳转到其他处理器.对于 ...
- Spring MVC重定向和转发
技术交流群:233513714 转发和重定向 开始Java EE时,可能会对转发(forward)和重定向(redirect)这个两个概念不清楚.本文先通过代码实例和运行结果图片感性 认识二者的区别, ...
- spring mvc 重定向加传参
常用: ModelAndViewi: return new ModelAndView("redirect:/toList"); 或者 ii:return "redire ...
- spring mvc重定向
spring mvc重定向有三种方法. 1.return new ModelAndView("redirect:/toUrl"); 其中/toUrlt是你要重定向的url. 2.r ...
- Spring MVC 的视图转发
Spring MVC 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作 1.使用RedirectView public ModelAndView login(){ RedirectView ...
- spring mvc重定向方法
一.不带参数,直接重定向到另一个地址: 返回String直接跳转,如: @RequestMapping(value = "/filehandle") public String u ...
- Spring MVC源码(四) ----- 统一异常处理原理解析
SpringMVC除了对请求URL的路由处理特别方便外,还支持对异常的统一处理机制,可以对业务操作时抛出的异常,unchecked异常以及状态码的异常进行统一处理.SpringMVC既提供简单的配置类 ...
- spring mvc 重定向问题
(1)我在后台一个controller跳转到另一个controller,为什么有这种需求呢,是这样的.我有一个列表页面,然后我会进行新增操作,新增在后台完成之后我要跳转到列表页面,不需要传递参数,列表 ...
- spring mvc 和mybatis整合 的异常处理
1.自定义异常信息类 通过构造函数来实现异常信息的接收 public class CustomException extends Exception { //异常信息 private String m ...
随机推荐
- HTML5 input元素新的特性
在HTML5中,<input>元素增加了许多新的属性.方法及控件.本文章分别对这三方面进行介绍. 目录 1. 属性 2. 方法 3. 新控件 1. 属性 <input>元素在H ...
- B样条基函数的定义和性质
定义:令U={u0,u1,…,um}是一个单调不减的实数序列,即ui≤ui+1,i=0,1,…,m-1.其中,ui称为节点,U称为节点矢量,用Ni,p(u)表示第i个p次(p+1阶)B样条基函数,其定 ...
- Spark踩坑记——初试
[TOC] Spark简介 整体认识 Apache Spark是一个围绕速度.易用性和复杂分析构建的大数据处理框架.最初在2009年由加州大学伯克利分校的AMPLab开发,并于2010年成为Apach ...
- seaJs学习笔记2 – seaJs组建库的使用
原文地址:seaJs学习笔记2 – seaJs组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
- C# 索引器,实现IEnumerable接口的GetEnumerator()方法
当自定义类需要实现索引时,可以在类中实现索引器. 用Table作为例子,Table由多个Row组成,Row由多个Cell组成, 我们需要实现自定义的table[0],row[0] 索引器定义格式为 [ ...
- 【转】外部应用和drools-wb6.1集成解决方案
一.手把手教你集成外部应用和drools workbench6.1 1. 首先按照官方文档安装workbench ,我用的是最完整版的jbpm6-console的平台系统,里面既包含j ...
- 【SAP业务模式】之ICS(二):基础数据
讲完业务,计划在前台做一下ICS的基本操作,不过在操作之前,得先建立好基本的基础数据. 1.首先创建接单公司LEON,对应工厂是ADA: 2.创建生产公司MXPL,对应工厂是PL01: 3.创建接单公 ...
- Selenium-java-获取当前时间
1 获取当前时间 // 获取当前时分秒 Calendar now = Calendar.getInstance(); int is = now.get(Calendar.HOUR_OF_DAY); i ...
- ASP.NET MVC 视图(三)
ASP.NET MVC 视图(三) 前言 上篇对于Razor视图引擎和视图的类型做了大概的讲解,想必大家对视图的本身也有所了解,本篇将利用IoC框架对视图的实现进行依赖注入,在此过程过会让大家更了解的 ...
- CSharpGL(8)使用3D纹理渲染体数据 (Volume Rendering) 初探
CSharpGL(8)使用3D纹理渲染体数据 (Volume Rendering) 初探 2016-08-13 由于CSharpGL一直在更新,现在这个教程已经不适用最新的代码了.CSharpGL源码 ...