这是转载自http://www.cnblogs.com/bejour/p/3351920.html感觉很有用,与大家分享。
对初次接触java ee,感觉这个简单的m删除文字格式vc实现的用户登录与注册比较的有参照价值。故记录下来。本篇中的代码源自于《轻量级Java EE企业应用实战(第三版)》第二章,其原来的代码是实现用户登录,我在它的基础上依照它的写法添加了用户注册。代码很粗陋,但是能用。Model模块代码,实现对数据库中表的操作
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class DbDao {
private Connection conn;
private String driver;
private String url;
private String username;
private String pass;
public DbDao(){
}
public DbDao(String driver, String url, String username, String pass) {
this.driver = driver;
this.url = url;
this.username = username;
this.pass = pass;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
删除文字格式 this.conn = conn;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
// get database connection
public Connection getConnection() throws Exception {
if(conn == null){
Class.forName(this.driver);
conn = (Connection) DriverManager.getConnection(url, username, this.pass);
}
return conn;
}
// insert records
public boolean insert(String sql, Object... args) throws Exception{
PreparedStatement pstmt = (PreparedStatement) getConnection().prepareStatement(sql);
for(int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
if(pstmt.executeUpdate() != 1)
return false;
return true;
}
// execute query
public ResultSet query(String sql, Object...args) throws Exception{
PreparedStatement pstmt = (PreparedStatement) getConnection().prepareStatement(sql);
for(int i=0; i< args.length; i++) {
pstmt.setObject(i+1, args[i]);
}
return pstmt.executeQuery();
}
public void modify(String sql, Object...args) throws Exception{
PreparedStatement pstmt = (PreparedStatement)getConnection().prepareStatement(sql);
for(int i = 0; i< args.length; i++) {
pstmt.setObject(i+1, args[i]);
}
pstmt.executeUpdate();
pstmt.close();
}
public void closeConn() throws Exception{
if(conn != null && !conn.isClosed())
conn.close();
}
}
contol模块代码,用servlet实现请求的处理及对数据库的查询与修改
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
@WebServlet(name="login", urlPatterns={"/login"})
public class LoginServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String errMsg = "";
RequestDispatcher rd;
String username = request.getParameter("username");
String pass = request.getParameter("pass");
try {
DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test",
"root", "root");
// 查询结果集
ResultSet rs = dd.query("select pass from user_table where username = ?", username);
if(rs.next()){
//用户名和密码匹配
if(rs.getString("pass").equals(pass)) {
//获取session对象
HttpSession session = request.getSession(true);
session.setAttribute("name", username);
//获取转发对象
rd = request.getRequestDispatcher("/welcome.jsp");
// 转发请求
rd.forward(request, response);
} else {
errMsg += "您的用户名密码不匹配,请重新输入";
}
} else {
errMsg += "您的用户名不存在,请先注册";
}
}catch(Exception e) {
e.printStackTrace();
}
// 如果出错,转发到重新登陆
if(errMsg != null && !errMsg.equals("")){
rd = request.getRequestDispatcher("/login.jsp");
request.setAttribute("err", errMsg);
rd.forward(request, response);
}
}
}
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
@WebServlet(name="register", urlPatterns={"/register"})
public class RegisterServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String errMsg = "";
RequestDispatcher rd;
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String conPass = request.getParameter("conPass");
if((username.length()==0)|| (pass.length()==0)||!pass.equals(conPass))
errMsg += "注册失败,请检查用户名和密码非空,并确定密码一致";
else {
try {
DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test",
"root", "root");
ResultSet rs = dd.query("select pass from user_table where username = ?", username);
if(rs.next()) {
errMsg += "用户已经存在,请重新设置用户名";
}
else {
boolean addUser = dd.insert("insert into user_table(username, pass) values(?, ?)",username, pass);
if(!addUser) {
errMsg += "注册用户出现错误";
}
// 注册成功,转发到welcome.jsp
HttpSession session = request.getSession(true);
session.setAttribute("name", username);
//获取转发对象
rd = request.getRequestDispatcher("/welcome.jsp");
// 转发请求
rd.forward(request, response);
}
}catch(Exception e) {
e.printStackTrace();
}
}
// 如果出错,转发到重新注册
if(errMsg != null && !errMsg.equals("")){
rd = request.getRequestDispatcher("/register.jsp");
request.setAttribute("err", errMsg);
rd.forward(request, response);
}
}
}
View模块,用jsp呈现注册与登录页面,以及成功后的登录页面。
<%@ page language="java" contentType="text/html; charset=GBK"
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=ISO-8859-1">
<title>Login</title>
</head>
<body>
<!-- 输出错误提示信息 -->
<span style="color:red; font-weight:bold">
<%
if(request.getAttribute("err")!=null){
out.println(request.getAttribute("err") + "<br/>");
}
%>
</span>
请输入用户名和密码:
<form id="login" method="post" action="login">
用户名:<input type="text" name="username" /><br/>
密码 <input type="password" name="pass" /><br/>
<input type="submit" value="登陆"/><br/>
</form>
<a href="register.jsp">注册用户</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GBK"
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=ISO-8859-1">
<title>Login</title>
</head>
<body>
<!-- 输出错误提示信息 -->
<span style="color:red; font-weight:bold">
<%
if(request.getAttribute("err")!=null){
out.println(request.getAttribute("err") + "<br/>");
}
%>
</span>
请输入用户名和密码:
<form id="login" method="post" action="register">
用户名:<input type="text" name="username" /><br/>
密码 <input type="password" name="pass" /><br/>
确认密码<input type="password" name="conPass" /><br/>
<input type="submit" value="注册"/><br/>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GBK"
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=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<h2>欢迎登陆, <%=request.getParameter("username") %></h2>
</body>
</html>
这里需要用到mysql数据库,在test数据库中建立user_table表,建表的语句可以如下(但不限于
create table user_table( id int primary key auto_increment, username varchar(20), pass varchar(20) );