Spring拦截器

12 篇文章 0 订阅

Spring的拦截器配置文件

<mvc:interceptors>
    <mvc:interceptor>
         <mvc:mapping path="/**" />
          <!-- 不需要拦截的路径-->
          <mvc:exclude-mapping path="/login"/>           
         <bean class="com.springmvc.controller.interceptor.LoginInterceptor" />
    </mvc:interceptor>
   <!-- 可以配置多个 -->
</mvc:interceptors>

LoginInterceptor.java

package com.springmvc.controller.interceptor;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        logger.info("请求URL::" + request.getRequestURL().toString()
                + ":: Start Time=" + System.currentTimeMillis());
        request.setAttribute("startTime", startTime);
        //if returned false, we need to make sure 'response' is sent
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("请求URL::" + request.getRequestURL().toString()
                + " Sent to Handler :: Current Time=" + System.currentTimeMillis());
         //这里可以做业务操作如判断session中user,不存在做跳转。   
        //we can add attributes in the modelAndView and use that in the view page
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        long startTime = (Long) request.getAttribute("startTime");
        logger.info("请求URL::" + request.getRequestURL().toString()
                + ":: End Time=" + System.currentTimeMillis());
        logger.info("请求URL::" + request.getRequestURL().toString()
                + ":: Time Taken=" + (System.currentTimeMillis() - startTime));
    }
 
}

UserController.java

package com.springmvc.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class UserController { 
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);	 
	
	/**
	 * 测试拦截器	
	 * @param model
	 * @return
	 */
	 @RequestMapping(value = "/home", method = RequestMethod.GET)
	    public String home(Model model) {
		 	logger.info("Welcome home! ");
	        try {
	            Thread.sleep(1000);
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
	         
	        model.addAttribute("serverTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	        logger.info("Before returning view page");
	        return "home";
	    }

}

浏览器URL测试 :http://localhost:8080/example/home

Spring框架中,拦截器是一种可以拦截请求并在处理请求之前或之后执行自定义逻辑的组件。它们可以用于实现身份验证、授权、日志记录等功能。下面是使用拦截器的步骤: 1. 创建一个类并实现`HandlerInterceptor`接口。 2. 在类中实现`preHandle`、`postHandle`和`afterCompletion`方法,分别在请求处理之前、请求处理之后和视图渲染完成后执行特定的逻辑。 3. 在配置文件中注册拦截器,并指定拦截的URL模式或特定路径。 以下是一个简单的例子: ```java public class CustomInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前执行的逻辑 return true; // 返回true继续处理请求,返回false终止请求处理 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 在请求处理之后但视图渲染之前执行的逻辑 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在视图渲染完成后执行的逻辑 } } ``` 在配置文件中注册拦截器: ```xml <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <!-- 拦截所有URL --> <bean class="com.example.CustomInterceptor"/> </mvc:interceptor> </mvc:interceptors> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值