玩转spring MVC(七)----拦截器

继续在前边的基础上来学习spring MVC中拦截器的使用,下面通过一个例子来实现(完整项目在这里下载:http://download.csdn.net/detail/u012116457/8433425)。

首先在项目中添加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则执行登陆逻辑,否则跳转到提示页面。


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。