Struts2+Spring+Hibernate整合的例子
阿新 • • 發佈:2019-01-06
最近學習了Struts2,Spring,Hibernate的內容。並做了一個簡單的訊息傳送的例子,因為系統很小,所以也不好意思叫系統。雖然例子簡單,但SSH整合的基本內容都包含了。就記錄下來,方便以後查閱。
這個是系統的基本需求。
使用者能夠傳送訊息(多選使用者進行群發),檢視自己的收件箱(其實是看自己接收到的訊息),檢視發件箱(檢視傳送訊息記錄)。使用者進行分組,每個分組也可以包含多個子分組。例子中只把分組的實體建立了,並未實現與分組相關的功能。
1.系統開始前最關鍵的也是最難的就是概念模型的設計。
使用者與訊息之間有兩個關係,一個是傳送訊息,另一個是接收訊息。其中傳送訊息使用者與訊息之間傳送訊息關係是一對多,使用者與訊息之間的接收訊息關係多對多,在進行概念模型設計是我們一般將多對對關係拆分為兩個多對一。圖中的概念模型就是就是將多對對關聯拆分為兩個多對一關聯之後的結果。拆分後還可以在抽象出來的類中加入一些欄位,圖中的ReceiveMessage就是抽象出來的類,在這個類中又加入了一個receiveTime欄位。
使用者與分組之間的關係是多對一關聯,由於分組是一個樹形結構,每個分組有一個父節點,每個分組又有若干子節點,所以父分組與自分組之間是一對多關聯。
將概念模型建立之後我們就可以在Hibernate對映表中建立相應的關聯映射了。
2.根據概念模型建立各個實體類。
package com.lql.model; import java.util.Set; //使用者 public class ContactPerson { private int id; private String name; private String password; private Group group; private Set<Message> sendMsgs;//已傳送訊息 private Set<ReceiverMessage> receiveMsgs;//接收到的訊息 public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Message> getSendMsgs() { return sendMsgs; } public void setSendMsgs(Set<Message> sendMsgs) { this.sendMsgs = sendMsgs; } public Set<ReceiverMessage> getReceiveMsgs() { return receiveMsgs; } public void setReceiveMsgs(Set<ReceiverMessage> receiveMsgs) { this.receiveMsgs = receiveMsgs; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.lql.model; import java.util.HashSet; import java.util.Set; public class Group { private int id; private String name; private Group parent; private Set<Group> sons; private Set<ContactPerson> persons; public Set<Group> getSons() { return sons; } public void setSons(Set<Group> sons) { this.sons = sons; } public Group getParent() { return parent; } public void setParent(Group parent) { this.parent = parent; } public void addPerson(ContactPerson person) { if (persons == null) { persons = new HashSet<ContactPerson>(); } persons.add(person); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<ContactPerson> getPersons() { return persons; } public void setPersons(Set<ContactPerson> persons) { this.persons = persons; } }
package com.lql.model;
import java.util.Set;
public class Message {
private int id;
private String title;
private String content;
private ContactPerson sender;
private Set<ReceiverMessage> receivers;//訊息的接收者集合
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ContactPerson getSender() {
return sender;
}
public void setSender(ContactPerson sender) {
this.sender = sender;
}
public Set<ReceiverMessage> getReceivers() {
return receivers;
}
public void setReceivers(Set<ReceiverMessage> receivers) {
this.receivers = receivers;
}
}
package com.lql.model;
import java.util.Date;
public class ReceiverMessage {
private int id;
private ContactPerson receiver;
private Message msg;
private Date receiveTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ContactPerson getReceiver() {
return receiver;
}
public void setReceiver(ContactPerson receiver) {
this.receiver = receiver;
}
public Message getMsg() {
return msg;
}
public void setMsg(Message msg) {
this.msg = msg;
}
public Date getReceiveTime() {
return receiveTime;
}
public void setReceiveTime(Date receiveTime) {
this.receiveTime = receiveTime;
}
}
上述實體類是根據概念模型建立的。接下來就是Hibernate關聯對映表的建立。
3.關聯對映檔案的建立。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--ContactPerson 對映檔案 -->
<hibernate-mapping
package="com.lql.model">
<class name="ContactPerson" table="tb_person" lazy="true">
<comment>Users may bid for or sell auction items.</comment>
<id name="id">
<generator class="native"/>
</id>
<property name="name" unique="true" not-null="true"/>
<property name="password"></property>
<!-- 使用者與所屬分組是多對一 -->
<many-to-one name="group" column="groupId"></many-to-one>
<!-- lazy="extra"是懶載入方式,inverse="true"表示在一的一段維護關聯關係 -->
<set name="sendMsgs" lazy="extra" inverse="true">
<key column="senderId"></key>
<one-to-many class="com.lql.model.Message"/>
</set>
<set name="receiveMsgs" lazy="extra" inverse="true">
<key column="receiverId"></key>
<one-to-many class="com.lql.model.ReceiverMessage"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Group對映檔案 -->
<hibernate-mapping package="com.lql.model">
<class name="Group" table="tb_group">
<comment>Users may bid for or sell auction items.</comment>
<id name="id">
<generator class="native" />
</id>
<property name="name"></property>
<!--
多對一聯絡,集合名為Group中persons key是在多的那張表裡加一個欄位groupid 在雙向關聯的中如果在某一方的關聯配置中指定
inverse=”true” ,那麼本方就不能維護兩者之間的關聯關係。關聯關係就由對方一方來維護。Inverse
預設是false,雙方都可以維護關聯關係。維護關聯關係的意思是可以再本方的物件中儲存對方的引用。
extra:一種比較聰明的懶載入策略,即呼叫集合的size/contains等方法的時候,hibernate並不會去載入整個集合的資料,而是發出一條聰明的SQL語句,以便獲得需要的值,只有在真正需要用到這些集合元素物件資料的時候,才去發出查詢語句載入所有物件的資料
-->
<set name="persons" lazy="extra" inverse="true">
<key column="groupId"></key><!-- key表示在多的那張表裡加一個欄位指向本表 -->
<one-to-many class="com.lql.model.ContactPerson" />
</set>
<many-to-one name="parent" column="pid"></many-to-one>
<set name="sons" lazy="extra" inverse="true">
<key column="pid"></key>
<one-to-many class="com.lql.model.Group" />
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--Message 對映檔案 -->
<hibernate-mapping
package="com.lql.model">
<class name="Message" table="tb_message" lazy="true">
<comment>Users may bid for or sell auction items.</comment>
<id name="id">
<generator class="native"/>
</id>
<property name="title"></property>
<property name="content"></property>
<many-to-one name="sender" column="senderId"></many-to-one>
<set name="receivers" lazy="extra" inverse="true">
<key column="msgId"/>
<one-to-many class="com.lql.model.ReceiverMessage"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--ReceiverMessage 對映檔案 -->
<hibernate-mapping package="com.lql.model">
<class name="ReceiverMessage" table="tb_receivermsg" lazy="true">
<comment>Users may bid for or sell auction items.</comment>
<id name="id">
<generator class="native" />
</id>
<many-to-one name="receiver" column="receiverId"></many-to-one>
<many-to-one name="msg" column="msgId"></many-to-one>
<property name="receiveTime"></property>
</class>
</hibernate-mapping>
對映檔案建立完畢。將Spring配置檔案貼出,Spring配置檔案中包括資料來源的配置,Spring事務管理配置,以及Hibernate對映檔案的配置。
4.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: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/tx
http://www.springframework.org/schema/tx/spring-tx.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">
<!-- 允許使用註解進行注入 -->
<context:annotation-config />
<!-- 允許Spring掃描類路徑的類,將符合條件的的類,注入Spring中 -->
<context:component-scan base-package="com.lql.*" />
<!-- Spring配置檔案中配置資料來源 -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/ssh_msg" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- 配置資料來源後配置SessionFactory property配置hibernate配置檔案中的一些配置項-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
</value>
</property>
<!-- Hibernate對映檔案 -->
<property name="mappingResources">
<list>
<value>com/lql/model/ContactPerson.hbm.xml</value>
<value>com/lql/model/Group.hbm.xml</value>
<value>com/lql/model/Message.hbm.xml</value>
<value>com/lql/model/ReceiverMessage.hbm.xml</value>
</list>
</property>
</bean>
<!--
配置Hibernate事務管理器 Spring整合Hibernate時,通常將Hibernate中的事務管理交給Spring來統一進行。
Dao只需進行自己的CRUD操作,不必關心事務管理的問題。
-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置哪些方法的呼叫需要增加事務管理器 -->
<aop:config>
<aop:pointcut id="allServiceMethods" expression="execution(* com.lql.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServiceMethods" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 對於增加,刪除,修改的方法,都需要事務管理 -->
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="send*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="is*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- <bean id="personDao" class="com.lql.dao.imp.PersonDaoImp">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="messageDao" class="com.lql.dao.imp.MessageDaoImp">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="personService" class="com.lql.service.imp.PersonServiceImp">
<property name="personDao" ref="personDao"></property>
</bean>
<bean id="messageService" class="com.lql.service.imp.MessageServiceImp">
<property name="messageDao" ref="messageDao"></property>
<property name="personDao" ref="personDao"></property>
</bean>-->
</beans>
資料庫採用的是Mysql,在mysql資料庫下建一個名為ssh_msg的資料庫。表不用自己建,只要我們正確配置了Hibernate對映表和Spring配置檔案,表就能給我們正確建立出來。
5.定義Dao和Service介面。
package com.lql.dao;
import java.util.List;
import com.lql.model.Message;
import com.lql.model.ReceiverMessage;
public interface MessageDao {
/**
* 儲存一條訊息
*/
public void saveMessage(Message message);
/**
* 儲存一條ReceiverMessage
* @param receiverMessage
*/
public void saveReceiveMessage(ReceiverMessage receiverMessage);
/**
* 根據使用者名稱查詢使用者收到的訊息
* @param id
* @return
*/
public List<Message> queryReceiveMsgs(int id);
/**
* 獲取該使用者傳送的訊息列表
* @param id
* @return
*/
public List<Message> querySendMsgs(int id);
}
package com.lql.dao;
import java.util.List;
import com.lql.model.ContactPerson;
import com.lql.model.Message;
public interface PersonDao {
/**
* 儲存一個Person
* @param person
*/
public void save(ContactPerson person);
/**
* 根據名字查詢Person
* @param name
* @return
*/
public ContactPerson queryPersonByName(String name);
/**
* 根據使用者ID獲取不包含不包含該使用者的使用者列表
* @param name
* @return
*/
public List<ContactPerson> queryPersonsExceptId(int id);
/**
* 根據ID查使用者
* @param id
* @return
*/
public ContactPerson queryPersonById(int id);
}
package com.lql.service;
import java.util.List;
import com.lql.model.Message;
public interface MessageService {
/**
*
* @param title:訊息標題
* @param content:訊息內容
* @param receiveIds:接收訊息人ID列表
* @param senderId:訊息傳送者的ID
*/
public boolean sendMessage(String title,String content,List<Integer> receiveIds,int senderId);
/**
* 獲取使用者收件箱的訊息
* @param id
*/
public List<Message> getReceiveMsgsById(int userId);
/**
* 獲取使用者發件箱訊息
*/
public List<Message> getSendMsgsById(int userId);
}
package com.lql.service;
import java.util.List;
import com.lql.model.ContactPerson;
import com.lql.model.Message;
public interface PersonService {
/**
* 根據使用者名稱和密碼判斷使用者能否登陸
* @param name
* @param pwd
* @return true:表示允許此使用者登陸
* false:不允許此使用者登陸
*/
public boolean isLogin(String name ,String pwd);
/**
* 取出除了當前登陸使用者之外的全部使用者
* @param id
* @return
*/
public List<ContactPerson> getAllPersonsExceptId(int id);
/**
* 增加一個使用者
* @param person
* @return
*/
public boolean addPerson(ContactPerson person);
/**
*
* @param id
* @return
*/
public ContactPerson getPersonById(int id);
}
介面是一種規範,在編碼之前我們應該先理一理請求的過程,把需要的介面先抽象出來,然後把所需介面定義出來,按照介面規範將所需的介面實現出來。
5.介面實現。
package com.lql.dao.imp;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.lql.dao.MessageDao;
import com.lql.model.Message;
import com.lql.model.ReceiverMessage;
@Repository("messageDao")//註解注入
public class MessageDaoImp implements MessageDao{
@Resource
private SessionFactory sessionFactory;//註解注入
public List<Message> queryReceiveMsgs(int id) {
// TODO Auto-generated method stub
/**
* 連線查詢,查詢使用者接收的訊息集合,tb_receive表中儲存著使用者id與接收訊息id之間的對映關係,
* 想要查詢根據使用者id查詢該使用者接收的訊息,應將三張表聯合起來查詢
*/
Session session = getSession();
String hql = "select m from ReceiverMessage rm join rm.receiver r join rm.msg m where r.id = ?";
Query query = session.createQuery(hql);
query.setParameter(0, id);
List<Message> receiverMsgs = query.list();
return receiverMsgs;
}
public List<Message> querySendMsgs(int id) {
// TODO Auto-generated method stub
Session session = getSession();
// String hql = "select m from Message m where m.sender.id = ?";//不使用連線
String hql = "select m from Message m join m.sender s where s.id = ?";//使用連線
Query query = session.createQuery(hql);
query.setParameter(0, id);
List<Message> sendMsgs = query.list();
return sendMsgs;
}
public void saveMessage(Message message) {
// TODO Auto-generated method stub
getSession().save(message);
}
public void saveReceiveMessage(ReceiverMessage receiverMessage) {
// TODO Auto-generated method stub
getSession().save(receiverMessage);
}
private Session getSession(){
return sessionFactory.getCurrentSession();
}
}
package com.lql.dao.imp;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.lql.dao.PersonDao;
import com.lql.model.ContactPerson;
@Repository("personDao")
public class PersonDaoImp implements PersonDao {
@Resource
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
public ContactPerson queryPersonById(int id) {
// TODO Auto-generated method stub
Session session = getSession();
String hql = "select cp from ContactPerson cp where cp.id = ?";
Query query = session.createQuery(hql);
query.setParameter(0, id);
ContactPerson person =(ContactPerson) query.uniqueResult();
return person;
}
public ContactPerson queryPersonByName(String name) {
// TODO Auto-generated method stub
Session session = getSession();
String hql = "select cp from ContactPerson cp where cp.name = ?";
Query query = session.createQuery(hql);
query.setParameter(0, name);
ContactPerson person =(ContactPerson) query.uniqueResult();
return person;
}
public List<ContactPerson> queryPersonsExceptId(int id) {
// TODO Auto-generated method stub
Session session = getSession();
String hql = "select cp from ContactPerson cp where cp.id not in ("+id+")";
Query query = session.createQuery(hql);
List<ContactPerson> persons = query.list();
return persons;
}
public void save(ContactPerson person) {
// TODO Auto-generated method stub
getSession().save(person);
}
}
package com.lql.service.imp;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.lql.dao.MessageDao;
import com.lql.dao.PersonDao;
import com.lql.model.ContactPerson;
import com.lql.model.Message;
import com.lql.model.ReceiverMessage;
import com.lql.service.MessageService;
@Service("messageService")
public class MessageServiceImp implements MessageService {
@Resource
private MessageDao messageDao;
@Resource
private PersonDao personDao;
public void setMessageDao(MessageDao messageDao) {
this.messageDao = messageDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public List<Message> getReceiveMsgsById(int userId) {
// TODO Auto-generated method stub
List<Message> receiveMsgs = messageDao.queryReceiveMsgs(userId);
return receiveMsgs;
}
public List<Message> getSendMsgsById(int userId) {
// TODO Auto-generated method stub
List<Message> sendMsgs = messageDao.querySendMsgs(userId);
return sendMsgs;
}
public boolean sendMessage(String title, String content,
List<Integer> receiveIds, int senderId) {
ContactPerson sender = personDao.queryPersonById(senderId);
if (sender == null) {
return false;
}
Message message = new Message();
message.setTitle(title);
message.setContent(content);
message.setSender(sender);
messageDao.saveMessage(message);
for (Integer receiverId : receiveIds) {
ReceiverMessage receiverMessage = new ReceiverMessage();
receiverMessage.setMsg(message);
receiverMessage.setReceiver(personDao.queryPersonById(receiverId));
receiverMessage.setReceiveTime(new Date());
messageDao.saveReceiveMessage(receiverMessage);
}
return true;
}
}
package com.lql.service.imp;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import com.lql.dao.PersonDao;
import com.lql.model.ContactPerson;
import com.lql.service.PersonService;
import com.opensymphony.xwork2.ActionContext;
@Service("personService")
public class PersonServiceImp implements PersonService {
@Resource
private PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public List<ContactPerson> getAllPersonsExceptId(int id) {
// TODO Auto-generated method stub
List<ContactPerson> persons = personDao.queryPersonsExceptId(id);
return persons;
}
public boolean isLogin(String name, String pwd) {
// TODO Auto-generated method stub
ContactPerson person = personDao.queryPersonByName(name);
if (person == null) {
return false;
} else if (!person.getPassword().equals(pwd)) {
return false;
}
ActionContext.getContext().getSession().put("user", person);
return true;
}
public boolean addPerson(ContactPerson person) {
// TODO Auto-generated method stub
personDao.save(person);
return true;
}
public ContactPerson getPersonById(int id) {
// TODO Auto-generated method stub
ContactPerson person = personDao.queryPersonById(id);
return person;
}
}
以上是與呈現層無關的Spring+hibernate的實現過程。下面就是Sturts2部分。
6.struts.xml配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.action.extension" value="action,do"></constant>
<constant name="struts.configuration.xml.reload" value="true"></constant>
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
<package name="login" namespace="/login" extends="struts-default">
<action name="isLogin" class="loginAction">
<result name="suceess">/main.jsp</result>
<result name="fail">/index.jsp</result>
</action>
</package>
<package name="message" namespace="/message" extends="struts-default">
<action name="msg_receive" method="scanReceiveMsgs" class="messageAction">
<result name="receive_msgs">/receive_msgs.jsp</result>
</action>
<action name="msg_sended" method="scanSendedMsgs" class="messageAction">
<result name="sended_msgs">/sended_msgs.jsp</result>
</action>
<action name="msg_go_send" method="goSendMsgs" class="messageAction">
<result name="go_send_msg">/send_msg.jsp</result>
</action>
<action name="msg_send" method="sendMsg" class="messageAction">
<result name="success">/send_msg.jsp</result>
<result name="fail">/send_msg.jsp</result>
</action>
</package>
</struts>
在訪問某個action下的方法時,可以這樣提交引數:包名/action名.action,比如message/msg_sended.action,就表示將請求交由messageAction來處理。
web.xml配置檔案,配置struts2.xml請求分發過濾器,以及Spring的監聽器。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--ContextLoaderListener會在應用伺服器啟動的時候自動初始化
在這個Listener初始化的時候,他會讀取contextConfigLocation的值
並根據它建立BeanFactory物件,並把這個物件放入ServletContext中
beanFactory被建立後會,Spring會自動例項化在beans.xml中註冊的所有類
當然也包括註冊的SessionFactory,例項化SessionFactory的時候
資料庫表也會被自動建立
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 在Service方法執行後,Session會自動關閉,如果我們使用懶載入時,有時會出現懶載入異常
這時我們可以在web.xml中加上這個過濾器,就會將這種情況避免
在沒有加這個OpenSessionInViewFilter時,session是在Service方法執行前進行建立,
並在service方法執行後關閉,如果加上這個filter,在經過這個filter後就是建立session,
直到將檢視呈現到瀏覽器前才關閉該session-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- struts2過濾器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
7.Strut2的Action
package com.lql.action;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.lql.service.PersonService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
@Controller("loginAction")
@Scope("prototype")
public class LoginAction {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Resource
private PersonService personService;
public String execute(){
if(!personService.isLogin(name, password)){
ActionContext.getContext().put("message", "使用者名稱或密碼有誤");
return "fail";
}
return "suceess";
}
}
package com.lql.action;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.lql.model.ContactPerson;
import com.lql.model.Message;
import com.lql.service.MessageService;
import com.lql.service.PersonService;
import com.opensymphony.xwork2.ActionContext;
@Controller("messageAction")
@Scope("prototype")
public class MessageAction {
private String title;
private String content;
@Resource
private PersonService personService;
@Resource
private MessageService messageService;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String scanReceiveMsgs() {
ContactPerson loginUser = getLoginUser();
System.out.println(loginUser.getName());
List<Message> receiveMsgs = messageService.getReceiveMsgsById(loginUser.getId());
ActionContext.getContext().put("receiveMsgs", receiveMsgs);
return "receive_msgs";
}
public String scanSendedMsgs() {
ContactPerson loginUser = getLoginUser();
List<Message> sendedMsgss = messageService.getSendMsgsById(loginUser.getId());
ActionContext.getContext().put("sendedMsgss", sendedMsgss);
return "sended_msgs";
}
public String goSendMsgs() {
ContactPerson loginUser = getLoginUser();
List<ContactPerson> users = personService.getAllPersonsExceptId(loginUser.getId());
ActionContext.getContext().put("users", users);
return "go_send_msg";
}
public String sendMsg() {
String[] ids = ServletActionContext.getRequest().getParameterValues("receiver_id");
List<Integer> receiver_ids = new ArrayList<Integer>();
for(String id:ids){
System.out.println(id);
receiver_ids.add(Integer.parseInt(id));
}
ContactPerson loginUser = getLoginUser();
messageService.sendMessage(title, content, receiver_ids, loginUser.getId());
List<ContactPerson> users = personService.getAllPersonsExceptId(loginUser.getId());
ActionContext.getContext().put("users", users);
ActionContext.getContext().put("message", "傳送成功");
return "success";
}
private ContactPerson getLoginUser(){
ContactPerson loginUser = (ContactPerson) ActionContext.getContext()
.getSession().get("user");
return loginUser;
}
}
基本上差不多了,還有Jsp頁面不貼出了,將專案連線貼出,需要的可以參考一下。點選開啟連結