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 (数据模型)
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author Barudisshu
- */
- public class DataProvider {
- //指定驱动名
- protected static String driver = "com.mysql.jdbc.Driver";
- //指定访问的URL
- protected static String url = "jdbc:mysql://localhost:3306/gossip";
- //MySQL用户名
- protected static String user = "root";
- //MySQL密码
- protected static String password = "***";
- //初始Connection
- protected static Connection connection = null;
- //建立连接
- public static Connection getConnection() {
- try {
- Class.forName(driver);
- connection = DriverManager.getConnection(url, user, password);
- return connection;
- } catch (ClassNotFoundException | SQLException e) {
- return null;
- }
- }
- //获取结果集
- public static ResultSet getResultSet(String sql) {
- Statement statement;
- ResultSet resultSet = null;
- Connection conn = getConnection();
- if (conn != null) {
- System.out.println("连接成功!");
- try {
- statement = conn.createStatement();
- resultSet = statement.executeQuery(sql);
- } catch (Exception e) {
- }
- return resultSet;
- } else {
- return null;
- }
- }
- //判断结果集是否为空
- public static boolean isResultSetNull(String sql) {
- int count = 0;
- ResultSet resultSet = getResultSet(sql);
- try {
- while (resultSet.next()) {
- count += 1;
- }
- } catch (SQLException ex) {
- Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE, null, ex);
- }
- if (count == 0) {
- return true;
- } else {
- return false;
- }
- }
- //是否执行
- public static boolean execute(String sql) {
- boolean success;
- Statement statement;
- Connection conn = getConnection();
- if (conn != null) {
- try {
- statement = conn.createStatement();
- success = statement.execute(sql);
- } catch (Exception e) {
- success = false;
- }
- } else {
- success = false;
- }
- return success;
- }
- //释放连接
- public static void releaseConnection() {
- try {
- if (connection != null) {
- connection.close();
- }
- } catch (Exception e) {
- }
- }
- }
创建注册验证Servlet,将取得请求参数、验证请求参数,业务跳转。逻辑业务部分。
代码清单4:Register.java (注册)
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.individuals.mysql.data.DataProvider;
- /**
- *
- * @author Barudisshu
- */
- public class RegisterServlet extends HttpServlet {
- private final String SUCCESS_VIEW = "success.view";
- private final String ERROR_VIEW = "error.view";
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- request.setCharacterEncoding("utf-8");
- //获取请求参数
- String email = request.getParameter("email");
- String user = request.getParameter("user");
- String password = request.getParameter("password");
- String confirmedPasswd = request.getParameter("resure");
- List<String> errors = new ArrayList<>();
- if (isInvalidEmail(email)) {
- errors.add("未填写邮件或邮件格式不正确");
- }
- if (isInvalidUsername(user)) {
- errors.add("用户名为空或已存在");
- }
- if (isInvalidPassword(password, confirmedPasswd)) {
- errors.add("请确认密码符合格式并再次确认密码");
- }
- String resultPage = ERROR_VIEW;
- if (!errors.isEmpty()) {
- request.setAttribute("errors", errors);
- } else {
- resultPage = SUCCESS_VIEW;
- createUserData(email, user, password);
- }
- request.getRequestDispatcher(resultPage).forward(request, response);
- }
- //判断邮箱输入格式是否正确
- private boolean isInvalidEmail(String email) {
- return email == null || !email.matches("^[_a-z0-9-]+([.]"
- + "[_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$");
- }
- //判断是否存在该用户
- private boolean isInvalidUsername(String username) {
- return !DataProvider.isResultSetNull("select * from gossip.userinfo where username = '" + username + "'");
- }
- //判断密码是否有效
- private boolean isInvalidPassword(String password, String confirmedPasswd) {
- return password == null
- || password.length() < 6
- || password.length() > 16
- || !password.equals(confirmedPasswd);
- }
- //创建用户资料并写入数据库
- private void createUserData(String email, String username, String password) {
- DataProvider.execute("insert into gossip.userinfo(email,username,password)"
- + " values ('" + email + "','" + username + "','" + password + "')");
- }
- @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);
- }
- @Override
- public String getServletInfo() {
- return "Short description";
- }// </editor-fold>
- }
下面分别建立注册成功与失败的视图。
代码清单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 (注册成功)
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- *
- * @author Barudisshu
- */
- public class Success extends HttpServlet {
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- try (PrintWriter out = response.getWriter()) {
- /* 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>会员" + request.getParameter("user") + "注册成功</h1>");
- out.println("<a href=\"login.jsp\">回首页登录");
- out.println("</body>");
- out.println("</html>");
- }
- }
- @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);
- }
- }
注册成功后就可以登录了,登录需要进行相关验证操作。
代码清单7:Login.java (验证用户登录)
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.individuals.mysql.data.DataProvider;
- /**
- *
- * @author Barudisshu
- */
- public class LoginServlet extends HttpServlet {
- private final String SUCCESS_VIEW = "member.view";
- private final String ERROR_VIEW = "login.jsp";
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- request.setCharacterEncoding("utf-8");
- String user = request.getParameter("user");
- String password = request.getParameter("password");
- if(checkLogin(user, password)){
- request.getRequestDispatcher(SUCCESS_VIEW).forward(request, response);
- }else{
- response.sendRedirect(ERROR_VIEW);
- }
- }
- //读取数据库,验证登录
- private boolean checkLogin(String username, String password) {
- if (username != null && password != null) {
- return !DataProvider.isResultSetNull("select * from gossip.userinfo "
- + "where username = '" + username + "' and password = '" + password + "'");
- }
- return false;
- }
- @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);
- }
- }
验证失败,则从新登录,通过sendRedirect()跳转到登录页面;验证成功,则进行下一步操作。
代码清单8:Member.java (登录成功)
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- *
- * @author Barudisshu
- */
- public class Member 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>会员 " + request.getParameter("user") + " 你好</h1>");
- 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);
- }
- }
代码清单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的表单的更多相关文章
- ASP.NET Aries 入门开发教程9:业务表单的开发
前言: 经过前面那么多篇的列表的介绍,终于到了大伙期待的表单开发了. 也是本系列的最后一篇文章了! 1:表单页面的权限设置与继承 对于表单页面,权限的设置有两种: 1:你可以选择添加菜单(设置为不显示 ...
- 探索ASP.NET MVC5系列之~~~3.视图篇(下)---包含常用表单和暴力解猜防御
其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...
- jQuery学习之路(8)- 表单验证插件-Validation
▓▓▓▓▓▓ 大致介绍 jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求.该插件捆绑了一套有用的验证方法,包括 ...
- jQuery学习之路(5)- 简单的表单应用
▓▓▓▓▓▓ 大致介绍 接下来的这几个博客是对前面所学知识的一个简单的应用,来加深理解 ▓▓▓▓▓▓ 单行文本框 只介绍一个简单的样式:获取和失去焦点改变样式 基本结构: <form actio ...
- 12、Struts2表单重复提交
什么是表单重复提交 表单的重复提交: 若刷新表单页面, 再提交表单不算重复提交. 在不刷新表单页面的前提下: 多次点击提交按钮 已经提交成功, 按 "回退" 之后, 再点击 &qu ...
- .net erp(办公oa)开发平台架构概要说明之表单设计器
背景:搭建一个适合公司erp业务的开发平台. 架构概要图: 表单设计开发部署示例图 表单设计开发部署示例说明1)每个开发人员可以自己部署表单设计至本地一份(当然也可以共用一套开发环境,但是如 ...
- javascript表单的Ajax 提交插件的使用
Ajax 提交插件 form.js 表单的下载地址:官方网站:http://malsup.com/jquery/form/ form.js 插件有两个核心方法:ajaxForm()和ajaxSubmi ...
- 玩转spring boot——AOP与表单验证
AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...
- from表单提交数据之后,后台对象接受不到值
如果SSH框架下,前段页面通过from表单提交数据之后,在后台对象显示空值,也就是接收不到值得情况下.首先保证前段输入框有值,这个可以在提交的时候用jQuery的id或者name选择器alert弹出测 ...
随机推荐
- __name__ __doc__ __package__
__name__只有主程序调用才可以 如果自己的唯一入口被调用 if __name__ == '__main__' : 才执行下面的代码 """ 这个是format的注释 ...
- git切换用户踩坑
1)配置用户信息 git config --global user.name "username" git config --global user.email "**@ ...
- HTML5-2
1 html5新增表单元素 <form> <!-- 数字 还有箭头,可以加减数字 并且可以设置最大最小值 --> <input type="number&quo ...
- 使用walle部署laravel的时候问题记录
1.使用walle部署laravel的时候检出后执行composer update提示 [RuntimeException]The HOME or COMPOSER_HOME environment ...
- phpstrom mac 快捷键
对应键 ⌘——Command ⌃ ——Control ⌥——Option/Alt ⇧——Shift ⇪——Caps Lock fn——功能键就是fn 编辑 Command+alt+T 用 (if..e ...
- ng-repeat 中的track by
<div style="font-size:15px"ng-repeat="item in groups.items track by $index"&g ...
- [SCOI2005]扫雷
我们可以发现...最开始的两个...只有两种情况...直接枚举一下...递推出结果好了... 呆码: #include<iostream> #include<cstring> ...
- 学习python及Pygame的安装及运行
Python: 注意勾上Add Python 2.7 to PATH,然后点“Install Now”即可完成安装. 或手动修改环境变量,win7:右击我的电脑->属性->高级->环 ...
- QT_REQUIER_CONFIG
在qglobal.h中,定义了很多宏.下面这个QT_REQUIER_CONFIG,展开成: #define QT_REQUIRE_CONFIG(feature) Q_STATIC_ASSERT_X(Q ...
- PHP协程入门详解
概念 咱们知道多进程和多线程是实现并发的有效方式.但多进程的上下文切换资源开销太大:多线程开销相比要小很多,也是现在主流的做法,但其的控制权在内核,从而使用户(程序员)失去了对代码的控制,而且线程的上 ...