[Spring MVC] - Interceptor 拦截器

Spring MVC中的Interceptor与Struts2的差不多。

下面是一个简单的Interceptor登陆验证例子:

 

1、需要在spring的配置文件中加入这段:

    <!-- 自定义拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.my.controller.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

 

2、LoginInterceptor

package com.my.controller.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception exception)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView view) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        final String ENC = "UTF-8";
        String fullPath = request.getRequestURI();
        String queryString = request.getQueryString();
        String contextPath = request.getContextPath();
        String controllerPath = fullPath.replace(contextPath, "");
        
        HttpSession session = request.getSession();
        Object account = session.getAttribute("account");
        
        if(queryString != null && !queryString.trim().equals("")) {
            queryString = "?" + queryString;
        }
        
        if(!controllerPath.startsWith("/passport") && account == null) {
            response.sendRedirect(contextPath + "/passport?path=" + URLEncoder.encode(contextPath + controllerPath + queryString, ENC));
        }
        
        return true;
    }
    
}

 

3、PassportController

package com.my.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.my.controller.bean.Account;

@Controller
@RequestMapping(value="passport")
public class PassportController {
    
    @RequestMapping(method=RequestMethod.GET)
    public String index(@RequestParam(value="path", defaultValue="/") String path, Model model) throws UnsupportedEncodingException {
        model.addAttribute("account", new Account());
        model.addAttribute("path", URLEncoder.encode(path,"UTF-8"));
        return "login/index";
    }
    
    @RequestMapping(value="login", method=RequestMethod.POST)
    public ModelAndView login(@ModelAttribute @Valid Account account, BindingResult result, @RequestParam(value="path", defaultValue="/") String path,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView view = new ModelAndView("login/index");
        request.getSession(false).setAttribute("account", account);
        if(path != null && path.trim() != "") {
            response.sendRedirect(URLDecoder.decode(path, "UTF-8"));
        }
        return view;
    }
    
    @RequestMapping(value="logout", method=RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("account");
        
        return "redirect:/passport";
    }
    
}

 

4、index.jsp view

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
    <form:form action="${pageContext.request.contextPath}/passport/login?path=${path}" method="post" modelAttribute="account">
    User name:<form:input path="userName"/><form:errors path="userName"/><br/>
    Password:<form:password path="password"/><form:errors path="password" /><br/>
    <input type="submit" value="Login" />
    </form:form>
</body>
</html>

 

5、测试

posted @ 2014-11-28 10:26  横渡  阅读(9667)  评论(1编辑  收藏  举报