一、背景
最近在一个springmvc+mtbatis项目中配置自定义拦截器时发现了一些问题,主要就是由
二、解决方案
1.如果没有使用
自定义拦截器方法如下:
2.如果可以自己配置
博客地址:https://www.cnblogs.com/yangzhilong/p/3725849.html;
3.如果你即想使用
以下代码为我写的未登录点击链接拦截到登录页面的代码,因为只是演示拦截器冲突问题,就不再进行注释,如需解释,请联系我。
package cn.edu.tit.interceptor;
import java.io.PrintWriter;
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;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
Object obj = session.getAttribute("teacherId"); // 当前teacherid
// 判断点击的uri是否和登录页面有关,进行筛选
String[] noFilters = new String[] { "login", "Login" }; // url中如果有"login"和"handle"不拦截
String uri = request.getRequestURI();
boolean beFilter = true;//判断是否需要拦截,true拦截
if (uri.indexOf("mooc") != -1) { //判断链接是否为登录相关页面
for (String s : noFilters) {
if (uri.indexOf(s) != -1) {
beFilter = false;
break;
}
}
}
// 进行有野登录权限拦截
if (beFilter) {
if (null == obj) {
// 未登录
PrintWriter out = response.getWriter();
StringBuilder builder = new StringBuilder();
builder.append("");
// builder.append("spoc-mooc"); //这里是http://ip:port/项目名
// builder.append("/jsp/Teacher/index.jsp\";"); //这里是重新登录的页面url
out.print(builder.toString());
out.close();
return false;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
/**
* This implementation always returns {@code true}.
* @author wenli
* service之前执行
*
*/
}