注销功能:
思路:移除session,返回登录页面
package com.Li.servlet.user;
//注销页面
import com.Li.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的session
req.getSession().removeAttribute(Constants.USER_SESSION);
//失败之后返回登陆页面。(重定向要加项目路径,转发不要加)
resp.sendRedirect("/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml
<!-- Servlet logout 注销-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.Li.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截优化
编写过滤器并且注册
package com.Li.filter;
import com.Li.pojo.User;
import com.Li.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;//用来获取session
HttpServletResponse response = (HttpServletResponse) resp;//用来重定向
//过滤器,从session中获取用户
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if (user==null){//已经被移除,或者注销了。将它移除到错误页面
response.sendRedirect("/smbms/error.jsp");
}else {//chain.dofilter作用是寻找下一个filter,但是user为null就没必要再寻找下一个filter过滤了所以写在false没问题。 可以写外面,但是没必要。
chain.doFilter(req, resp);//不要写错。要写原版本的。
}
}
public void destroy() {
}
}
web.xml
<!-- 用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.Li.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
<!-- 因为jsp页面下的都必须登录才能使用-->
</filter-mapping>