首先要建立好数据库。

好了,先写好两个静态页面,分别负责登录和注册。

代码清单1:login.jsp(登录页面)

<%--
Document : login
Created on : 2013-8-29, 17:14:30
Author : Barudisshu
--%> <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<form action="login.do" method="post">
<table>
<tr>
<td><label for="user">用户名:</label></td>
<td><input type="text" id="user" name="user" value=""></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input type="password" id="password" name="password" value=""></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="登录"></td>
</tr>
</table>
</form>
</div>
</body>
</html>

代码清单2:register.jsp (注册页面)

<%--
Document : register
Created on : 2013-8-29, 17:14:50
Author : Barudisshu
--%> <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
</head>
<body>
<div>
<form action="register.do" method="post">
<table>
<tr>
<td><label for="user">用户名:</label></td>
<td><input type="text" id="user" name="user" value=""></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input type="password" id="password" name="password" value=""></td>
</tr>
<tr>
<td><label for="resure">确认密码:</label></td>
<td><input type="password" id="resure" name="resure" value=""></td>
</tr>
<tr>
<td><label for="email">邮箱地址:</label></td>
<td><input type="email" id="password" name="email" value=""></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>

建立数据库模型,主要实现数据库连接建立、执行查询、释放连接、判断等操作。

代码清单3:DataProvider.java (数据模型)

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9. /**
  10. *
  11. * @author Barudisshu
  12. */
  13. public class DataProvider {
  14.  
  15. //指定驱动名
  16. protected static String driver = "com.mysql.jdbc.Driver";
  17. //指定访问的URL
  18. protected static String url = "jdbc:mysql://localhost:3306/gossip";
  19. //MySQL用户名
  20. protected static String user = "root";
  21. //MySQL密码
  22. protected static String password = "***";
  23. //初始Connection
  24. protected static Connection connection = null;
  25.  
  26. //建立连接
  27. public static Connection getConnection() {
  28. try {
  29. Class.forName(driver);
  30. connection = DriverManager.getConnection(url, user, password);
  31. return connection;
  32. } catch (ClassNotFoundException | SQLException e) {
  33. return null;
  34. }
  35. }
  36.  
  37. //获取结果集
  38. public static ResultSet getResultSet(String sql) {
  39. Statement statement;
  40. ResultSet resultSet = null;
  41. Connection conn = getConnection();
  42. if (conn != null) {
  43. System.out.println("连接成功!");
  44. try {
  45. statement = conn.createStatement();
  46. resultSet = statement.executeQuery(sql);
  47. } catch (Exception e) {
  48. }
  49. return resultSet;
  50. } else {
  51. return null;
  52. }
  53. }
  54.  
  55. //判断结果集是否为空
  56. public static boolean isResultSetNull(String sql) {
  57. int count = 0;
  58. ResultSet resultSet = getResultSet(sql);
  59. try {
  60. while (resultSet.next()) {
  61. count += 1;
  62. }
  63. } catch (SQLException ex) {
  64. Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
  65. }
  66. if (count == 0) {
  67. return true;
  68. } else {
  69. return false;
  70. }
  71. }
  72.  
  73. //是否执行
  74. public static boolean execute(String sql) {
  75. boolean success;
  76. Statement statement;
  77. Connection conn = getConnection();
  78. if (conn != null) {
  79. try {
  80. statement = conn.createStatement();
  81. success = statement.execute(sql);
  82. } catch (Exception e) {
  83. success = false;
  84. }
  85. } else {
  86. success = false;
  87. }
  88. return success;
  89. }
  90.  
  91. //释放连接
  92. public static void releaseConnection() {
  93. try {
  94. if (connection != null) {
  95. connection.close();
  96. }
  97. } catch (Exception e) {
  98. }
  99. }
  100. }

创建注册验证Servlet,将取得请求参数、验证请求参数,业务跳转。逻辑业务部分。

