1、登录页面
Java代码
public class login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if (username.equals("wjj") && password.equals("123")) {
req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
} else {
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
Jsp代码
<form action="/servlet/login" method="post" style="text-align: center">
账号:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit" value="登录">
</form>
2、成功页面
<h1 style="text-align: center">主页</h1>
<h3 style="text-align: center">登陆成功,欢迎你。</h3>
<p style="text-align: center"> <a href="/servlet/loginout">注销</a> </p>
3、失败页面
<h2 style="text-align: center">登陆失败,用户名或者密码错误。请重试!</h2>
<p style="text-align: center"> <a href="/login.jsp">返回登录页面。</a> </p>
4、用户是否非法登录过滤器实现
Java代码
public class LoginFilter 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;
Object userSession = request.getSession().getAttribute(Constant.USER_SESSION);
if (userSession == null) {
response.sendRedirect("/error.jsp");
}
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
}
}
web.xml代码
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.wjj.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
5、注销登录
public class loginout extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if (user_session != null) {
req.getSession().removeAttribute(Constant.USER_SESSION);
// resp.sendRedirect("/login.jsp");
resp.setHeader("refresh","1;/login.jsp");
} else {
resp.setHeader("refresh","1;/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}