Filter攔截器-登入
由於頁面可以通過路徑及檔名直接訪問,出於安全考慮,使用Filter攔截器進行攔截,判斷是否已經登入,否則跳轉到登陸頁面通過實現Filter,關鍵程式碼如下
private FilterConfig config = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest)request;
HttpServletResponse response1 = (HttpServletResponse)response;
HttpSession session = request1.getSession();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Users user = (Users) session.getAttribute(Conts.SESSION_NAME);
String pat = request1.getRequestURI();
//!pat.endsWith("login.jsp") 不過濾登入頁
if(null == user && !pat.endsWith("login.jsp")){
System.out.println("沒有登入");
response1.sendRedirect(request1.getContextPath()+"/login.jsp");
} else{
System.out.println("已經登入");
chain.doFilter(request,response);
}
}
web.xml配置
<filter>
<filter-name>control</filter-name>
<filter-class>com.sms.servlet.control</filter-class>
</filter>
<filter-mapping>
<filter-name>control</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
由於我這是後臺,所以我這裡過濾所有的jsp,也可以寫成 <url-pattern>/xxx目錄</url-pattern>即表示過濾這個目錄下所有檔案
這裡的Conts.SESSION_NAME 是一個靜態SESSION常量,方便於後期修改 如下:
public class Conts {
public final static String SESSION_NAME = "Login";
}