代码清单4:Register.java (注册)

  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import net.individuals.mysql.data.DataProvider;
  9.  
  10. /**
  11. *
  12. * @author Barudisshu
  13. */
  14. public class RegisterServlet extends HttpServlet {
  15.  
  16. private final String SUCCESS_VIEW = "success.view";
  17. private final String ERROR_VIEW = "error.view";
  18.  
  19. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  20. throws ServletException, IOException {
  21. response.setContentType("text/html;charset=UTF-8");
  22. request.setCharacterEncoding("utf-8");
  23. //获取请求参数
  24. String email = request.getParameter("email");
  25. String user = request.getParameter("user");
  26. String password = request.getParameter("password");
  27. String confirmedPasswd = request.getParameter("resure");
  28. List<String> errors = new ArrayList<>();
  29. if (isInvalidEmail(email)) {
  30. errors.add("未填写邮件或邮件格式不正确");
  31. }
  32. if (isInvalidUsername(user)) {
  33. errors.add("用户名为空或已存在");
  34. }
  35. if (isInvalidPassword(password, confirmedPasswd)) {
  36. errors.add("请确认密码符合格式并再次确认密码");
  37. }
  38. String resultPage = ERROR_VIEW;
  39. if (!errors.isEmpty()) {
  40. request.setAttribute("errors", errors);
  41. } else {
  42. resultPage = SUCCESS_VIEW;
  43. createUserData(email, user, password);
  44. }
  45.  
  46. request.getRequestDispatcher(resultPage).forward(request, response);
  47. }
  48.  
  49. //判断邮箱输入格式是否正确
  50. private boolean isInvalidEmail(String email) {
  51. return email == null || !email.matches("^[_a-z0-9-]+([.]"
  52. + "[_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$");
  53. }
  54.  
  55. //判断是否存在该用户
  56. private boolean isInvalidUsername(String username) {
  57. return !DataProvider.isResultSetNull("select * from gossip.userinfo where username = '" + username + "'");
  58. }
  59.  
  60. //判断密码是否有效
  61. private boolean isInvalidPassword(String password, String confirmedPasswd) {
  62. return password == null
  63. || password.length() < 6
  64. || password.length() > 16
  65. || !password.equals(confirmedPasswd);
  66. }
  67.  
  68. //创建用户资料并写入数据库
  69. private void createUserData(String email, String username, String password) {
  70. DataProvider.execute("insert into gossip.userinfo(email,username,password)"
  71. + " values ('" + email + "','" + username + "','" + password + "')");
  72. }
  73.  
  74. @Override
  75. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  76. throws ServletException, IOException {
  77. processRequest(request, response);
  78. }
  79.  
  80. @Override
  81. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  82. throws ServletException, IOException {
  83. processRequest(request, response);
  84. }
  85.  
  86. @Override
  87. public String getServletInfo() {
  88. return "Short description";
  89. }// </editor-fold>
  90. }

下面分别建立注册成功与失败的视图。

代码清单5:Error.java (注册失败)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
*
* @author Barudisshu
*/
public class Error extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"utf-8\">");
out.println("<title>新增会员失败</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>新增会员失败</h1>");
out.println("<ul style='color:red;'>");
List<String> errors = (List<String>) request.getAttribute("errors");
for (String error : errors) {
out.println("<li>" + error + "</li>");
}
out.println("</ul>");
out.println("<a href='register.html'>返回注册页面</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

代码清单6:Success.java (注册成功)

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7.  
  8. /**
  9. *
  10. * @author Barudisshu
  11. */
  12. public class Success extends HttpServlet {
  13.  
  14. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. response.setContentType("text/html;charset=UTF-8");
  17. try (PrintWriter out = response.getWriter()) {
  18. /* TODO output your page here. You may use following sample code. */
  19. out.println("<!DOCTYPE html>");
  20. out.println("<html>");
  21. out.println("<head>");
  22. out.println("<meta charset=\"utf-8\">");
  23. out.println("<title>新增会员成功</title>");
  24. out.println("</head>");
  25. out.println("<body>");
  26. out.println("<h1>会员" + request.getParameter("user") + "注册成功</h1>");
  27. out.println("<a href=\"login.jsp\">回首页登录");
  28. out.println("</body>");
  29. out.println("</html>");
  30. }
  31. }
  32.  
  33. @Override
  34. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  35. throws ServletException, IOException {
  36. processRequest(request, response);
  37. }
  38.  
  39. @Override
  40. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  41. throws ServletException, IOException {
  42. processRequest(request, response);
  43. }
  44. }

