jsp不使用filter登陆例子(IntelliJ IDEA 2016)

1.新建web application项目,设置好服务器和library。
2.添加login.jsp, success.jsp, fail.jsp三个文件:

  • login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

      
    login
  
  
    
username: password:
  • success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

   
     Title
  
  
    login successfully! welcome ${username}
  

  • fail.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

      
    Title
  
  
    login fail
  

3.新建servlet包--LoginServlet类

  • LoginServlet
package servlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginServlet extends javax.servlet.http.HttpServlet {     
      protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
          String username = request.getParameter("username"); 
          String password = request.getParameter("password");
          if ("admin".equals(username) && "admin".equals(password)) {         
              //check success           
              HttpSession session = request.getSession();
              session.setAttribute("username", username); 
              response.sendRedirect(request.getContextPath()  + "/success.jsp");        
          } else { 
              //check fail 
              response.sendRedirect(request.getContextPath() + "/fail.jsp");        
          }    
      }    
      protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    }
}

4.修改web.xml

  • web.xml

    
            
       LoginServlet        
       servlet.LoginServlet   
        
        
      LoginServlet        
      /servlet/LoginServlet    
    

5.启动服务器打开127.0.0.1:8080/project_name/login.jsp
6.弊端:
不安全,可以随意打开success.jsp

你可能感兴趣的:(jsp不使用filter登陆例子(IntelliJ IDEA 2016))