SERvet的表单

Posted yangshuyuan1009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SERvet的表单相关的知识,希望对你有一定的参考价值。

首先要建立好数据库。

技术分享图片

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

代码清单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的表单的主要内容,如果未能解决你的问题,请参考以下文章

jBPM 的Servet 的WEB-INF\lib 中需要哪些Drools JARS?

ServletJava Servet Filter 过滤器

window servet 2012 r2 配置php服务器环境

SpringBoot中表单提交报错“Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported“(代码片段

Xamarin 表单 - 侧边菜单左侧栏、片段和列表视图

HTML代码片段