注册成功后就可以登录了,登录需要进行相关验证操作。

代码清单7:Login.java (验证用户登录)

  1. import java.io.IOException;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import net.individuals.mysql.data.DataProvider;
  7.  
  8. /**
  9. *
  10. * @author Barudisshu
  11. */
  12. public class LoginServlet extends HttpServlet {
  13.  
  14. private final String SUCCESS_VIEW = "member.view";
  15. private final String ERROR_VIEW = "login.jsp";
  16.  
  17. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  18. throws ServletException, IOException {
  19. response.setContentType("text/html;charset=UTF-8");
  20. request.setCharacterEncoding("utf-8");
  21. String user = request.getParameter("user");
  22. String password = request.getParameter("password");
  23. if(checkLogin(user, password)){
  24. request.getRequestDispatcher(SUCCESS_VIEW).forward(request, response);
  25. }else{
  26. response.sendRedirect(ERROR_VIEW);
  27. }
  28.  
  29. }
  30.  
  31. //读取数据库,验证登录
  32. private boolean checkLogin(String username, String password) {
  33. if (username != null && password != null) {
  34. return !DataProvider.isResultSetNull("select * from gossip.userinfo "
  35. + "where username = '" + username + "' and password = '" + password + "'");
  36. }
  37. return false;
  38. }
  39.  
  40. @Override
  41. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  42. throws ServletException, IOException {
  43. processRequest(request, response);
  44. }
  45.  
  46. @Override
  47. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  48. throws ServletException, IOException {
  49. processRequest(request, response);
  50. }
  51. }

验证失败,则从新登录,通过sendRedirect()跳转到登录页面;验证成功,则进行下一步操作。

代码清单8:Member.java (登录成功)

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7.  
  8. /**
  9. *
  10. * @author Barudisshu
  11. */
  12. public class Member extends HttpServlet {
  13.  
  14. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. response.setContentType("text/html;charset=UTF-8");
  17. PrintWriter out = response.getWriter();
  18. try {
  19. /* TODO output your page here. You may use following sample code. */
  20. out.println("<!DOCTYPE html>");
  21. out.println("<html>");
  22. out.println("<head>");
  23. out.println("<meta charset=\"utf-8\">");
  24. out.println("<title>会员登录成功页面</title>");
  25. out.println("</head>");
  26. out.println("<body>");
  27. out.println("<h1>会员 " + request.getParameter("user") + " 你好</h1>");
  28. out.println("</body>");
  29. out.println("</html>");
  30. } finally {
  31. out.close();
  32. }
  33. }
  34.  
  35. @Override
  36. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  37. throws ServletException, IOException {
  38. processRequest(request, response);
  39. }
  40.  
  41. @Override
  42. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  43. throws ServletException, IOException {
  44. processRequest(request, response);
  45. }
  46. }

代码清单9:web.xml (标准依赖部署文件)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>net.individuals.web.servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>net.individuals.web.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Error</servlet-name>
<servlet-class>net.individuals.web.servlet.Error</servlet-class>
</servlet>
<servlet>
<servlet-name>Success</servlet-name>
<servlet-class>net.individuals.web.servlet.Success</servlet-class>
</servlet>
<servlet>
<servlet-name>Member</servlet-name>
<servlet-class>net.individuals.web.servlet.Member</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Error</servlet-name>
<url-pattern>/error.view</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Success</servlet-name>
<url-pattern>/success.view</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Member</servlet-name>
<url-pattern>/member.view</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

