新建SecurityFilter.Java
- package org.thj.bookstore.util;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class SecurityFilter implements Filter {
- public void destroy() {
- }
- public void doFilter(ServletRequest req, ServletResponse res,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest)req;
- HttpServletResponse response = (HttpServletResponse)res;
- if(request.getSession().getAttribute("user")==null){
- String path = request.getContextPath();
- //没有登陆就跳到index.jsp
- response.sendRedirect(path + "/index.jsp");
- }
- else{
- chain.doFilter(request,response);
- }
- }
- public void init(FilterConfig arg0) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
在web.xml中注册:
- <filter>
- <filter-name>securityFilter</filter-name>
- <filter-class>org.thj.bookstore.util.SecurityFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>securityFilter</filter-name>
- <url-pattern>/jsp/*</url-pattern>
- </filter-mapping>
- <!--只过滤jsp目录下的所以页面-->
- <filter-mapping>
- <filter-name>userlogin</filter-name>
- <url-pattern>/jsp/user/*</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>userlogin</filter-name>
- <url-pattern>/jsp/ques/*</url-pattern>
- </filter-mapping>