1. 程式人生 > >Dao模式登入註冊案例

Dao模式登入註冊案例

登陸:


package cn.itcast.domain;

public class User {

private int id;
private String username;
private String password;
private String email;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

}

package cn.itcast.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
//使用配置檔案
public class JdbcUtils {
private static final String DRIVERCLASS;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
static {
DRIVERCLASS = ResourceBundle.getBundle("jdbc").getString("driverClass");
URL = ResourceBundle.getBundle("jdbc").getString("url");
USERNAME = ResourceBundle.getBundle("jdbc").getString("username");
PASSWORD = ResourceBundle.getBundle("jdbc").getString("password");
}
static {
try {
// 將載入驅動操作,放置在靜態程式碼塊中.這樣就保證了只加載一次.
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
// 2.獲取連線
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return con;
}
//關閉操作
public static void closeConnection(Connection con) throws SQLException{
if(con!=null){
con.close();
}
}
public static void closeStatement(Statement st) throws SQLException{
if(st!=null){
st.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException{
if(rs!=null){
rs.close();
}
}

}

頁面顯示/login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <title>My JSP 'index.jsp' starting page</title>
  </head>
    <body>
${requestScope["login.message"]}<br>


<form action="${pageContext.request.contextPath}/login" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="登入">
</form>
  </body>
</html>

執行提交到

package cn.itcast.web.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 cn.itcast.domain.User;
import cn.itcast.exception.LoginException;
import cn.itcast.service.UserService;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.得到使用者名稱與密碼
String username = request.getParameter("username");
String password = request.getParameter("password");
// 2.封裝屬性到javaBean
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 3.呼叫service中登入方法
UserService service = new UserService();
User existUser
null;
try {
existUser=service.login(user);
if (existUser == null) { // 代表使用者名稱或密碼錯誤,儲存錯誤資訊在request域,請求轉發到login.jsp
request.setAttribute("login.message", "使用者名稱或密碼錯誤");
request.getRequestDispatcher("/login.jsp").forward(request,
response);
return;
} else {
request.getSession().setAttribute("user", existUser);存到session中
response.sendRedirect(request.getContextPath() + "/success.jsp");
return;
}
} catch (LoginException e) {
request.setAttribute("login.message", e.getMessage());
request.getRequestDispatcher("/login.jsp").forward(request,
response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

package cn.itcast.service;

import java.sql.SQLException;
import cn.itcast.dao.UserDaoImpl;
import cn.itcast.domain.User;
import cn.itcast.exception.LoginException;
public class UserService {
// service層的登入方法
public User login(User user) throws LoginException {
User existUser = null;
try {
existUser = new UserDaoImpl().findUser(user);
} catch (SQLException e) {
e.printStackTrace();
throw new LoginException("登入失敗");
}
return existUser;
}

}

package cn.itcast.exception;
public class LoginException extends Exception {

public LoginException() {
super();
}
public LoginException(String message, Throwable cause) {
super(message, cause);
}
public LoginException(String message) {
super(message);
}
public LoginException(Throwable cause) {
super(cause);
}

}

封裝

package cn.itcast.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import cn.itcast.domain.User;
import cn.itcast.exception.LoginException;
import cn.itcast.utils.JdbcUtils;
public class UserDaoImpl implements UserDao{
// 查詢使用者---使用Statement完成登入操作,存在風險(sql注入)
public User findUser(User user) throws SQLException  {
// 1.sql語句
String sql = "select * from user where username='" + user.getUsername()
+ "' and password='" + user.getPassword() + "'";
// 2.執行sql
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = JdbcUtils.getConnection();
st = con.createStatement();
rs = st.executeQuery(sql);
if (rs.next()) { // 如果可以next,代表查詢到了這個使用者的資訊就將結果集中的資訊封裝到User物件中.
User u = new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
return u;
}
} finally {
try {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(st);
JdbcUtils.closeConnection(con);

} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
// 使用PreparedStatement來完成操作,它可以解決sql注入.
public User findUser(User user) throws SQLException {
// 1.sql語句
String sql = "select * from user where username=? and password=?";
// 2.執行sql
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = JdbcUtils.getConnection();
pst = con.prepareStatement(sql);
pst.setString(1, user.getUsername());
pst.setString(2, user.getPassword());
rs = pst.executeQuery();// 無引數
if (rs.next()) { // 如果可以next,代表查詢到了這個使用者的資訊,就將結果集中的資訊封裝到User物件中.
User u = new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
return u;
}
}finally {
try {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(pst);
JdbcUtils.closeConnection(con);

} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}

}

package cn.itcast.dao;
import cn.itcast.domain.User;
public interface UserDao {
public User findUser(User user) throws Exception;
}

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>登入成功:${user.username}
</body>
</html>

註冊