SpringMVC攔截器:解決專案中介面(url)訪問許可權的問題(通過url不能隨意訪問controller層)
阿新 • • 發佈:2018-12-09
層次關係
攔截器實現HandlerInterceptor介面
package com.bybo.aca.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class Login implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object object) throws Exception {
/*HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;*/
String urlString = request.getRequestURI();
///olForum/forumList.html模擬登入頁
if(urlString.endsWith("forumList.html")){
return true;
}
//請求的路徑
String contextPath=request.getContextPath();
/*httpRequest.getRequestDispatcher("/olForum/forumList").forward(httpRequest, httpResponse);*/
/*response.sendRedirect(contextPath+"/olForum/forumList.html");*/
response.sendRedirect(contextPath + "/olForum/forumList.html?login=aaa");
return false;
/*httpResponse.sendRedirect(httpRequest.getContextPath()+"/olForum/forumList.html");
return;*/
}
}
spring.xml
<mvc:interceptors>
<!-- 使用bean定義一個Interceptor,直接定義在mvc:interceptors根下面的Interceptor將攔截所有的請求 -->
<!-- <bean class="com.bybo.aca.web.interceptor.Login"/> -->
<mvc:interceptor>
<!-- 進行攔截:/**表示攔截所有controller -->
<mvc:mapping path="/**" />
<!-- 不進行攔截 -->
<mvc:exclude-mapping path="/index.html"/>
<bean class="com.bybo.aca.web.interceptor.Login"/>
</mvc:interceptor>
</mvc:interceptors>