爲了讓很多初學SSH框架的人會搭這個SSH框架我寫了一個“ 登錄的案例 ”以供初學者學習
好了長話短說了,這裏我準備先把框架的項目結構放出來然後把三個配置文件放出來 最後把每個項目源碼放出來 以供大家參考
這裏IDE 我用的 Eclipse 數據庫用的是 MySql數據庫 其實都不太影響 還有這些架包 我就不上傳CSDN了 需要架包的直接加我微信 13289899524 我會發給你 很方便的!
這是項目框架 大家看一下 !
首先我們建立各個包 com.java.action com.java.dao等等 這些包建好後 然後在依次向裏面添加代碼
第一步
在User.java裏面創建用戶類
com.java.entity 包下的 User.java
package com.java.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 本類爲項目的實體類
* @時間 2018-10-10
* @author Jiang
*
*/
@Entity
@Table(name="t_user")//這裏寫數據庫對應的表格
public class User {
private Integer id;//賬號id
private String userName;//登錄賬號
private String password;//登錄密碼
@Id
@GenericGenerator(name = "generator", strategy = "native") //功能代替 User.hbm.xml 配置文件
@GeneratedValue(generator = "generator") //功能代替 User.hbm.xml 配置文件
@Column(name = "id", length = 11) //功能代替 User.hbm.xml 配置文件 這樣註解的方式寫 就不用新建 User.hbm.xml
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "userName", length = 20)//註解的方式 功能代替 User.hbm.xml 配置文件
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "password", length = 20)//註解的方式 功能代替 User.hbm.xml 配置文件
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + "]";
}
}
後臺處理這塊其實還沒法寫呢 我們把這個寫了之後要先寫前臺頁面的 一個登陸頁面一個登陸成功後的頁面
這個是 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>
<form
action="${pageContext.request.contextPath }/user/user_login.action"
method="post">
賬號:<input type="text" name="user.userName" value="${user.userName }" /><br />
密碼:<input type="password" name="user.password"
value="${user.password }"><br /> <input type="submit"
value="login" /><font color="red">${error }</font>
</form>
</body>
</html>
這個是登陸成功後的頁面
<%@ 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>
歡迎:${currentUser.userName }
</body>
</html>
這倆個頁面其實要先寫 因爲後臺代碼都是爲這倆個頁面服務的 這倆個頁面寫好後 我們把 三個配置文件統一 一下一配置好了
不然一會寫代碼的時候其實也出不了錯 早晚要配 那就先配了吧 這個配置文件也是比較麻煩的 知識量特別大
先配置 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>
<!--數據庫連接設置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/db_test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!--方言-->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 顯示sql語句 -->
<property name="show_sql">true</property>
<!-- 自動更新 -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
這個 hibernate.cfg.xml 很簡單也很固定格式 方言的話對應自己的 數據庫 什麼數據庫 寫什麼方言 改一下就行了 我用的是Mysql數據庫 所以方言就是 上面的 然後就是jdbc 鏈接的時候 記得改一下 自己的 數據庫的用戶名和密碼
好啦 然後 配置 applicationContext.xml這是 配置Spring的配置文件 這個屬於Spring裏面的
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 定義數據源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/db_test">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- session工廠 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<!-- 自動掃描註解方式配置的hibernate類文件 -->
<property name="packagesToScan">
<list>
<value>com.java.entity</value>
</list>
</property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事務通知屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定義事務傳播屬性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置事務切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.java.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
<!-- 自動加載構建bean -->
<context:component-scan base-package="com.java" />
</beans>
這裏面用到了 知識點就是 AOP面向切面編程 我註釋寫的也很清楚了 專業名詞都在那裏寫的 有什麼實在不懂的 百度一下專業名字就全懂了 這個先配置 ,這裏提一點就是 配置數據源的時候 記得和自己的數據名字一樣 賬號密碼也要改一樣 不然就會出現 即不報錯只是登錄密碼怎麼輸都不會登錄上去的結果 其他的到沒啥好說的 貼上去就好了
第三個配置文件 struts2的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.action.extension" value="action" />
<package name="SSH" namespace="/user" extends="struts-default">
<action name="user_*" method="{1}" class="com.java.action.UserAction">
<result name="success">/success.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>
這裏面內容很少 ,一個是成功的後跳轉的頁面 一個是 失敗後跳轉的頁面 這也很簡單 大家一看也就 明白了
三個花了好多多天研究好的配置文件貼完了 基本上項目的一半也完成了 現在的話 就把業務代碼一個一個補齊
先寫 UserAction.java 因爲前臺數據來了 第一個到達的類就是這個類了
package com.java.action;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.stereotype.Controller;
import com.java.entity.User;
import com.java.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
/**
* struts2 處理請求類 將頁面提交的信息到次頁面
* 進行業務處理然後根據結果判斷執行該跳轉到的頁面
*
* @Controller:
* @Resource:
*/
@Controller
public class UserAction extends ActionSupport implements ServletRequestAware{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
@Resource
private UserService userService;
private User user;
private String error;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
*
* @return
* @throws Exception
*/
public String login() throws Exception{
HttpSession session=request.getSession();
User currentUser=userService.findUserByNameAndPassword(user);
// System.out.println(currentUser);
if(currentUser!=null){
session.setAttribute("currentUser", currentUser);
return SUCCESS;
}else{
error="用後名或者密碼錯誤!";
return ERROR;
}
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
}
然後在這裏aciton類裏面調用我們的service
我習慣寫service的時候 寫成接口的形式 所以 先把 UserService.java 接口寫好
package com.java.service;
import java.util.List;
import com.java.entity.User;
public interface UserService {
public void saveUser(User user);
public void updateUser(User user);
public User findUserById(int id);
public void deleteUser(User user);
public List<User> findAllList();
public User findUserByNameAndPassword(User user);
}
然後寫實現類 實現類在這個接口旁邊建一個impl包 在包裏面寫 UserServiceImpl.java實現的代碼
package com.java.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.java.dao.BaseDao;
import com.java.entity.User;
import com.java.service.UserService;
@Service("userService")//給service取個id userService
public class UserServiceImpl implements UserService{
@Resource//寫個Resource Spring會自動注入進來
private BaseDao<User> baseDao;//指定類型叫User 要和BaseDAPimpl中的 Resource裏面要一致
/**
* 保存一個對象
*
* @param o
* @return
*/
@Override
public void saveUser(User user) {
baseDao.save(user);
}
/**
* 更新一個對象
*
* @param o
*/
@Override
public void updateUser(User user) {
baseDao.update(user);
}
/**
* 獲得一個對象
*
* @param c
* 對象類型
* @param id
* @return Object
*/
@Override
public User findUserById(int id) {
return baseDao.get(User.class, id);
}
/**
* 刪除一個對象
*
* @param o
*/
@Override
public void deleteUser(User user) {
baseDao.delete(user);
}
@Override
public List<User> findAllList() {
return baseDao.find("from User");
}
@Override
public User findUserByNameAndPassword(User user) {
return baseDao.get("from User u where u.userName=? and u.password=?", new Object[]{user.getUserName(),user.getPassword()});
}
}
實現類其實還沒寫完 因爲實現類裏面 調用的方法都是 dao裏面的 方法 所以我們補齊 dao裏面的方法 按道理我們應該先寫dao裏面的代碼的 其實這裏的話 大家知道就行 大家寫的時候注意就好了
寫dao的時候也是先寫一個dao的接口然後開始實現他
package com.java.dao;
import java.io.Serializable;
import java.util.List;
/**
* 基礎數據庫操作類
*
* @author Jiang
*
*/
public interface BaseDao<T> {
/**
* 保存一個對象
*
* @param o
* @return
*/
public Serializable save(T o);
/**
* 刪除一個對象
*
* @param o
*/
public void delete(T o);
/**
* 更新一個對象
*
* @param o
*/
public void update(T o);
/**
* 保存或更新對象
*
* @param o
*/
public void saveOrUpdate(T o);
/**
* 查詢
*
* @param hql
* @return
*/
public List<T> find(String hql);
/**
* 查詢集合
*
* @param hql
* @param param
* @return
*/
public List<T> find(String hql, Object[] param);
/**
* 查詢集合
*
* @param hql
* @param param
* @return
*/
public List<T> find(String hql, List<Object> param);
/**
* 查詢集合(帶分頁)
*
* @param hql
* @param param
* @param page
* 查詢第幾頁
* @param rows
* 每頁顯示幾條記錄
* @return
*/
public List<T> find(String hql, Object[] param, Integer page, Integer rows);
/**
* 查詢集合(帶分頁)
*
* @param hql
* @param param
* @param page
* @param rows
* @return
*/
public List<T> find(String hql, List<Object> param, Integer page, Integer rows);
/**
* 獲得一個對象
*
* @param c
* 對象類型
* @param id
* @return Object
*/
public T get(Class<T> c, Serializable id);
/**
* 獲得一個對象
*
* @param hql
* @param param
* @return Object
*/
public T get(String hql, Object[] param);
/**
* 獲得一個對象
*
* @param hql
* @param param
* @return
*/
public T get(String hql, List<Object> param);
/**
* select count(*) from 類
*
* @param hql
* @return
*/
public Long count(String hql);
/**
* select count(*) from 類
*
* @param hql
* @param param
* @return
*/
public Long count(String hql, Object[] param);
/**
* select count(*) from 類
*
* @param hql
* @param param
* @return
*/
public Long count(String hql, List<Object> param);
/**
* 執行HQL語句
*
* @param hql
* @return 響應數目
*/
public Integer executeHql(String hql);
/**
* 執行HQL語句
*
* @param hql
* @param param
* @return 響應數目
*/
public Integer executeHql(String hql, Object[] param);
/**
* 執行HQL語句
*
* @param hql
* @param param
* @return
*/
public Integer executeHql(String hql, List<Object> param);
}
然後同樣在他旁邊建立一個 impl包 裏面寫 BaseDaoImpl.java
package com.java.dao.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.dao.BaseDao;
/**
* 實現類 整個DAO層只需要寫倆個就是 BaseDAO和 BaseDAOImpl
*
* Spring4出來之前不支持泛型注入 你有多少個模塊DAO接口你就得寫多少 接口100個實現就是100個這就很頭疼
*
* Repository這是一個註解 自動加載構造bean spring會自動掃描
*
* @author Jiang
*
* @param <T>
*
* @Repository("baseDao"):
* @SuppressWarnings("all"):
*
*
*/
@Repository("baseDao")
@SuppressWarnings("all")
public class BaseDaOImpl<T> implements BaseDao<T> {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Serializable save(T o) {
return this.getCurrentSession().save(o);
}
public void delete(T o) {
this.getCurrentSession().delete(o);
}
public void update(T o) {
this.getCurrentSession().update(o);
}
public void saveOrUpdate(T o) {
this.getCurrentSession().saveOrUpdate(o);
}
public List<T> find(String hql) {
return this.getCurrentSession().createQuery(hql).list();
}
public List<T> find(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.list();
}
public List<T> find(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.list();
}
public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
if (page == null || page < 1) {
page = 1;
}
if (rows == null || rows < 1) {
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {
if (page == null || page < 1) {
page = 1;
}
if (rows == null || rows < 1) {
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}
public T get(Class<T> c, Serializable id) {
return (T) this.getCurrentSession().get(c, id);
}
public T get(String hql, Object[] param) {
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0) {
return l.get(0);
} else {
return null;
}
}
public T get(String hql, List<Object> param) {
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0) {
return l.get(0);
} else {
return null;
}
}
public Long count(String hql) {
return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
}
public Long count(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return (Long) q.uniqueResult();
}
public Long count(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return (Long) q.uniqueResult();
}
public Integer executeHql(String hql) {
return this.getCurrentSession().createQuery(hql).executeUpdate();
}
public Integer executeHql(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.executeUpdate();
}
public Integer executeHql(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.executeUpdate();
}
}
最後不要忘記建我們的數據的 還有數據庫名字
數據庫名字就叫 db_test 這樣你也不用去該源碼裏面的數據名字了 然後表名叫 t_user 就好了
我們測試一下
還有比較寶貴的就是這些架包啦
需要架包的話直接加我微信13289890524 我直接就QQ發給你了 不需要就算了