老紫竹JavaEE培训教程(3)- 登录表单和密码判断

来源:互联网 发布:kali linux怎么更新源 编辑:程序博客网 时间:2024/05/19 14:01


1 登录页面的代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%
  3.   /** 
  4.    *  老紫竹JavaEE培训教程(2)- 登录表单和密码判断 
  5.    */
  6. %>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  11. <title>登录</title>
  12. </head>
  13. <body>
  14. 登录
  15. <form method="post" name="LOGIN_FORM" id="LOGIN_FORM" action="logincheck.jsp"><br />
  16. 用户名:<input type="text" id="username" name="username" size="20" maxlength="20" /><br />
  17. 密码:<input type="password" id="password" name="password" size="20" maxlength="20" /><br />
  18. <input type="submit" value="登录" /></form>
  19. </body>
  20. </html>
2 登录判断的代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <%
  3.   /** 
  4.    *  老紫竹JavaEE培训教程(2)- 登录表单和密码判断 
  5.    */
  6. %>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  11. <title>登录检测</title>
  12. </head>
  13. <body>
  14. <a href="login.jsp">返回登录</a>
  15. <%
  16.   // 设置请求数据的编码方式
  17.   // 应尽可能放在其它代码的前面
  18.   request.setCharacterEncoding("UTF-8");
  19.   // 判断登录方式必须是POST
  20.   if ("POST".equals(request.getMethod())) {
  21.     // 从request对象里读取参数
  22.     String username = request.getParameter("username");
  23.     String password = request.getParameter("password");
  24.     // 判断用户名和密码必须填写
  25.     if (username == null || username.trim().length() == 0) {
  26.       out.println("请填写用户名");
  27.     } else if (password == null || password.trim().length() == 0) {
  28.       out.println("请填写密码");
  29.     } else {
  30.       // 去掉前后的空格等
  31.       username = username.trim();
  32.       password = password.trim();
  33.       // 判断用户名和密码
  34.       if ("admin".equals(username) && "1234".equals(password)) {
  35.         out.println("登录成功");
  36.       } else {
  37.         out.println("用户名或密码失败!");
  38.       }
  39.     }
  40.   } else {
  41.     out.print("请使用POST提交方式");
  42.   }
  43. %>
  44. </body>
  45. </html>

3 运行
http://127.0.0.1:8080/j2ee/login.jsp

用户名为:admin
密码为:1234

4 测试
  • 不输入任何东西,直接提交
  • 只输入用户名,提交
  • 只输入密码,提交
  • 输入错误的用户名,提交
  • 输入错误的密码,提交
  • 输入正确的用户名和密码,提交
  • 手工输入 http://127.0.0.1:8080/j2ee/logincheck.jsp 看看效果


登录是表单操作的基础,请一定要掌握。
原创粉丝点击