实现起来比较简单,主要是用户输入信息的检测和页面的跳转的实现。
首先要建立好数据库。
好了,先写好两个静态页面,分别负责登录和注册。
代码清单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>