servlet的简单登录

xiaoxiao2021-02-28  4

servlet有2个核心:request和response

通过request传入数据,response响应

 

1.LoginServlet.java

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

/**    * @Title:  com.zrcx.servlet.LoginServlet.java  * @Description: servlet登录  * @Copyright: Copyright (c) 2017  * @Company:  * @author: ***  * @date:   * @version: V1.0    */ public class LoginServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override  public void init(ServletConfig config) throws ServletException {   System.out.println("初始化....");  }   

 @Override  public void destroy() {   System.out.println("servlet关闭....");  }  

 @Override  protected void service(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {   String username = request.getParameter("username");   String password = request.getParameter("password");   System.out.println("用户名:" + username);   System.out.println("密码:" + password);   arg1.setContentType("text/html;charset=UTF-8");   PrintWriter out = arg1.getWriter();   out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");   out.println("<HTML>");   out.println("  <HEAD><TITLE>登录结果页面</TITLE></HEAD>");   out.println("  <BODY>");   if ("abc".equals(username) && "123".equals(password)) {    out.print("<center><h1>用户登录成功</h1></center>");    //获取会话对象    HttpSession session = request.getSession();    session.setAttribute("ticket", "门票");    System.out.println("会话ID:" + session.getId());   }else{    out.print("<center><h1>用户登录失败</h1></center>");    }   out.println("  </BODY>");   out.println("</HTML>");   out.flush();   out.close();  }

}

 

2.login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录页面</title> <style type="text/css">   </style> </head> <body>  <form action="LoginServlet" method="get">  <table>  <tr>  <td>用户名:</td>  <td>   <input type="text" name = "username">  </td>  </tr>  <tr>  <td>密  码:</td>  <td>   <input type="password" name = "password">  </td>  </tr>  <tr>  <td> </td>   <td>   <input type="submit" value="登录" name ="btn1" />    <input name ="reset" type="reset" value="重置" οnclick="resetAll();"/>    </td>   </tr>   </table>  </form> </body> </html>

 

转载请注明原文地址: https://www.6miu.com/read-1750179.html

最新回复(0)