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>
復制代碼

其它與上述的一樣


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM