<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h2>首页1</h2> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2>登录页</h2> <form action="/my01_war/login" method="post"> <div> 账号:<input type="text" name="username"/> </div> <div> 密码:<input type="text" name="password"/> </div> <input type="submit" /> </form> </body> </html>
package java0808; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username =req.getParameter("username"); String password = req.getParameter("password"); System.out.println("账号为"+username); System.out.println("密码为"+password); if (username.equals("zs")&&password.equals("123")){ HttpSession session = req.getSession(); session.setAttribute("isLogin",true); resp.sendRedirect(req.getContextPath()+"/index.html"); } else { resp.setContentType("text/plain;charset=UTF8"); resp.getWriter().write("登陆失败"); resp.sendRedirect(req.getContextPath()+"/login.html"); } } }
package java0808; import org.jboss.weld.context.http.Http; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebFilter("/*") public class MyFilter implements Filter { //过滤器 @Override public void init(FilterConfig filterConfig) throws ServletException {//init指的是初始化 System.out.println("过滤器的初始化"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF8"); System.out.println("经过过滤器要做的事情"); HttpServletRequest httpServletRequest =(HttpServletRequest) request; HttpServletResponse httpServletResponse=(HttpServletResponse) response; String path=httpServletRequest.getServletPath(); if ("/login.html".equals(path)||"/login".equals(path)){ chain.doFilter(request, response); return; } HttpSession session = httpServletRequest.getSession();//获得session boolean isLogin = false; if (session.getAttribute("isLogin")!=null) isLogin=(Boolean)session.getAttribute("isLogin"); if (isLogin) { chain.doFilter(request, response); return; } ((HttpServletResponse) response).sendRedirect(httpServletRequest.getContextPath()+"/login.html"); } @Override public void destroy() { System.out.println("销毁"); } }