1. 程式人生 > >玩轉spring MVC(七)----攔截器

玩轉spring MVC(七)----攔截器

首先在專案中新增interceptor-servlet.xml來配置攔截器,當然,必須在web.xml中配置在tomcat啟動時載入,如下:

 <!--1.配置spring分發器(是總的控制中心  被攔截的url會匯聚到該servlet) -->
	<servlet>
	    <servlet-name>springmvc</servlet-name>  
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <!--配置spring上下文  (從該目錄下載入spring mvc的配置檔案) -->
	    <init-param>
	       <param-name>contextConfigLocation</param-name>
	       <param-value>/WEB-INF/classes/spring/*servlet.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>  <!-- tomcat啟動後立即載入 -->
	</servlet>
這個攔截器主要實現的功能是在頁面請求登陸時,如果在允許登陸時時間範圍內,則正常執行,否則跳轉到某一特定頁面。

interceptor-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:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd            
    http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd                 http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd                 
    http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-3.0.xsd">
  
  <!-- 攔截器 -->
	<mvc:interceptors>
	    <!-- 多個攔截器,順序執行 -->
	    <!-- 攔截器1 登陸攔截 -->
	    <mvc:interceptor>
	       <mvc:mapping path="/login/login.do" /><!-- 可以寫多個,如果為/*,將攔截所有的Controller -->
	       <bean class="module.interceptor.LoginInterceptor">
	            <!--startTimeStr 屬性指定允許登陸的開始時間-->  
                <property name="startTimeStr">  
                    <value>07:00:00</value>  
                </property>  
                <!--endTimeStr 屬性指定允許登陸的結束時間-->  
                <property name="endTimeStr">  
                    <value>23:00:00</value>  
                </property>  
                <!--outTimePageUrl  屬性指定不在時間範圍內時,提示頁面的URL-->  
                <property name="outTimePageUrl">  
                    <value>http://localhost:8080/springMVC/index.jsp  
                    </value>  
                </property>  
	       </bean>
	    </mvc:interceptor>
	</mvc:interceptors>
	
</beans>

請求被攔截後處理類:
package module.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;

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

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

/**
 * 登陸操作的攔截器
 * 
 * @author Administrator
 * 
 */
public class LoginInterceptor implements HandlerInterceptor {

	private String startTimeStr;
	private String endTimeStr;
	private String outTimePageUrl;

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		SimpleDateFormat hms=new SimpleDateFormat("HH:mm:ss");
		Date startTimeDat=hms.parse(startTimeStr);
		Date endTimeDat=hms.parse(endTimeStr);
		Date now = new Date();
		String nowHMS = hms.format(now);
		now=hms.parse(nowHMS);
		
	    if(startTimeDat.before(now)&&now.before(endTimeDat)){   //當前時間在規定的時間範圍內
	    	System.out.println("當前時間允許登陸");
	    	return true;			
		}else{
			System.out.println("當前時間不允許登陸");
			response.sendRedirect(outTimePageUrl); // 返回提示頁面  
			return false;
		}
	}
    //get和set方法
	public String getStartTimeStr() {
		return startTimeStr;
	}

	public void setStartTimeStr(String startTimeStr) {
		this.startTimeStr = startTimeStr;
	}

	public String getEndTimeStr() {
		return endTimeStr;
	}

	public void setEndTimeStr(String endTimeStr) {
		this.endTimeStr = endTimeStr;
	}

	public String getOutTimePageUrl() {
		return outTimePageUrl;
	}

	public void setOutTimePageUrl(String outTimePageUrl) {
		this.outTimePageUrl = outTimePageUrl;
	}

}
登陸頁面的控制類如下:
package module.controller;

import javax.annotation.Resource;

import module.entity.User;
import module.service.LoginService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/login")
public class LoginController {

	private static String INDEX = "module/jsp/index";
	private static String LOGIN = "module/jsp/login";

	
	//@Autowired() @Qualifier("loginServiceImpl2")  
	@Resource(name="loginServiceImpl2")
	private LoginService loginService;
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String login(User user) {
		System.out.println(user.getName());
		User u = loginService.findByName(user.getName());
		if (u != null)
			System.out.println(u.getPassword());
		if ("admin".equals(user.getName()))
			return INDEX;
		return LOGIN;
	}

}

當客戶端發來請求:http://localhost:8080/springMVC/login/login.do時,請求會被攔截,提交給LoginInterceptor進行處理,返回true則執行登陸邏輯,否則跳轉到提示頁面。