サーブレットが簡単に実現する登録ログイン機能
実現は比較的簡単で,主にユーザ入力情報の検出とページのジャンプの実現である.
まずデータベースを構築します.
はい、まず2つの静的ページを書いて、それぞれログインと登録を担当します.
コードリスト1:login.jsp(ログインページ)
コードリスト2:register.jsp(登録ページ)
データベースモデルを構築し、主にデータベース接続の確立、クエリーの実行、接続の解放、判断などの操作を実現する.
コードリスト3:DataProvider.JAva(データモデル)
登録検証サーブレットを作成すると、要求パラメータ、検証要求パラメータ、ビジネスジャンプが取得されます.論理ビジネス・セクション.
コードリスト4:Register.JAva(登録)
次に、登録に成功したビューと失敗したビューをそれぞれ作成します.
コードリスト5:Error.JAva(登録失敗)
コードリスト6:Success.JAva(登録成功)
登録に成功するとログインできます.ログインには検証操作が必要です.
コードリスト7:Login.JAva(ユーザーログインの検証)
検証に失敗すると、新しいログインからsendRedirect()を介してログインページにジャンプします.検証に成功したら、次の操作を行います.
コードリスト8:Member.JAva(ログイン成功)
コードリスト9:web.xml(標準依存配置ファイル)
まずデータベースを構築します.
はい、まず2つの静的ページを書いて、それぞれログインと登録を担当します.
コードリスト1:login.jsp(ログインページ)
<%--
Document : login
Created on : 2013-8-29, 17:14:30
Author : Barudisshu
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<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"%>
<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) {
}
}
}
登録検証サーブレットを作成すると、要求パラメータ、検証要求パラメータ、ビジネスジャンプが取得されます.論理ビジネス・セクション.
コードリスト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 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";
}//
}
次に、登録に成功したビューと失敗したビューをそれぞれ作成します.
コードリスト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("");
out.println("");
out.println("");
out.println("");
out.println(" ");
out.println("");
out.println("");
out.println(" "
);
out.println(""
);
List errors = (List) request.getAttribute("errors");
for (String error : errors) {
out.println("" + error + "");
}
out.println("");
out.println(" ページに る");
out.println("");
out.println("");
} 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("");
out.println("");
out.println("");
out.println("");
out.println(" ");
out.println("");
out.println("");
out.println(" "
+ request.getParameter("user") + " ");
out.println(" トップページにログイン);
out.println("");
out.println("");
}
}
@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("");
out.println("");
out.println("");
out.println("");
out.println(" ");
out.println("");
out.println("");
out.println(" "
+ request.getParameter("user") + " ");
out.println("");
out.println("");
} 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(標準依存配置ファイル)
<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>LoginServletservlet-name>
<servlet-class>net.individuals.web.servlet.LoginServletservlet-class>
servlet>
<servlet>
<servlet-name>RegisterServletservlet-name>
<servlet-class>net.individuals.web.servlet.RegisterServletservlet-class>
servlet>
<servlet>
<servlet-name>Errorservlet-name>
<servlet-class>net.individuals.web.servlet.Errorservlet-class>
servlet>
<servlet>
<servlet-name>Successservlet-name>
<servlet-class>net.individuals.web.servlet.Successservlet-class>
servlet>
<servlet>
<servlet-name>Memberservlet-name>
<servlet-class>net.individuals.web.servlet.Memberservlet-class>
servlet>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/login.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServletservlet-name>
<url-pattern>/register.dourl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>Errorservlet-name>
<url-pattern>/error.viewurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>Successservlet-name>
<url-pattern>/success.viewurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>Memberservlet-name>
<url-pattern>/member.viewurl-pattern>
servlet-mapping>
<session-config>
<session-timeout>
30
session-timeout>
session-config>
web-app>