springMVC拦截器HandlerInterceptor用法代码示例

时间:2022-11-18 17:50:12

摘要:很多时候我们都会去修改其他同事的bug,甚至是已经离职的同事的bug,有时候我们点击页面去不着到后台对应的是哪个controller,针对这个问题,其实我们可以通过sprngmvc的拦截器来拦击用户的请求从而知道页面请求的是哪个class的哪个方法,当然这些打印日志信息肯能并不适合放在生产环境,或者这个拦截器也是非必要的。。。。

一、HandlerInterceptor用法

第一步:注册拦截器

?
1
2
3
4
<!-- 注册拦截器 -->
    <mvc:interceptors>
        <bean class="com.project.base.interceptor.ControlInterceptor" />
    </mvc:interceptors>

第二步:继承HandlerInterceptor ,实现拦截器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.iflashbuy.limanman;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class ControlInterceptor implements HandlerInterceptor{
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 执行完控制器后调用,即离开时
     */
    @Override
        public void afterCompletion(HttpServletRequest request,
                HttpServletResponse response, Object arg2, Exception arg3)
                        throws Exception {
    }
    @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 arg1, Object arg2) throws Exception {
        int i = 1;
        try {
            @SuppressWarnings("unchecked")
                        Map<String, Object> parmMap = request.getParameterMap();
            Iterator<String> iter = parmMap.keySet().iterator();
            while (iter.hasNext()) {
                Object key = iter.next();
                Object value = parmMap.get(key);
                logger.info("第" + i + "个param---->{}-{}", key, value);
                i = i + 1;
            }
        }
        catch (Exception e) {
            i = 1;
        }
        i = 1;
        return true;
    }
}

二、后台打印信息效果

springMVC拦截器HandlerInterceptor用法代码示例

三、拓展使用拦截器实现http基本认证

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
     * 执行完控制器后调用,即离开时
     */
@Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object arg2, Exception arg3)
            throws Exception {
    logger.info("className--->" + arg2);
    logger.info("request--->" + request);
}
@Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {
}
@Override
    public Boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2) throws Exception {
    String sessionAuth = (String) request.getSession().getAttribute("auth");
    if (sessionAuth != null) {
        System.out.println("this is next step");
        nextStep(request, response);
    } else {
        if (!checkHeaderAuth(request, response)) {
            response.setStatus(401);
            response.setHeader("Cache-Control", "no-store");
            response.setDateHeader("Expires", 0);
            response.setHeader("WWW-authenticate", "Basic Realm=\"请输入管理员账号密码\"");
            return false;
        }
    }
    return true;
}
private Boolean checkHeaderAuth(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
    String auth = request.getHeader("Authorization");
    System.out.println("auth encoded in base64 is " + getFromBASE64(auth));
    if ((auth != null) && (auth.length() > 6)) {
        auth = auth.substring(6, auth.length());
        String decodedAuth = getFromBASE64(auth);
        System.out.println("auth decoded from base64 is " + decodedAuth);
        request.getSession().setAttribute("auth", decodedAuth);
        return true;
    } else {
        return false;
    }
}
private String getFromBASE64(String s) {
    if (s == null)
                return null;
    try {
        byte[] encodeBase64 = Base64.encodeBase64(s.getBytes("UTF-8"));
        return new String(encodeBase64);
    }
    catch (UnsupportedEncodingException e) {
        return null;
    }
}
public void nextStep(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
    System.out.println("you can go to the controller");
}

总结

以上就是本文关于springMVC拦截器HandlerInterceptor用法代码示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:https://my.oschina.net/fengshuzi/blog/364397