使用SSH框架實現簡單的登入功能
一、準備工作
1.資料庫
2.開發工具
開發工具與環境:MyEclipse2017,jdk1.8,tomcat8.0
二、環境搭建
1.開啟MyEclipse,建立web工程ssh_example
點選finish即可
2.匯入jar包
jar包下載地址https://pan.baidu.com/s/1htoiLQO,密碼vtf8
將所有的jar包複製到工程的WebRoot/WEB-INF/lib目錄下,並Add to Build Path
接下來就開始寫程式碼了。
三、程式碼實現
1.建立實體類User和hibernate對映配置檔案
首先在src下建立包entity,在此包下建立User.java和User.hbm.xml檔案
User.java:
package entity;
public class User {
private Integer uid;
private String username;
private String password;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
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;
}
@Override
public String toString () {
return "User [uid=" + uid + ", username=" + username + ", password=" + password + "]";
}
}
User.hbm.xml:對映檔案中配置的是資料庫表和實體類User的對映關係
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 資料庫表與實體類的對映配置 -->
<hibernate-mapping>
<!-- name:實體類的全路徑;table:資料庫中的表名 -->
<class name="entity.User" table="user">
<!-- id:主鍵,property:一般屬性
name:實體類中的屬性名;column:資料庫表的欄位名,若不配置則預設與屬性名相同 -->
<id name="uid" column="uid">
<!-- 主鍵自增策略 -->
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
2.建立UserDao類
在src下建立dao包,並在包內建立UserDao.java
UserDao.java:
package dao;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import entity.User;
public class UserDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
// 新增使用者
public boolean addUser(User user) {
if(!verifyUsername(user.getUsername())) {
hibernateTemplate.save(user);
return true;
}
return false;
}
// 驗證使用者名稱是否存在
public boolean verifyUsername(String username) {
List<User> users = (List<User>) hibernateTemplate.find("from User where username=?", username);
return users.isEmpty() ? false:true;
}
// 驗證密碼是否正確
public boolean verifyPassword(String username, String password) {
List queryList = hibernateTemplate.find("select password from User where username=?", username);
return ( queryList.get(0).toString() ).equals(password);
}
}
3.建立UserService類
在src下建立service包,並在包內建立UserService.java
package service;
import org.springframework.transaction.annotation.Transactional;
import dao.UserDao;
import entity.User;
@Transactional
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public boolean loginVerify(String username, String password) {
boolean passLogin = false;
passLogin = userDao.verifyUsername(username);
if(passLogin) {
passLogin = userDao.verifyPassword(username, password);
}
return passLogin;
}
public boolean userRegister(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
return userDao.addUser(user);
}
}
4.建立action類
由於需要實現登入和註冊兩個功能,所以編寫兩個action類LoginActon和RegisterAction,分別實現登入和註冊功能
在src下建立action包,並在此包內建立LoginAction.java和RegisterAction兩個類
LoginAction.java
package action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import entity.User;
import service.UserService;
public class LoginAction extends ActionSupport implements SessionAware {
private UserService userService;
private String username;
private String password;
private Map session;
public void setSession(Map session) {
this.session = session;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
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 void validate() {
super.clearErrorsAndMessages();
if("".equals(username)) {
super.addActionError("使用者名稱不能為空!");
}
if("".equals(password)) {
super.addActionError("密碼不能為空!");
}
}
public String execute() {
if(userService.loginVerify(username, password)){
User user = new User();
user.setUsername(username);
user.setPassword(password);
session.put("user", user);
return "success";
} else {
super.addActionError("登入失敗!");
return INPUT;
}
}
}
RegisterAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
import service.UserService;
public class RegisterAction extends ActionSupport {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
private String username;
private String password;
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 void validate() {
super.clearErrorsAndMessages();
if("".equals(username)) {
super.addActionError("使用者名稱不能為空!");
}
if("".equals(password)) {
super.addActionError("密碼不能為空!");
}
}
public String execute() {
if(userService.userRegister(username, password)) {
super.addActionMessage("註冊成功!");
} else {
super.addActionError("註冊失敗,該使用者名稱已存在!");
}
return "success";
}
}
5.建立並編寫相關配置檔案
(1)log4j配置檔案
工程需要使用log4j作為日誌輸出工具,故需要log4j的配置檔案
在src下建立log4j.properties檔案,內容如下:
#log4j.properties
log4j.rootLogger=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] -%m%n
(2)struts2的配置檔案
在src下建立struts.xml檔案,註冊action,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="demo" namespace="/" extends="struts-default">
<!-- class屬性中不寫action的路徑,因為在spring已經配置過了,應該寫spring中bean的id -->
<action name="loginAction" class="loginAction">
<result name="success">/loginSuccess.jsp</result>
<result name="input">/login.jsp</result>
</action>
<action name="registerAction" class="registerAction">
<result name="success">/register.jsp</result>
<result name="input">/register.jsp</result>
</action>
</package>
</struts>
(3)hibernate核心配置檔案
在該例中將hibernate核心配置檔案中的配置寫在了下面的spring配置檔案中
(4)spring的配置檔案
spring配置檔案起到了整合struts2和hibernate的重要作用
在src目錄下建立spring配置檔案applicationContext.xml,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 資料來源的配置,使用C3P0連線池,使用者名稱和密碼需要根據實際情況配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh_example"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- hibernate核心配置 -->
<property name="hibernateProperties">
<props>
<!-- 是否需要列印sql語句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否對列印的sql語句進行格式化(容易閱讀) -->
<prop key="hibernate.format_sql">true</prop>
<!-- 是否自動建立表,update:若表存在則更新,不存在則自動建立 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- hibernate對映檔案的引入 -->
<property name="mappingResources">
<list>
<value>entity/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 開啟事務註解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 管理struts2的action物件,scope="prototype"表示多例 -->
<bean id="loginAction" class="action.LoginAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<bean id="registerAction" class="action.RegisterAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="dao.UserDao">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>
(5)web.xml配置
在WebRoot/WEB-INF目錄下建立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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ssh_example</display-name>
<!-- 指定spring配置檔案的路徑 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- struts2核心過濾器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!-- context監聽器的配置,此監聽器會監聽到servletContext物件的建立,然後載入spring配置檔案,建立spring配置檔案中宣告的物件,並儲存到servletContext容器中去 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
6.前臺介面
最後就是編寫簡單的前臺介面,與後臺進行互動
需要的介面由登陸介面,註冊介面和登入成功的介面
在WebRoot目錄下分別建立login.jsp,register.jsp和loginSuccess.jsp三個jsp檔案,內容如下:
(1)login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login page</title>
</head>
<body>
<h3>登入</h3>
<span style="color:red"><s:actionerror/></span>
<form method="post" action="<%=path%>/loginAction.action">
<span>使用者名稱:</span><input type="text" name="username" value="${username}"/><br/>
<span>密碼 :</span><input type="text" name="password" value="${password}"/><br/>
<input type="submit" style="height:25px;width:237px" value="登入" />
</form>
<a href="<%=path%>/register.jsp">註冊頁面</a>
</body>
</html>
(2)register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
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>
<title>register page</title>
</head>
<body>
<h3>註冊</h3>
<s:actionmessage/>
<span style="color:red"><s:actionerror/></span>
<form method="post" action="<%=path%>/registerAction.action">
<span>使用者名稱:</span><input type="text" name="username" value="${username}"/><br/>
<span>密碼 :</span><input type="text" name="password" value="${password}"/><br/>
<input type="submit" style="height:25px;width:237px" value="註冊" />
</form>
<a href="<%=path%>/login.jsp">登入頁面</a>
</body>
</html>
(3)loginSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login success page</title>
</head>
<body>
<h1>登入成功!</h1>
<h3>當前登入使用者為:<s:property value="#session.user.username" /></h3>
</body>
</html>
整個工程的目錄結構:
四、部署測試
程式碼終於編寫完了,現在開始部署工程,測試功能有沒有實現吧!
部署工程後啟動tomcat伺服器,在瀏覽器的位址列輸入http://localhost:8080/ssh_example,回車就進入了下面的介面
然後點選註冊頁面先去註冊一個賬號吧
註冊成功後再進入登陸頁面,輸入剛才註冊的使用者名稱和密碼,點選登陸,如果出現下面的介面就表示大功告成了
注:如果要使密碼欄不可見,只需修改jsp中密碼的input標籤即可
<span>密碼 :</span><input type="password"
name="password" value="${password}" /><br/>
最後附上整個工程的程式碼連結: