使用Servlet開發用戶登錄功能 => spring
改造前
目錄
user.java
package com.bean;
public class user {
private Integer u_id;
private String u_username;
private String u_password;
public user(String u_username, String u_password) {
this.u_username = u_username;
this.u_password = u_password;
}
public user() {
}
public Integer getU_id() {
return u_id;
}
public void setU_id(Integer u_id) {
this.u_id = u_id;
}
public String getU_username() {
return u_username;
}
public void setU_username(String u_username) {
this.u_username = u_username;
}
public String getU_password() {
return u_password;
}
public void setU_password(String u_password) {
this.u_password = u_password;
}
}
userDaoImpl.java c3p0來連接數據庫
package com.dao;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.bean.user;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class userDaoImpl implements userDao {
private static ComboPooledDataSource dpdsource;
static {
// 連接數據庫c3p0
try {
dpdsource = new ComboPooledDataSource();
dpdsource.setDriverClass("com.mysql.cj.jdbc.Driver");
dpdsource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC");
dpdsource.setUser("root");
dpdsource.setPassword("88888888");
} catch (PropertyVetoException e) {
e.printStackTrace();
System.out.println("連接失敗");
}
}
public user getuserByInfo(user u) { // 通過數據庫獲取用戶
QueryRunner qr = new QueryRunner(dpdsource); // 使用一個類 操作數據庫 查詢並返回對象
String sql = "select * from user1 where u_username =? and u_password = ?";
try {
return qr.query(sql, new BeanHandler<user>(user.class), u.getU_username(), u.getU_password());
} catch (SQLException e) {
e.printStackTrace();
System.out.println("返回失敗");
}
return null;
}
}
userserviceImpl.java
package com.service;
import com.bean.user;
import com.dao.userDao;
import com.dao.userDaoImpl;
public class userServiceImpl implements userService {
private userDao ud = new userDaoImpl();
@Override
public user getuserByInfo(user u) {
return ud.getuserByInfo(u);
}
}
userLoginService.java
package com.web;
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 javax.servlet.http.HttpSession;
import com.bean.user;
import com.service.userService;
import com.service.userServiceImpl;
@WebServlet("/userLogin")
public class userLoginService extends HttpServlet {
private static final long serialVersionUID = 1L;
public userLoginService() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收表單信息數據
String username = request.getParameter("username");
String password = request.getParameter("password");
user u = new user(username, password);
// 封裝成user對象
// 調用service方法驗證用戶
// 根據用戶驗證結果進行操作
userService us = new userServiceImpl();
user loginUser = us.getuserByInfo(u);
if (loginUser == null) {
// 驗證失敗到login_page.jsp
request.setAttribute("errorMsg", "登陸失敗");
request.getRequestDispatcher("/login_page.jsp").forward(request, response);
}
// 驗證成功登陸,重定向到index.jsp
else {
HttpSession session = request.getSession();
session.setAttribute("user", loginUser);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>我是首頁,登錄成功</h1>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>登錄/注冊</title>
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- bootstrap framework -->
<link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- elegant icons -->
<link href="${pageContext.request.contextPath }/css/style.css" rel="stylesheet" media="screen">
<!-- main stylesheet -->
<link href="${pageContext.request.contextPath }/css/main.min.css" rel="stylesheet" media="screen">
<!-- jQuery -->
<script src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
</head>
<body class="login_page">
<div class="login_header">
</div>
<div class="login_register_form">
<div class="form_wrapper animated-short" id="login_form">
<h3 class="sepH_c"><span>Login</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="register_form">Register</a></h3>
<form id="loginFrom" action="${pageContext.request.contextPath }/userLogin" method="post">
<div class="input-group input-group-lg sepH_a">
<span class="input-group-addon"><span class="icon_profile"></span></span>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="input-group input-group-lg">
<span class="input-group-addon"><span class="icon_key_alt"></span></span>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div>
<a id="errorMsg" href="javascript:void(0)" style="color: red">${errorMsg}</a>
</div>
<div class="sepH_c text-right">
<a href="javascript:void(0)" class="small">Forgot password?</a>
</div>
<div class="form-group sepH_c">
<a href="javascript:doucment:loginFrom.submit()" class="btn btn-lg btn-primary btn-block">Log in</a>
</div>
</form>
</div>
<div class="form_wrapper animated-short" id="register_form" style="display:none">
<h3 class="sepH_c"><span>Register</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="login_form">Login</a></h3>
<form name = "registerForm" action="${pageContext.request.contextPath}/userRegister" method="post">
<div class="input-group input-group-lg sepH_a">
<span class="input-group-addon"><span class="icon_profile"></span></span>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="input-group input-group-lg sepH_a">
<span class="input-group-addon"><span class="icon_key_alt"></span></span>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="input-group input-group-lg sepH_c">
<span class="input-group-addon"><span class="icon_mail_alt"></span></span>
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="form-group sepH_c">
<a href="javascript:doucment:registerForm.submit()" class="btn btn-lg btn-success btn-block">Register</a>
</div>
</form>
</div>
</div>
<script>
$(function () {
$('.form-switch').on('click', function (e) {
e.preventDefault();
var $switchTo = $(this).data('switchForm'),
$thisForm = $(this).closest('.form_wrapper');
$('.form_wrapper').removeClass('fadeInUpBig');
$thisForm.addClass('fadeOutDownBig');
setTimeout(function () {
$thisForm.removeClass('fadeOutDownBig').hide();
$('#' + $switchTo).show().addClass('fadeInUpBig');
}, 300);
});
});
</script>
</body>
</html>
改造后 :通過spring注入
applicationContext.xml
<!-- 配置c3p0連接池 -->
<bean name="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="88888888" />
</bean>
<!-- 配置dao alt + / 自動命名-->
<bean name="userDao" class="com.dao.userDaoImpl">
<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- 配置service -->
<bean name="userService" class="com.service.userServiceImpl">
<property name="ud" ref="userDao"/>
</bean>
userLoginService.java
package com.web;
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 javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bean.user;
import com.service.userService;
@WebServlet("/userLogin")
public class userLoginService extends HttpServlet {
private static final long serialVersionUID = 1L;
public userLoginService() {
super();
}
private userService us;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收表單信息數據
String username = request.getParameter("username");
String password = request.getParameter("password");
user u = new user(username, password);
// 封裝成user對象
// 調用service方法驗證用戶
// 根據用戶驗證結果進行操作
// userService us = new userServiceImpl();通過容器獲取!!!
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
us = (userService) ac.getBean("userService");
user loginUser = us.getuserByInfo(u);
if (loginUser == null) {
// 驗證失敗到login_page.jsp
request.setAttribute("errorMsg", "登陸失敗");
request.getRequestDispatcher("/login_page.jsp").forward(request, response);
}
// 驗證成功登陸,重定向到index.jsp
else {
HttpSession session = request.getSession();
session.setAttribute("user", loginUser);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
每次請求都會新創建一個容器,在web項目中我們只需要一個
useloginService.java
package com.web;
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 javax.servlet.http.HttpSession;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.bean.user;
import com.service.userService;
@WebServlet("/userLogin")
public class userLoginService extends HttpServlet {
private static final long serialVersionUID = 1L;
public userLoginService() {
super();
}
private userService us;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收表單信息數據
String username = request.getParameter("username");
String password = request.getParameter("password");
user u = new user(username, password);
// 封裝成user對象
// 調用service方法驗證用戶
// 根據用戶驗證結果進行操作
// userService us = new userServiceImpl();通過容器獲取!!!
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
us = (userService) wac.getBean("userService");
user loginUser = us.getuserByInfo(u);
if (loginUser == null) {
// 驗證失敗到login_page.jsp
request.setAttribute("errorMsg", "登陸失敗");
request.getRequestDispatcher("/login_page.jsp").forward(request, response);
}
// 驗證成功登陸,重定向到index.jsp
else {
HttpSession session = request.getSession();
session.setAttribute("user", loginUser);
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
applicationContext.xml
<!-- 配置c3p0連接池 -->
<bean name="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="88888888" />
</bean>
<!-- 配置dao alt + / 自動命名-->
<bean name="userDao" class="com.dao.userDaoImpl">
<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- 配置service -->
<bean name="userService" class="com.service.userServiceImpl">
<property name="ud" ref="userDao"/>
</bean>
DAO類都是進行數據操作的類,
是對於數據庫中的數據做增刪改查等操作的代碼。
DAO(Data Access Object) 數據訪問對象是一個面向對象的數據庫接口,它顯露了 Microsoft Jet 數據庫引擎(由 Microsoft Access 所使用),並允許 Visual Basic 開發者通過 ODBC 像直接連接到其他數據庫一樣,直接連接到 Access 表。DAO 最適用於單系統應用程序或小范圍本地分布使用。
DAO層一般有接口和該接口的實現類,接口用於規范實現類,實現類一般用於用於操作數據庫! 一般操作修改,添加,刪除數據庫操作的步驟很相似,就寫了一個公共類DAO類 ,修改,添加,刪除數據庫操作時直接調用公共類DAO類。
擴展資料:
DAO(Data Access Object)是一個數據訪問接口,數據訪問:顧名思義就是與數據庫打交道。夾在業務邏輯與數據庫資源中間。
在核心J2EE模式中是這樣介紹DAO模式的:為了建立一個健壯的J2EE應用,應該將所有對數據源的訪問操作抽象封裝在一個公共API中。用程序設計的語言來說,就是建立一個接口,接口中定義了此應用程序中將會用到的所有事務方法。在這個應用程序中,當需要和數據源進行交互的時候則使用這個接口,並且編寫一個單獨的類來實現這個接口在邏輯上對應這個特定的數據存儲。
訪問對象
DAO(數據訪問對象)是一種應用程序編程接口(API),存在於微軟的Visual Basic中,它允許程序員請求對微軟的Access數據庫的訪問。DAO是微軟的第一個面向對象的數據庫接口。DAO對象封閉了Access的Jet函數。通過Jet函數,它還可以訪問其他的結構化查詢語言(SQL)數據庫。