回到学校已经有三个星期了,那也有三个星期没有去写博客了,今天就对之前学习的内容进行一个小的项目回顾一下吧。
今天要实现的项目是某网站里面的注册登录注销三个功能。
开发环境:Eclipse ,tomcat8.0,jdk1.8,mysql5.5。
导入的jar包:commons-beanutils-1.8.3.jar,commons-logging-1.1.1.jar,jstl.jar,mysql-connector-java-5.1.26-bin.jar,standard.jar。
做什么之前都需要去了解清楚需求。
1注册:用户输入用户名(3~8位字母组成),密码:(必须输入,3~8位数字组成),重复密码:(必须和密码一致),邮箱:(必须输入,且要符合邮箱的格式),出生日期:(必须输入,格式2001-03-18)。
2登录:输入用户名和密码,正确后会跳转会主页,并显示用户名在主页上。
3注销:点击注销后主页上不在显示用户名,并出现登录注册按钮。
那我们现在去编程吧。首先是写前端的代码:
index.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>XXXtitle>
<style type="text/css">
//编写样式后面的工作
*{margin:0;
padding:0;
}
body{
font-size:12px;
font-family:"微软雅黑";
}
a{color:blue;
text-decoration: none;
}
a:HOVER {
color:red;
}
style>
head>
<body>
XX网站<br/>
<c:if test="${sessionScope.user ==null }">
<a href="<%=path %>/login.jsp">登录a>
<a href="<%=path %>/regist.jsp">注册a>
c:if>
<c:if test="${sessionScope.user !=null }">
欢迎<a href="">${sessionScope.user.username}a>
<a href="${pageContext.request.contextPath }/servlet/LogoutServlet">注销a>
c:if>
body>
html>
regist.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>XXXtitle>
head>
<body>
<form action="${pageContext.request.contextPath}/servlet/RegistServlet" method="post">
<table border="1">
<tr>
<th>用户名:(必须输入,3~8位字母组成)th>
<td>
<input type="text" id="username" name="username" value="${formbean.username }"/>${formbean.errors.username}
td>
tr>
<tr>
<th>密码:(必须输入,3~8位数字组成)th>
<td>
<input type="password" name="password" value="${formbean.password}"/>${formbean.errors.password}
td>
tr>
<tr>
<th>重复密码:(必须和密码一致)th>
<td>
<input type="password" name="repassword" value="${formbean.repassword}"/>${formbean.errors.repassword}
td>
tr>
<tr>
<th>邮箱:(必须输入,且要符合邮箱的格式)th>
<td>
<input type="text" name="email" value="${formbean.email}"/>${formbean.errors.email}
td>
tr>
<tr>
<th>出生日期:(必须输入,格式2001-03-18)th>
<td>
<input type="text" name="birthday" value="${formbean.birthday}" />${formbean.errors.birthday}
td>
tr>
table>
<input type="submit" value="注册" />
form>
body>
html>
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录页面title>
head>
<body>
<form action="${pageContext.request.contextPath}/servlet/LoginServlet" method="post">
<table >
<tr>
<th>账号:th>
<td>
<input type="text" name="username">
td>
tr>
<tr>
<th>密码:th>
<td>
<input type="text" name="password">
td>
tr>
table>
<input type="submit" value="登录"/>
form>
body>
html>
下面展示一下包结构:
下面是后端代码:
top.wyxbs.domain包下的User.java
/**
* 用户类
* @author chenjingbin
*
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 邮箱
*/
private String email;
/**
* 出生日期
*/
private Date birthday;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", email=" + email + ", birthday=" + birthday
+ "]";
}
}
top.wyxbs.util包下的类
/**
*
* 数据库帮助类
* @author chenjingbin
* @since 2017/3/16
*/
public class DBHelper {
private final static String URL = "jdbc:mysql://localhost:3306/wyxbs";
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String USER = "wyxbsadmin";
private final static String PASSWORD = "111111";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* 获取Connection对象
* @return Connection
*/
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
/**
* 关闭流
* @param connection
* @param statement
* @param resultSet
* @throws SQLException
*/
public static void streamClose(Connection connection, Statement statement,
ResultSet resultSet) throws SQLException {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
//--------------------------------------------------
public class WebUtil {
/**
* 使用BeanUtils完成Javabean对象
* @param request
* @param class1 类的对象
* @return
*/
public static T fillBean(HttpServletRequest request,Class class1){
T t = null ;
try {
t = class1.newInstance();
BeanUtils.populate(t, request.getParameterMap());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}
top.wyxbs.dao包下的类:
import top.wyxbs.domain.User;
public interface UserDao {
/**
* 保存用户
* @param user 用户对象
*/
void save(User user);
/**
* 查找用户根据用户名去找
* @param name 用户名
* @return 返回用户对象
*/
User findUserByName(String name);
/**
* 根据账号密码去查找用户
* @param name 用户名
* @param password 密码
* @return 返回符合的用户对象
*/
User findUser(String name ,String password);
}
//-------------------------------------------------
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import top.wyxbs.domain.User;
import top.wyxbs.util.DBHelper;
public class UserDaoImpl implements UserDao {
@Override
public void save(User user) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement prepareStatement = null ;
String sql = "insert into t_user (username ,password,email,birthday) values(?,?,?,? );";
try {
connection = DBHelper.getConnection();
//需要去转换java.util.date 转换为java.sql.date
// Date date =new Date(user.getBirthday().getTime());
//System.out.println(date);
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, user.getUsername());
prepareStatement.setString(2, user.getPassword());
prepareStatement.setString(3, user.getEmail());
prepareStatement.setDate(4, new Date(user.getBirthday().getTime()));
prepareStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
DBHelper.streamClose(connection, prepareStatement, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭流出现问题");
}
}
}
@Override
public User findUserByName(String name) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
String sql="select username,password,email,birthday from t_user where username=?";
try {
connection = DBHelper.getConnection();
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, name);
resultSet = prepareStatement.executeQuery();
User user = new User();
while(resultSet.next()){
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(new java.util.Date(resultSet.getDate("birthday").getTime()));
return user;
}
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
DBHelper.streamClose(connection, prepareStatement, resultSet);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭流出错了");
}
}
return null;
}
@Override
public User findUser(String name, String password) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
String sql="select username,password,email,birthday from t_user where username=? and password=?";
try {
connection = DBHelper.getConnection();
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, name);
prepareStatement.setString(2, password);
resultSet = prepareStatement.executeQuery();
User user = new User();
while(resultSet.next()){
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(new java.util.Date(resultSet.getDate("birthday").getTime()));
return user;
}
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
DBHelper.streamClose(connection, prepareStatement, resultSet);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭流出错了");
}
}
return null;
}
}
top.wyxbs.exception包下的类:
/**
* 用户已经存在异常类
* @author chenjingbin
*
*/
public class UserExistException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public UserExistException() {
}
public UserExistException(String message) {
super(message);
}
public UserExistException(Throwable cause) {
super(cause);
}
public UserExistException(String message, Throwable cause) {
super(message, cause);
}
}
top.wyxbs.service包下的类:
import top.wyxbs.domain.User;
import top.wyxbs.exception.UserExistException;
public interface BusinessService {
/**
* 完成用户信息注册
* @param user 用户信息
* @throws UserExistException 用户已经存在
*/
void regist(User user) throws UserExistException;
/**
* 完成用户登录
* @param username 用户名
* @param password 密码
* @return 如果用户名或密码不正确,返回null
*/
User login(String username,String password);
}
//--------------------------------------------------
import top.wyxbs.dao.UserDao;
import top.wyxbs.dao.UserDaoImpl;
import top.wyxbs.domain.User;
import top.wyxbs.exception.UserExistException;
public class BusinessServiceImpl implements BusinessService {
private UserDao userDao = new UserDaoImpl();
@Override
public void regist(User user) throws UserExistException {
// TODO Auto-generated method stub
User findUserByName = userDao.findUserByName(user.getUsername());
if(findUserByName!=null){
throw new UserExistException(user.getUsername()+"已经存在");
}
userDao.save(user);
}
@Override
public User login(String username, String password) {
// TODO Auto-generated method stub
return userDao.findUser(username, password);
}
}
//------------------------------------------------------
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
/**
* 用户注册时临时产生的注册用户类
* @author chenjingbin
*
*/
public class UserRegistFormBean {
private String username;
private String password;
private String repassword;
private String email;
private String birthday;
//存放错误信息
private Map errors = new HashMap();
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 getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public Map getErrors() {
return errors;
}
/**
* 验证信息,服务器端
* @return
*/
public boolean validate(){
//只要不满足要求的,就像errors中放消息
//用户名必须输入,3~8位字母组成
if(username==null||username.equals("")){
errors.put("username", "请输入用户名");
}else{
if(!username.matches("[a-zA-Z]{3,8}")){
errors.put("username", "用户名不符合要求");
}
}
//密码必须输入,3~8位数字组成
if(password == null || password.equals("")){
errors.put("password", "请输入密码");
}else{
if (!password.matches("\\d{3,8}")) {
errors.put("password", "密码不符合要求");
}
}
//重复密码必须和密码一致
if(repassword == null || repassword.equals("")){
errors.put("repassword", "请输入密码");
}else{
if(!password.equals(repassword)){
errors.put("repassword", "两次输入的密码不对");
}
}
//邮箱必须输入,且要符合邮箱的格式
if(email == null || email .equals("")){
errors.put("email", "请输入邮箱");
}else{
if (!email.matches("\\b^['_a-z0-9-\\+]+(\\.['_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|org|pro|tel|travel|xxx)$\\b")) {
errors.put("email", "邮箱格式不符合");
}
}
if(birthday == null || birthday .equals("")){
errors.put("birthday", "请输入生日");
}else{
try{
new DateLocaleConverter().convert(birthday);
}catch (Exception e) {
errors.put("birthday", "请输出正确的日期");
}
}
return errors.isEmpty();
}
}
在写后端代码的时候写完一个小功能代码都需要去测试一下才行,于是有一个test包。
public class BusinessServiceImplTest {
private BusinessService businessService = new BusinessServiceImpl();
@Test
public void registTest(){
User user = new User();
user.setUsername("abc");
user.setPassword("456");
user.setEmail("[email protected]");
user.setBirthday(new Date());
try {
businessService.regist(user);
} catch (UserExistException e) {
// TODO Auto-generated catch block
System.out.println("已经存在");
}
}
@Test
public void loginTest(){
User login = businessService.login("abc", "456");
System.out.println(login);
}
}
//-------------------------------------------------------
import java.util.Date;
import org.junit.Test;
import top.wyxbs.dao.UserDao;
import top.wyxbs.dao.UserDaoImpl;
import top.wyxbs.domain.User;
/**
* 测试userDaoImpl类
* @author chenjingbin
*
*/
public class UserDaoImplTest {
@Test
public void saveTest(){
//测试保存用户是否成功
User user = new User();
user.setUsername("小黄");
user.setPassword("123");
user.setEmail("qewrer");
user.setBirthday(new Date());
UserDao userDao =new UserDaoImpl();
userDao.save(user);
}
@Test
public void findUserByNameTest(){
UserDao userDao =new UserDaoImpl();
User findUserByName = userDao.findUserByName("小黄");
System.out.println(findUserByName.toString());
}
@Test
public void findUserTest(){
UserDao userDao =new UserDaoImpl();
User findUserByName = userDao.findUser("小黄","123");
System.out.println(findUserByName.toString());
}
}
top.wyxbs.web.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 top.wyxbs.domain.User;
import top.wyxbs.service.BusinessService;
import top.wyxbs.service.BusinessServiceImpl;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BusinessService s = new BusinessServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User login = s.login(username, password);
if(login != null){
request.getSession().setAttribute("user", login);
response.getWriter().write("登录成功,2秒转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
}else{
response.getWriter().write("错误的用户名或密码,2秒转向登录页面");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/login.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//---------------------------------------------------
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 chenjingbin
*
*/
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.getSession().removeAttribute("user");
out.write("注销成功");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//-----------------------------------------------------
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import top.wyxbs.domain.User;
import top.wyxbs.exception.UserExistException;
import top.wyxbs.service.BusinessService;
import top.wyxbs.service.BusinessServiceImpl;
import top.wyxbs.service.UserRegistFormBean;
import top.wyxbs.util.WebUtil;
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BusinessService s = new BusinessServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先是考虑编码问题
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//
UserRegistFormBean fillBean = WebUtil.fillBean(request, UserRegistFormBean.class);
//说明信息不符合
if(!fillBean.validate()){
request.setAttribute("formbean", fillBean);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return ;
}
User user = new User();
try {
//注册转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.copyProperties(user, fillBean);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.regist(user);
response.setHeader("Refresh", "2:URL="+request.getContextPath()+"/index.jsp");
response.getWriter().write("注册成功");
} catch (UserExistException e) {
// TODO Auto-generated catch block
//回显数据
fillBean.getErrors().put("username", "用户已经存在");
request.setAttribute("formbean", fillBean);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
还有一个文件那就是web.xml文件:
<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" version="2.5">
<display-name>display-name>
<servlet>
<servlet-name>RegistServletservlet-name>
<servlet-class>top.wyxbs.web.controller.RegistServletservlet-class>
servlet>
<servlet>
<servlet-name>LoginServletservlet-name>
<servlet-class>top.wyxbs.web.controller.LoginServletservlet-class>
servlet>
<servlet>
<servlet-name>LogoutServletservlet-name>
<servlet-class>top.wyxbs.web.controller.LogoutServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>RegistServletservlet-name>
<url-pattern>/servlet/RegistServleturl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServletservlet-name>
<url-pattern>/servlet/LoginServleturl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServletservlet-name>
<url-pattern>/servlet/LogoutServleturl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
最后运行图:
大概就完成了。数据库设计这个比较简单那我就没有给大家去展示了,但是也要去说一下规则吧,创建一个项目那在mysql中也要去创建一个新的数据库,然后创建一个新的用户并设置权限。具体sql语句大家自行去查。
总结一下:这里面没有使用到ajax去处理,如果页面使用jsp代码块的话只用jsp表达式去获取值,用El表达式会出现空值的问题。