下面来解读下三层架构的登录和注册功能实现,本文采用的是myeclipse工具!如果是idea或者eclipse工具的同学,你可以自己参考本文写读。
项目的主要结构:
com.db(数据库连接类):
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static final String dDriver="com.mysql.jdbc.Driver";//mysql驱动名
private static final String url="jdbc:mysql://localhost:3306/uc_test";//数据库访问地址
private static final String us="root";//数据库账号
private static final String pw="123456";//数据库密码
private Connection conn=null;//数据库连接对象
//通过构造方法进行数据库连接
public DBConnection() throws Exception{
try {
Class.forName(dDriver);//通过发射机制加载驱动
this.conn=DriverManager.getConnection(url, us, pw);
} catch (Exception e) {
throw e;
}
}
//取得数据库连接
public Connection getConneticon(){
return this.conn;
}
//关闭对象,释放内存
public void object() throws Exception{
try {
if(this.conn!=null){
this.conn.close();
}
} catch (SQLException e) {
throw e;
}
}
}
com.user(Bena类对象):
package com.user;
public class User {
private int id;//id
private String username;//用户账号
private String password;//密码
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;
}
}
com.dao(数据访问层):
package com.dao;
import com.user.User;
public interface UserDao {
//注册用户
public int addUser(User user) throws Exception;
//登录
public boolean selectUser(User user) throws Exception;
//根据用户名判断用户是否存在
public User findUser(String username) throws Exception;
}
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.user.User;
public class UserDaoImpI implements UserDao {
private Connection conn=null;//数据库连接对象
private PreparedStatement pstmt=null;//mysql执行对象
ResultSet rs=null;//结果集对象
//通过构造方法取得数据库连接
public UserDaoImpI(Connection conn){
this.conn=conn;
}
//注册
public int addUser(User user) throws Exception {
int result=0;//自定义标识,用来接收受影响的行数
String sql="insert into us_test(username,password) values(?,?)";
this.pstmt=this.conn.prepareStatement(sql);//预加载sql语句
this.pstmt.setString(1,user.getUsername());//设置用户名
this.pstmt.setString(2,user.getPassword());//设置用户密码
result=this.pstmt.executeUpdate();//执行数据库操作
pstmt.close();
return result;
}
//登录
public boolean selectUser(User user) throws Exception {
boolean flag=false;//自定义标识
String sql="select * from us_test where username=? and password=?";
this.pstmt=this.conn.prepareStatement(sql);//预加载mysql语句
this.pstmt.setString(1,user.getUsername());//设置用户名
this.pstmt.setString(2,user.getPassword());//设置用户密码
rs=this.pstmt.executeQuery();//执行数据库操作
if(rs.next()){//如果有记录则表示用户存在
flag=true;
}
return flag;
}
//根据用户名查找用户是否存在
public User findUser(String username) throws Exception {
String sql="select * from us_test where username=?";
User u=new User();
this.pstmt=this.conn.prepareStatement(sql);//预加载mysql语句
this.pstmt.setString(1,username);//设置用户名
rs=this.pstmt.executeQuery();//执行数据库操作
if(rs.next()){//如果有一条用户记录,则封装到user对象中
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassword(rs.getString(3));
}
rs.close();
pstmt.close();
return u;
}
}
com.service(业务逻辑层):
package com.service;
import com.dao.UserDao;
import com.dao.UserDaoImpI;
import com.db.DBConnection;
import com.user.User;
public class UserService implements UserDao{
private DBConnection conn=null;//数据库连接类
private UserDao dao=null;//dao实例化对象
//实例化数据库连接,并且实例化dao实现类
public UserService() throws Exception{
this.conn=new DBConnection();
this.dao=new UserDaoImpI(this.conn.getConneticon());
}
//注册
public int addUser(User user) throws Exception {
int result=0;//标识
try {
result=this.dao.addUser(user);
} catch (Exception e) {
throw e;
}finally{
this.conn.object();
}
return result;
}
//登录
public boolean selectUser(User user) throws Exception {
boolean flag=false;
try {
flag=this.dao.selectUser(user);
} catch (Exception e) {
throw e;
}finally{
this.conn.object();
}
return flag;
}
//根据用户名查找用户是否存在
public User findUser(String username) throws Exception {
User u=null;
try {
u=this.dao.findUser(username);
} catch (Exception e) {
throw e;
}finally{
this.conn.object();
}
return u;
}
}
com.factory(工厂类):
package com.factory;
import com.dao.UserDao;
import com.service.UserService;
public class Botory {
public static UserDao getUserfind() throws Exception{
return new UserService();
}
}
com.servlet(登录和注册的业务代码实现):
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.factory.Botory;
import com.user.User;
@WebServlet(name="Insert",urlPatterns="/insert")
public class Insert extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//设置响应编码格式
String username=req.getParameter("username");//获取用户输入的账号
String password=req.getParameter("password");//获取用户输入的密码
User user =new User();
user.setUsername(username);//设置用户账号
user.setPassword(password);//设置用户的密码
try {
if(Botory.getUserfind().findUser(username).getId()==0){//用户名可用
if(Botory.getUserfind().addUser(user)>0){//注册成功
req.setAttribute("status","ok");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}else{
req.setAttribute("status","vo");
req.getRequestDispatcher("/insert.jsp").forward(req, resp);
}
}else{
req.setAttribute("status","on");
req.getRequestDispatcher("/insert.jsp").forward(req, resp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.factory.Botory;
import com.user.User;
@WebServlet(name="Login",urlPatterns="/login")
public class Login extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//设置请求编码格式
String username=req.getParameter("username");//获取用户输入的账号
String password=req.getParameter("password");//获取用户输入的密码
try {
User user=new User();
user.setUsername(username);//设置用户账号
user.setPassword(password);//设置用户密码
boolean flag=Botory.getUserfind().selectUser(user);
if(flag){
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}else{
req.setAttribute("status","on");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
login.jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登录</title>
</head>
<body>
<form action="login" method="post">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
<script type="text/javascript">
var error='<%=request.getAttribute("status")%>';
if(error=="on"){
alert("账号或密码错误!");
}else if(error="ok"){
alert("注册成功,请登录!");
}
</script>
</html>
insert.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>注册</title>
</head>
<body>
<form action="insert" method="post">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
<script type="text/javascript">
var error='<%=request.getAttribute("status")%>';
if(error=="on"){
alert("注册用户已存在!");
}else if(error=="vo"){
alert("注册失败!");
}
</script>
</body>
</html>