客户端URL访问
- 客户端请求URL,到达DispacherServlet后,DispacherServlet调用某个Controller执行。而拦截器就是作用在DispacherServlet和Controller之间,当请求发生时,先判断该请求有没有设置拦截器,然后再往后进行。
- 自定义一个拦截器,需要实现org.springframework.web.servlet.HandlerInterceptor类
import com.yml.entity.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SessionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Admin admin = SessionUtils.getAdmin(request);
if(admin == null){
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("您没有权限,请<a href='login'>登录</a>");
return false;
}
return true;
}
@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 {
}
}
- 在SpringMVC.xml中配置拦截器
- mvc:mapping path是需要拦截的路径
- mvc:exclude-mapping path是排除拦截的路径(即该路径不使用拦截器)
- <bean class注入定义的拦截器类
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/*"/>
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/dy/*"/>
<mvc:exclude-mapping path="/static/**"/>
<mvc:exclude-mapping path="/reg"/>
<bean class="com.yml.utils.SessionInterceptor" />
</mvc:interceptor>
</mvc:interceptors>