分析

  1. DW设计好前台页面拷贝到Eclipse
  2. MYSQL创建好数据表(与注册信息相符)
  3. 创建db.properties文件,把数据库连接信息存进去
  4. 创建工具类DBUtil,建立数据库连接
  5. 创建用户bean属性类,声明注册表信息变量
  6. 创建dao/daoImpl数据库操作接口及实现类
  7. 创建dao/daoImpl数据库操作接口及实现类
  8. 创建service/serviceImpl操作服务接口及实现类
  9. 创建注册servlet,处理注册页面的请求
  10. 创建登陆servlet,处理登陆页面的请求
  11. 创建注销servlet,处理页面发送的请求请求
  12. 测试排错

实现

登陆页面

提交后会检查数据库是否有匹配的用户,下方有个注册链接,点击可跳转。

如果用户名密码错误,跳回登陆页面,并提示错误。

如果用户名密码正确,跳转登陆成功页面,并显示欢迎信息,点击注销,可退出登录

注册页面

提交后会检查数据库是否有相同的用户名。

如果用户名密码正确,提示2秒跳转登陆页面

如果用户名密码错误,跳回注册页面,并提示错误。

MYSQL数据库

数据库设计与注册信息匹配

代码

db.properties文档

  classDriver=com.mysql.cj.jdbc.Driver
  url=jdbc:mysql://localhost:3306/userlist
  username=root
  password=password
  

Login.jsp登陆页面

	<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>
	
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
	<title>Login</title>
	<style type="text/css">
	<!--
	.STYLE1 {
		font-family: Arial, Helvetica, sans-serif;
		font-size: 36px;
		color: #666666;
		font-style: italic;
	}
	-->
	</style>
	</head>
	
	<body>
	<form id="form1" name="form1" method="post" action="${pageContext.request.contextPath }/login">
	<label>
	<div align="center"><span class="STYLE1"><br />
	  <br />
	  <br />
	  <br />
	  Login</span><br />
	  <br />
	  Username
	  <input type="text" name="username" />
	
	  <br />
	      ${msg }
	    <br />
	    Password
	    <input type="password" name="password" />
	    <br />
	    <br />
	  <input type="submit" name="Submit" value="Login" />
	  <br />
	  <br />
	  No account Please Regist <a href="regist.jsp">here</a>. </div>
	  </label>
	  <p align="center">
	    <label></label>
	  </p>
	  <p align="center">
	    <label></label>
	  </p>
	</form>
	</body>
	</html>

regist.jsp注册页面

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>regist</title>
<style type="text/css">
<!--
.STYLE1 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 36px;
	font-style: italic;
	color: #666666;
-->
</style>
</head>

<body>

<form id="form1" name="form1" method="post" action="${pageContext.request.contextPath}/regist">
  <label></label>
  <div align="center">
    <p class="STYLE1">&nbsp;</p>
    <table width="269" border="0">
      <tr>
        <td height="46" colspan="2"><div align="center"><span class="STYLE1">Regist</span></div></td>
      </tr>
 
      <tr>
        <td width="111" height="46"><div align="right">Username:</div></td>
        <td width="148"><label>
          <input type="text" name="username" />
${msg }
        </label></td>
      </tr>
      <tr>
        <td height="24"><div align="right">Password:</div></td>
        <td><input type="password" name="password" /></td>
      </tr>
      <tr>
        <td height="50"><div align="right">ConfirmPassword:</div></td>
        <td><label>
          <input type="password" name="password" />
        </label>
          <label></label></td>
      </tr>
      <tr>
        <td><div align="right">Email:</div></td>
        <td><input type="text" name="mail" /></td>
      </tr>
      <tr>
        <td height="45"><div align="right">Birthday:</div></td>
        <td><label>
          <input type="Date" name="birthday" />
        </label>
          <label> </label></td>
      </tr>
      <tr>
        <td height="40" colspan="2"><label>
          <div align="center">
            <input type="submit" name="Submit" value="Regist" />
          </div>
        </label></td>
      </tr>
      </table>
  </div>
  <label>
  <label><br />
  </label>
  <label></label><label><br />
  </label>