SERvet的表单的更多相关文章

  1. ASP.NET Aries 入门开发教程9:业务表单的开发

    前言: 经过前面那么多篇的列表的介绍,终于到了大伙期待的表单开发了. 也是本系列的最后一篇文章了! 1:表单页面的权限设置与继承 对于表单页面,权限的设置有两种: 1:你可以选择添加菜单(设置为不显示 ...

  2. 探索ASP.NET MVC5系列之~~~3.视图篇(下)---包含常用表单和暴力解猜防御

    其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...

  3. jQuery学习之路(8)- 表单验证插件-Validation

    ▓▓▓▓▓▓ 大致介绍 jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求.该插件捆绑了一套有用的验证方法,包括 ...

  4. jQuery学习之路(5)- 简单的表单应用

    ▓▓▓▓▓▓ 大致介绍 接下来的这几个博客是对前面所学知识的一个简单的应用,来加深理解 ▓▓▓▓▓▓ 单行文本框 只介绍一个简单的样式:获取和失去焦点改变样式 基本结构: <form actio ...

  5. 12、Struts2表单重复提交

    什么是表单重复提交 表单的重复提交: 若刷新表单页面, 再提交表单不算重复提交. 在不刷新表单页面的前提下: 多次点击提交按钮 已经提交成功, 按 "回退" 之后, 再点击 &qu ...

  6. .net erp(办公oa)开发平台架构概要说明之表单设计器

    背景:搭建一个适合公司erp业务的开发平台.   架构概要图: 表单设计开发部署示例图    表单设计开发部署示例说明1)每个开发人员可以自己部署表单设计至本地一份(当然也可以共用一套开发环境,但是如 ...

  7. javascript表单的Ajax 提交插件的使用

    Ajax 提交插件 form.js 表单的下载地址:官方网站:http://malsup.com/jquery/form/ form.js 插件有两个核心方法:ajaxForm()和ajaxSubmi ...

  8. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  9. from表单提交数据之后,后台对象接受不到值

    如果SSH框架下,前段页面通过from表单提交数据之后,在后台对象显示空值,也就是接收不到值得情况下.首先保证前段输入框有值,这个可以在提交的时候用jQuery的id或者name选择器alert弹出测 ...

随机推荐

  1. __name__ __doc__ __package__

    __name__只有主程序调用才可以 如果自己的唯一入口被调用 if __name__ == '__main__' : 才执行下面的代码 """ 这个是format的注释 ...

  2. git切换用户踩坑

    1)配置用户信息 git config --global user.name "username" git config --global user.email "**@ ...

  3. HTML5-2

    1 html5新增表单元素 <form> <!-- 数字 还有箭头,可以加减数字 并且可以设置最大最小值 --> <input type="number&quo ...

  4. 使用walle部署laravel的时候问题记录

    1.使用walle部署laravel的时候检出后执行composer update提示 [RuntimeException]The HOME or COMPOSER_HOME environment ...

  5. phpstrom mac 快捷键

    对应键 ⌘——Command ⌃ ——Control ⌥——Option/Alt ⇧——Shift ⇪——Caps Lock fn——功能键就是fn 编辑 Command+alt+T 用 (if..e ...

  6. ng-repeat 中的track by

    <div style="font-size:15px"ng-repeat="item in groups.items track by $index"&g ...

  7. [SCOI2005]扫雷

    我们可以发现...最开始的两个...只有两种情况...直接枚举一下...递推出结果好了... 呆码: #include<iostream> #include<cstring> ...

  8. 学习python及Pygame的安装及运行

    Python: 注意勾上Add Python 2.7 to PATH,然后点“Install Now”即可完成安装. 或手动修改环境变量,win7:右击我的电脑->属性->高级->环 ...

  9. QT_REQUIER_CONFIG

    在qglobal.h中,定义了很多宏.下面这个QT_REQUIER_CONFIG,展开成: #define QT_REQUIRE_CONFIG(feature) Q_STATIC_ASSERT_X(Q ...

  10. PHP协程入门详解

    概念 咱们知道多进程和多线程是实现并发的有效方式.但多进程的上下文切换资源开销太大:多线程开销相比要小很多,也是现在主流的做法,但其的控制权在内核,从而使用户(程序员)失去了对代码的控制,而且线程的上 ...