登录功能优化
实现注销功能
- 移除session
- 返回登陆页面
LogoutServlet.java
package com.hao.servlet.user;
import com.hao.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 {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除Session
req.getSession().removeAttribute(Constants.USER_SESSION);
//返回登陆页面
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
}
在xml中注册
<!-- 注销-->
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.hao.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
登录拦截优化
- 编写过滤器
- 注册过滤器
SysFilter.java
package com.hao.filter;
import com.hao.pojo.User;
import com.hao.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 servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if (user==null){//说明对象已被移除
response.sendRedirect("/SMBMS/error.jsp");
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
public void destroy() {
}
}
注册
<!-- 登陆过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.hao.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
访问测试
- 正常登录
- 退出
- 直接访问网址