</form>
</body>
</html>

Success注册成功

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Success Regist</title>
<style type="text/css">
<!--
.STYLE1 {color: #0000CC}
.STYLE2 {font-size: 16px}
-->
</style>
</head>

<body>

<div align="center">
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p class="STYLE2">Welcome your coming: <span class="STYLE1">${user.username }</span></p>
  <p class="STYLE2"><a href="${pageContext.request.contextPath }/logout">Logout</a></p>
</div>
</body>
</html>

DBUtils数据库连接

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

import org.junit.Test;
/*
 * 
 * 数据库连接,调用properties文件
 * 
 * */
public class DBUtil {
	private static String classDriver;
	private static String url;
	private static String username;
	private static String password;
	static {
		ResourceBundle rb = ResourceBundle.getBundle("db");
		classDriver = rb.getString("classDriver");
		url = rb.getString("url");
		username = rb.getString("username");
		password = rb.getString("password");

		try {
			Class.forName(classDriver);
		} catch (ClassNotFoundException e) {
			System.out.println("driver ok");
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, username, password);

	}
}

bean用户注册信息

package javabean;

import java.util.Date;
/*
 * 
 * 用户注册信息
 * 
 */
public class user {
	private int id;
	private String username;
	private String password;
	private String mail;
	private Date birthday;
	

	public int getId() {
		return id;
	}
	public void setId(int 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 getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public Date getbirthday() {
		return birthday;
	}
	public void setbirthday(Date birthday) {
		this.birthday = birthday;
	}

	
	
}

dao访问数据库接口

package dao;

import javabean.user;

public interface userDao {
	/*
	 * 
	 * 数据库操作接口
	 * 
	 */
	public void addUser(user user)throws Exception;

	
	public user findUsernameAndPassword (user user) throws Exception;
	
	public user findUsername(user user) throws Exception;
}

Impl数据库操作类

package dao.Impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import dao.userDao;
import javabean.user;
import util.DBUtil;

public class userDaoImpl implements userDao {
	/*
	 * 
	 * 数据库操作实现类
	 * 
	 */
	@Override
	public void addUser(user user) throws Exception {
	Connection conn=null;
	PreparedStatement ps=null;
	
	conn=DBUtil.getConnection();
	ps=conn.prepareStatement("insert into userlist.t_user(username,password,mail,birthday) values (?,?,?,?)");
	ps.setString(1, user.getusername());
	ps.setString(2, user.getpassword());
	ps.setString(3,user.getMail());
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	String birthday=sdf.format(user.getbirthday());
	ps.setString(4, birthday);
	
	ps.execute();
	}
	
	@Override
	public user findUsernameAndPassword(user user) throws Exception {
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		conn=DBUtil.getConnection();
		ps=conn.prepareStatement("Select username,password,mail,birthday from userlist.t_user where username=? and password=?");
		ps.setString(1,user.getusername());
		ps.setString(2,user.getpassword());
		rs=ps.executeQuery();
		
		user u = null;
		if (rs.next()) {
			u = new user();
			u.setusername(rs.getString("username"));
			u.setpassword(rs.getString("password"));
			u.setMail(rs.getString("mail"));
			u.setbirthday(rs.getDate("birthday"));
		}
		return u;
	}

	@Override
	public user findUsername(user user) throws Exception {
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		conn=DBUtil.getConnection();
		ps=conn.prepareStatement("Select username,password,mail,birthday from userlist.t_user where username=?");
		ps.setString(1,user.getusername());
		rs=ps.executeQuery();
		
		user u = null;
		if (rs.next()) {
			u = new user();
			u.setusername(rs.getString("username"));
			u.setpassword(rs.getString("password"));
			u.setMail(rs.getString("mail"));
			u.setbirthday(rs.getDate("birthday"));
		}
		return u;
	}
	

}

Service处理数据服务接口

package service;

import javabean.user;

public interface userService {
	/*
	 * 
	 * 处理数据提供服务接口
	 * 
	 */
	public void addUser(user user) throws Exception;
	
	public user findUsernameAndPassword(user user) throws Exception;
	
	public user findUsername(user user) throws Exception;
}

ServiceImpl处理数据服务实现类

package service.Impl;

import dao.userDao;
import dao.Impl.userDaoImpl;
import javabean.user;
import service.userService;

public class userServiceImpl implements userService {
	/*
	 * 
	 * 处理数据服务实现类
	 * 
	 */
	
		userDao userdao=new userDaoImpl();
	@Override
	public void addUser(user user) throws Exception {
		userdao.addUser(user);

	}
	@Override
	public user findUsernameAndPassword(user user) throws Exception {
		return userdao.findUsernameAndPassword(user);
	}
	@Override
	public user findUsername(user user) throws Exception {
		return userdao.findUsername(user);
	}
	
}

ServLetlogin处理登陆页面发送过来的数据

package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javabean.user;
import service.userService;
import service.Impl.userServiceImpl;

public class login extends HttpServlet {
	/*
	 * 
	 * 处理登陆页面发送过来的数据
	 * 
	 * 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");		
		response.setContentType("text/html; charset=utf-8");
		
		user user=new user();
		user.setusername(request.getParameter("username"));
		user.setpassword(request.getParameter("password"));
		
		userService us=new userServiceImpl();
		try {
			user u=us.findUsernameAndPassword(user);
			if (u !=null) {
				request.getSession().setAttribute("user", u);
				request.getRequestDispatcher("/success_regist.jsp").forward(request, response);
			}else {
				request.setAttribute("msg", "用户名或密码错误!");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

ServletLogout处理注销登陆请求

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class logout extends HttpServlet {
	/*
	 * 
	 * 处理注销登陆请求
	 * 
	 */
	
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath() + "/login.jsp");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doGet(request, response);
	}

}

