未登录跳转登录页面
package cn.tedu.filter; 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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.tedu.bean.User; /** * Servlet Filter implementation class CheckLogin */ @WebFilter("/web/*") public class CheckLogin implements Filter { /** * Default constructor. */ public CheckLogin() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //1.获取session的user属性值,判断为空的话,说明没登陆过,跳转到login.jsp页面 //2.不为空,调用doFilter方法
//强转为httpservletrequest和httpservletresponse HttpServletRequest rq=(HttpServletRequest)request; HttpServletResponse rp=(HttpServletResponse)response; User user= (User) rq.getSession().getAttribute("user"); if(user==null){ rp.sendRedirect("/TeduStore/login.jsp"); } chain.doFilter(rq, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }