登录功能优化
- 注销功能:
思路:移除session,返回登录页面
1.写注销Servlet
package com.gongyi.servlet.user;
import com.gongyi.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 {
//移除用户的Constants.USER_SESSION
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录页面
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.注册web.xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.gongyi.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
- 登录拦截优化
1.编写一个过滤器并注册
过滤器:
package com.gongyi.filter;
import com.gongyi.pojo.User;
import com.gongyi.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//过滤器,从session中获取用户
User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
if (user == null) {//已经被移除或者注销了,或者未登录
response.sendRedirect(request.getContextPath() + "/error.jsp");
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
}
注册web.xml
<!--用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.gongyi.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>请登录后再访问该页面</h1>
<a href="${pageContext.request.contextPath }/login.jsp">返回</a>
</body>
</html>
2.测试登录,注销,权限都要保证ok
效果图:
登录后自动跳转到http://localhost:8080/smbms_war/jsp/frame.jsp
注销后,再次访问:http://localhost:8080/smbms_war/jsp/frame.jsp
重定向到了:http://localhost:8080/smbms_war/error.jsp
彩蛋
1.web.xml中配置servlet-class,输入类名回车即可补全全路径
2.idea实现接口没有@Override关键字
图形化界面重写方法ok:
解决:注解是JDK1.5之后的特性
修改idea的module中的language level大于5【默认是5】
3.发布tomcat编译报错:【未涉及到具体业务代码】
思路:jdk版本 设置一致