ServLetRegist处理用户注册信息

package servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 javabean.user;
import service.userService;
import service.Impl.userServiceImpl;

public class regist extends HttpServlet {
	private static final long serialVersionUID = 1L;
    /*
     * 
     * 处理用户注册信息
     * 
     */
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");		
		response.setContentType("text/html; charset=utf-8");
		
		user u=new user();
		u.setusername(request.getParameter("username"));
		u.setpassword(request.getParameter("password"));
		u.setMail(request.getParameter("mail"));

			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

			try {
				Date birthday = sdf.parse(request.getParameter("birthday"));
				u.setbirthday(birthday);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

//		try {
//			ConvertUtils.register(new DateLocaleConverter(), Date.class);
//			BeanUtils.populate(u, request.getParameterMap());
//		} catch (IllegalAccessException e1) {
//			e1.printStackTrace();
//		} catch (InvocationTargetException e1) {
//			e1.printStackTrace();
//		}

		userService us=new userServiceImpl();

		
		try {
			user result=us.findUsername(u);
			if (result!=null) {
				request.setAttribute("msg", "用户名重复!");
				request.getRequestDispatcher("/regist.jsp").forward(request, response);;
			}else {
				us.addUser(u);
				response.getWriter().write("恭喜!注册成功!2秒后跳转到登陆页面。");
				response.setHeader("refresh","2;"+request.getContextPath()+"/login.jsp");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doGet(request, response);
	}

}

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">
<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>regist</display-name>
  <servlet-name>regist</servlet-name>
  <servlet-class>servlet.regist</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>regist</servlet-name>
  <url-pattern>/regist</url-pattern>
</servlet-mapping>
<servlet>
  <description></description>
  <display-name>login</display-name>
  <servlet-name>login</servlet-name>
  <servlet-class>servlet.login</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
  <description></description>
  <display-name>logout</display-name>
  <servlet-name>logout</servlet-name>
  <servlet-class>servlet.logout</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>logout</servlet-name>
  <url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>