版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/kese7952/article/details/82944525
本案例的技術選型主要是jsp+servlet+JavaBean,采用三層架構的分層思想與MVC設計模式結合進行規範開發。
采用的資料庫是MySQL,并且搭配資料源連接配接池DBCP和apache官方提供的DBUtils進行資料庫連接配接開發。
目的是為了簡化SQL連接配接編碼,并且提高連接配接資料庫的性能。
本案例代碼不含有Css和Js效果,如需要完整代碼,通路:
https://download.csdn.net/download/kese7952/10702892 DBUtils的元件官方最新下載下傳位址: http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi以下是DBUtils1.7版本的分享連結:https://pan.baidu.com/s/1Ohg9v-vN2m3lwP_BSizrGA 提取碼:idca
DBCP的元件官方最新下載下傳位址:
http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi POOL的元件官方最新下載下傳位址: http://commons.apache.org/proper/commons-pool/download_pool.cgi以下是DBCP和POOL最新版本的分享連結:https://pan.baidu.com/s/1tR5LAT5v2B94_d0wACCvSA 提取碼:3e5o
項目的層級結構圖如下:
1. 先設計資料庫,有兩種方式:
a)編寫SQL代碼[推薦]:
1. 建立sql檔案:
2. 編寫SQL代碼:
-- 建立資料庫
create database login;
-- 選擇資料庫
use login;
-- 建立使用者表
create table user(
id int primary key auto_increment, -- 使用者編号 - 主鍵(自動遞增)
username varcahr(30), -- 使用者名
password varcahr(30), -- 使用者密碼
email varcahr(50), -- 使用者郵箱
sex varcahr(50) -- 使用者性别 [注:最後一個字段,不要再最後加入“,”]
);
3. 使用代碼進行執行建表!
b)使用可視化視窗進行建表
2. 開始寫實體類:User.java
package cn.javabs.login.entity;
/**
* Title: User.java
* @date 2018年10月5日 下午3:19:40
* @author Mr.yang
* 使用者的實體類設計
*/
public class User {
private Integer id;
private String username;
private String password;
private String sex;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
3.接下來寫的是DAO的接口
package cn.javabs.login.dao;
import java.sql.SQLException;
import cn.javabs.login.entity.User;
/**
* Title: UserDao.java
* @date 2018年10月5日 下午3:24:55
* @author Mr.yang
* 使用者的DAO接口設計
* |--- 接口是不可以被final修飾的哦!
* |--- 登入
* |--- 注冊
*/
public interface UserDao {
/**
* 使用者登入(需要傳入兩個參數)
* @param username 使用者名
* @param password 密碼
* @return 使用者對象
* @throws SQLException
*/
User login(String username,String password) throws SQLException;
/**
* 使用者注冊(傳入的是對象)
* @param user
* @return 整數
* @throws SQLException
*/
int regist(User user) throws SQLException;
}
4.接下來寫的是DAO的實作類
package cn.javabs.login.dao.impl;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.javabs.login.dao.UserDao;
import cn.javabs.login.entity.User;
import cn.javabs.login.util.DBCPUtils;
/**
* Title: UserDaoImpl.java
* 使用者的DAO實作類的設計
* @date 2018年10月5日 下午3:28:33
* @author Mr.yang 采用[資料源連接配接池 - DBCP] 使用Dbutils工具類中的QueryRunner進行
*/
public class UserDaoImpl implements UserDao {
QueryRunner queryRunner = new QueryRunner(DBCPUtils.getDataSource());
@Override
public User login(String username, String password) throws SQLException {
return queryRunner.query(
"select * from user where username = ? and password = ?", //
new BeanHandler<User>(User.class), username, password);
}
@Override
public int regist(User user) throws SQLException {
return queryRunner.update("insert into user(username,password,sex,email)values(?,?,?,?)",
user.getUsername(),
user.getPassword(),
user.getSex(),
user.getEmail()
);
}
}
4.接下來需要把DAO中的用到的資料源連接配接池的工具類補全
package cn.javabs.login.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
/**
* Title: DBCPUtils.java
*
* @date 2018年10月5日 下午4:04:48
* @author Mr.yang
*/
public class DBCPUtils {
public static DataSource dataSource;
static {
try {
String resource = "jdbc.properties";
InputStream is = DBCPUtils.class.getClassLoader()
.getResourceAsStream(resource);
Properties properties = new Properties();
properties.load(is);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 擷取資料源
* @return
*/
public static DataSource getDataSource() {
return dataSource;
}
/**
* 擷取連接配接
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
4.2 在config的中建立配置檔案:jdbc.properties
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql:///login
username = root
password = sorry
# 初始化連接配接
initialSize=10
# 最大連接配接數量
maxActive=50
# 最大空閑數量
maxIdle=20
# 最小空閑數量
minIdle=5
5.接下來把service層的接口設計出來
package cn.javabs.login.service;
import cn.javabs.login.entity.User;
/**
* Title: UserService.java
* @date 2018年10月5日 下午4:15:04
* @author Mr.yang
*/
public interface UserService {
/**
* 使用者登入(傳入兩個參數,使用者名和密碼)
* @param username
* @param password
* @return 使用者對象
*/
User userLogin(String username,String password);
/**
* 使用者注冊(傳入的是對象)
* @param user
* @return 影響的行數
*/
int userRegister(User user);
}
6.接下來把service層的實作類設計出來
package cn.javabs.login.service.impl;
import java.sql.SQLException;
import cn.javabs.login.dao.UserDao;
import cn.javabs.login.dao.impl.UserDaoImpl;
import cn.javabs.login.entity.User;
import cn.javabs.login.service.UserService;
/**
* Title: UserServiceImpl.java
* @date 2018年10月5日 下午4:17:34
* @author Mr.yang
*/
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
@Override
public User userLogin(String username, String password) {
try {
User user = userDao.login(username, password);
return user;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public int userRegister(User user) {
try {
return userDao.regist(user);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
7.接下來把controller層的控制器設計出來
package cn.javabs.login.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import cn.javabs.login.entity.User;
import cn.javabs.login.service.UserService;
import cn.javabs.login.service.impl.UserServiceImpl;
/**
*
* @author Mryang StringUtilsz中的isNotbBlock:判斷某字元串是否不為空且長度不為0且不由空白符構成
*
*/
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 引入UserService
UserService userService = new UserServiceImpl();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
// 如果傳入的參數是login
if ("login".equals(method)) {
login(request, response);
// 如果傳入的參數是regist
} else if ("regist".equals(method)) {
regist(request, response);
// 如果傳入的參數是logout
} else if ("logout".equals(method)) {
logout(request, response);
// 如果傳入的參數是tologin
} else if ("tologin".equals(method)) {
tologin(request, response);
// 如果傳入的參數是toregist
} else if ("toregist".equals(method)) {
toregist(request, response);
// 如果傳入的參數是對應不上
} else {
request.setAttribute("msg", "該功能正在開發...");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
/**
* 使用者登入
*
* @param request
* @param response
*/
private void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1. 擷取前台jsp表單傳遞的參數
*/
String username = request.getParameter("username");
String password = request.getParameter("password");
// 如果測試傳入的參數。可以打開72行的注釋
// System.out.println("使用者名:" + username + "<br/>" + "密碼" + password);
/*
* 2.根據參數進行判斷
*/
// 2.1 如果使用者名和密碼都不為空
if (StringUtils.isNotBlank(username)
&& StringUtils.isNotBlank(password)) {
// 2.1.1 傳遞到service層登入方法
User user = userService.userLogin(username, password);
// 2.1.2 判斷使用者資訊是否查詢到
if (user != null) {
// 查詢到,存入session
request.getSession().setAttribute("USER_SESSION", user);
// 登入成功,轉向首頁
request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(
request, response);
} else {
// 未查詢到或者使用者名和密碼不比對,将失敗的資訊存儲到msg中
request.setAttribute("msg", "使用者名或者密碼不對!");
// 登入失敗,轉向錯誤資訊提示頁面,根據存入的msg取出相對應的内容
request.getRequestDispatcher("/message.jsp").forward(request,
response);//
}
// 2.2 如果使用者名或者密碼為空
} else {
request.setAttribute("msg", "使用者名或者密碼不許為空!");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(
request, response);//
}
}
/**
* 使用者注冊
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void regist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user = new User();
// 1. 擷取前台jsp頁面的參數
String username = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
// 2. 将擷取到的參數封裝到user對象中去
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setSex(sex);
if (StringUtils.isNotBlank(user.getUsername())
&& StringUtils.isNotBlank(user.getPassword())) {
int rows = userService.userRegister(user);
if (rows > 0) {
response.setHeader("refresh",
"1;url=UserServlet?method=tologin");
} else {
request.setAttribute("msg", "注冊失敗!");
request.getRequestDispatcher("/message").forward(request,
response);
}
}else{
request.setAttribute("msg", "使用者名或者密碼不許為空");
request.getRequestDispatcher("/message").forward(request,
response);
}
}
/**
* 轉向到登入頁面
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void tologin(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,
response);//
}
/**
* 轉向到注冊頁面
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void toregist(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/regist.jsp").forward(
request, response);//
}
/**
* 使用者登出
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void logout(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(
request, response);//
}
}
8.首頁
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="WEB-INF/jsp/regist.jsp"></jsp:forward>
</body>
</html>
登入頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/login.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<style type="text/css">
#err{
color: red;
margin-left: 115px;
margin-top: 25px;
padding-top: 22px;
}
#toregist{
margin-left: 280px;
font-size: 14px;
text-decoration: none;
color:deepskyblue;
}
a:HOVER {
color:red;
font-size: 15px;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="page">
<div class="loginwarrp">
<div class="logo">管理者登陸</div>
<br />
<span id="err">${msg }</span><!-- 錯誤資訊提示 -->
<a id="toregist" href="${pageContext.request.contextPath}/UserServlet?method=toregist">沒有賬号,去注冊</a>
<div class="login_form">
<form id="Login" name="Login" method="post" action="${pageContext.request.contextPath}/UserServlet?method=login">
<li class="login-item">
<span>使用者名:</span>
<input type="text" id="username" name="username" class="login_input" >
<span id="count-msg" class="error"></span>
</li>
<li class="login-item">
<span>密 碼:</span>
<input type="password" id="password" name="password" class="login_input" >
<span id="password-msg" class="error"></span>
</li>
<!--
<li class="login-item verify">
<span>驗證碼:</span>
<input type="text" name="CheckCode" class="login_input verify_input">
</li>
<img src="images/verify.png" border="0" class="verifyimg" />
-->
<div class="clearfix"></div>
<li class="login-sub">
<input type="submit" name="Submit" value="登入" />
<input type="reset" name="Reset" value="重置" />
</li>
</form>
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function() {
var config = {
vx : 4,
vy : 4,
height : 2,
width : 2,
count : 100,
color : "121, 162, 185",
stroke : "100, 200, 180",
dist : 6000,
e_dist : 20000,
max_conn : 10
}
CanvasParticle(config);
}
</script>
<script type="text/javascript" src="js/canvas-particle.js"></script>
</body>
</html>
9.注冊頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>${initParam.MyTitle}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="css/demo.css">
<link rel="stylesheet" href="css/sky-forms.css">
<link rel="stylesheet" href="css/sky-forms-ie8.css">
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.placeholder.min.js"></script>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<script src="js/sky-forms-ie8.js"></script>
<style type="text/css">
#tologin{
margin-left: 220px;
font-size: 14px;
text-decoration: none;
}
a:HOVER {
color:red;
font-size: 15px;
text-decoration: underline;
}
</style>
</head>
<body class="bg-cyan">
<div class="body body-s">
<form action="${pageContext.request.contextPath}/UserServlet?method=regist" method="post" id="sky-form" class="sky-form">
<header>請填寫表單</header>
<fieldset> <!-- -->
<a id="tologin" href="${pageContext.request.contextPath}/UserServlet?method=tologin">已有賬号,去登入</a>
<br />
<br />
<section>
<label class="input">
<i class="icon-append icon-user"></i>
<input type="text" name="username" placeholder="使用者名">
<b class="tooltip tooltip-bottom-right">請輸入使用者名</b>
</label>
</section>
<section>
<label class="input">
<i class="icon-append icon-envelope-alt"></i>
<input type="email" name="email" placeholder="Email">
<b class="tooltip tooltip-bottom-right">請輸入您的Email位址</b>
</label>
</section>
<section>
<label class="input">
<i class="icon-append icon-lock"></i>
<input type="password" name="password" placeholder="密碼" id="password">
<b class="tooltip tooltip-bottom-right">請輸入您的密碼</b>
</label>
</section>
<section>
<label class="input">
<i class="icon-append icon-lock"></i>
<input type="password" name="passwordConfirm" placeholder="請再次輸入您的密碼">
<b class="tooltip tooltip-bottom-right">請再次輸入您的密碼</b>
</label>
</section>
<section>
<label class="select">
<select name="sex">
<option value="0" selected disabled>請選擇性别</option>
<option value="1">男性</option>
<option value="2">女性</option>
</select>
<i></i>
</label>
</section>
</fieldset>
<fieldset>
<section>
<label class="checkbox"><input type="checkbox" name="subscription" id="subscription"><i></i>I
我願意接受網際網路研習社最新動态</label>
<label class="checkbox"><input type="checkbox" name="terms" id="terms"><i></i>I
我同意注冊許可</label>
</section>
</fieldset>
<footer>
<button type="submit" class="button">送出注冊</button>
</footer>
</form>
</div>
<script type="text/javascript">
$(function()
{
// Validation
$("#sky-form").validate(
{
// Rules for form validation
rules:
{
username:
{
required: true
},
email:
{
required: true,
email: true
},
password:
{
required: true,
minlength: 3,
maxlength: 20
},
passwordConfirm:
{
required: true,
minlength: 3,
maxlength: 20,
equalTo: '#password'
},
firstname:
{
required: true
},
lastname:
{
required: true
},
gender:
{
required: true
},
terms:
{
required: true
}
},
// Messages for form validation
messages:
{
login:
{
required: 'Please enter your login'
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
password:
{
required: 'Please enter your password'
},
passwordConfirm:
{
required: 'Please enter your password one more time',
equalTo: 'Please enter the same password as above'
},
firstname:
{
required: 'Please select your first name'
},
lastname:
{
required: 'Please select your last name'
},
gender:
{
required: 'Please select your gender'
},
terms:
{
required: 'You must agree with Terms and Conditions'
}
},
// Do not change code below
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
</script>
<div style="width:960px;margin:10px auto; clear:both; text-align:center; ">
<script src="/statics/js/ad/96090.js" type="text/javascript"></script>
</div>
<div style="width:960px;margin:20px auto; clear:both; text-align:center; font-size:12px; line-height:25px; ">
<a href="https://blog.csdn.net/kese7952" style="color:#333"><strong>Mryang個人整理</strong></a> </strong>
轉載請自覺注明出處!注:此代碼僅供學習交流,請勿用于商業用途。
<br>
關注更多學習内容更新 請加入Java學習交流群 : <strong>827829292</strong> <a target="_blank" href="https://jq.qq.com/?_wv=1027&k=5gfNSI6"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png"
alt="程式設計研習社QQ群①" title="程式設計研習社QQ群①"></a>
<script src="/statics/js/inc_share.js" type="text/javascript"></script>
<script src="/statics/js/inc_statistics.js" type="text/javascript"></script>
<script src="/statics/js/inc_monitor.js" type="text/javascript"></script>
</div>
</body>
</html>
10.登入成功頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h3>
${sessionScope.USER_SESSION.username},遇到您真好!
</h3>
<hr/>
<h4>
<a href="${pageContext.request.contextPath}/UserServlet?method=logout">如果您呆的厭倦了,可以點我離開</a>
</h4>
</center>
</body>
</html>
錯誤提示頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${msg}
</body>
</html>
web.xml的配置檔案内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<context-param>
<param-name>MyTitle</param-name>
<param-value>javaWeb案例之使用者的注冊</param-value>
</context-param>
<display-name>Login</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UserServlet</display-name>
<servlet-name>UserServlet</servlet-name>
<servlet-class>cn.javabs.login.controller.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
</web-app>
最終的頁面效果如下所示: