SSH 環境搭建及註解實現登錄功能 DEMO
前言
最近通過網上的視頻學習了一下 SSH 三大框架的整合應用,熟悉一下流程,視頻其實三四天就可以看完了。比較基礎的內容,更多的是需要自己去嘗試,離開視頻後一步步去操作,去實踐。
環境
Eclipse 4.7.1
Windows 7
Spring 4.3.9 版本
Struts 2.5 版本
Hibernate 5.2.12 版本
C3P0 0.9.5.2 版本
MySQL 驅動 5.1.41
struts2-spring-plugin-2.5.13.jar
說明版本只是因爲,不同版本配置可能有所不同,自己配置的時候,因爲 jar 包都是從官網下載,所以版本都比較新。配置起來有所不同,同時有些使用的方法也可能被廢棄了。
配置
新建 web 項目
導入相關的 jar 包
配置文件的配置
編寫後臺代碼
前臺頁面
測試
新建 web 項目
打開 Eclipse,File —— New —— Dynamic Web project,輸入項目名稱,然後 Finally
導入相關的 jar 包
導入最基礎的 jar 包即可,缺包的再導入相關的 jar 包
Struts2 的官網有提供必須的最小 jar 包
Hibernate 則導入 required 文件夾下的 jar 包和 jpa 文件夾下的 jar 包
Spring 的 jar 包(需要導入 spring-orm-4.3.9.RELEASE.jar 與 Hibernate 整合)
mysql 驅動的 jar 包
導入 Struts2 與 Spring 整合的插件包 struts2-spring-plugin-2.5.13.jar
導入 c3p0-0.9.5.2.jar
我的導入如下:
配置文件的配置
web.xml 配置
在 /ssh_anno(項目名)/WebContent/WEB-INF 下創建一個 web.xml 文件。配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>ssh_anno</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/login.jsp</welcome-file>
</welcome-file-list>
<!-- 配置監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.xml 配置
在 src 下創建 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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/learnSSH?characterEncoding=UTF-8" />
<property name="user" value="root" />
<property name="password" value="123456" />
</bean>
<!-- 開啓註解掃描 -->
<context:component-scan base-package="test" />
<!-- SessionFactory 創建 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
<!-- 在覈心配置文件中沒有映射文件 -->
<property name="packagesToScan" value="test.entity"></property>
</bean>
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 開啓註解,使用哪個事務管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
修改 applicationContext.xml 配置中的數據庫名稱,賬號以及密碼,數據庫必須存在。Hibernate 可以配置自動創建對應的表,但是無法自動創建數據庫。
hibernate.cfg.xml 文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 輸出底層 SQL 語句 -->
<property name="hibernate.show_sql">true</property>
<!-- 輸出底層 SQL 語句格式 -->
<property name="hibernate.format_sql">true</property>
<!-- update:數據庫中如果已經有表,則更新;如果沒有,Hibernate 自動創建對應的表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置數據庫方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
</session-factory>
</hibernate-configuration>
struts.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="front" namespace="/" extends="struts-default">
<!-- 配置全局動態方法調用 -->
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="user_*" class="userAction" method="{1}">
<result name="loginSuccess">/WEB-INF/hello.jsp</result>
<result name="login">/WEB-INF/login.jsp</result>
</action>
</package>
</struts>
編寫後臺代碼
編寫實體類 User.java
在 src 下創建包 test.entity,然後創建 User.java 文件,代碼如下:
package test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int uid;
@Column
private String username;
@Column
private String password;
@Column
private String address;
public int getUid() {
return uid;
}
public void setUid(int 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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
UserAction.java 代碼編寫
在 src 下創建包 test.action,然後創建 UserAction.java 文件,代碼如下:
package test.action;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import test.entity.User;
import test.service.UserService;
@Controller("userAction")
@Scope(value="prototype")
public class UserAction extends ActionSupport {
@Resource(name="userService")
private 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 String login() {
User user = new User();
user.setUsername(username);
user.setPassword(password);
User userExist = userService.login(user);
if (null != userExist) {
HttpServletRequest request = ServletActionContext.getRequest();
request.getSession().setAttribute("user", userExist);
return "loginSuccess";
} else {
return "login";
}
}
}
UserService.java 代碼編寫
在 src 下創建包 test.service,然後創建 UserService.java 文件,代碼如下:
package test.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.dao.UserDao;
import test.entity.User;
@Service(value="userService")
@Transactional
public class UserService {
@Resource(name="userDao")
private UserDao userDao;
// 登錄驗證
public User login(User user) {
return userDao.login(user);
}
}
UserDao.java 和 UserDaoImpl.java 代碼編寫
在 src 下創建包 test.dao,然後創建 UserDao.java 和 UserDaoImpl.java 文件,代碼如下:
UserDao.java
package test.dao;
import test.entity.User;
public interface UserDao {
// 登錄驗證
User login(User user);
}
UserDaoImpl.java
package test.dao;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;
import test.entity.User;
@Component("userDao")
public class UserDaoImpl implements UserDao {
@Resource(name="hibernateTemplate")
private HibernateTemplate hibernateTemplate;
// 登錄
@SuppressWarnings("unchecked")
@Override
public User login(User user) {
List<User> list = (List<User>) hibernateTemplate.
find("from User where username=? and password=?", user.getUsername(),user.getPassword());
if (null != list && list.size() > 0) {
return list.get(0);
}
return null;
}
}
前臺頁面
在 /ssh_anno/WebContent/WEB-INF/ 下創建 login.jsp 和 hello.jsp 頁面
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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登錄頁面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user_login.action" method="post">
<br />
<br />
用戶名:<input type="text" id="username" name="username" /> <br />
密碼:<input type="password" id="password" name="password" /> <br />
<button type="submit">提交</button>
</form>
</body>
</html>
hello.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>Hello,SSH</title>
</head>
<body>
<h1>Hello,${user.username}</h1>
</body>
</html>
測試
在 MySQL 中創建數據庫,這裏數據庫名爲 learnSSH。與 applicationContext.xml 中的配置保持一致即可。
運行項目,則會自動在 learnSSH 數據庫中創建表 t_user
手動往裏面輸入一條記錄,例如用戶名爲 test,密碼爲 123
在 http://localhost:8080/ssh_anno/ 頁面,輸入剛纔的賬號密碼,點擊登錄,成功跳轉到 hello.jsp 頁面的內容。
OK,測試成功!
後記
到此,基本整合就結束了,剩下的就是往上面新增一些功能了。加入註解之後,整個開發變得更爲整潔了,也方便了許多。
關於 SSH 的瞭解,估計也就到此告一段落了,之後則去折騰其他的,如今更多的是使用 SSM 或者其他的。瞭解多一套框架,以此來擴展自己的知識面。在遇到新老項目對接的時候,不至於什麼都不懂,自己實踐後,留個小 DEMO 並做下筆記。需要用到時,翻看一下自己的筆記和 DEMO,也就很快就上手了。
在實踐中成長!
HochenChong
時間:2017-12-21