---
title: "【转】struts2+spring3.0+hibernate注解方式"
author: "mib168"
date: "2014-01-28T15:02:07Z"
tags: []
categories: ["企业架构"]
slug: "struts2-spring3-0-hibernate"
draft: false
lastmod: "2014-01-28T15:02:07Z"
id: 2009597
url: "https://mib168.iteye.com/blog/2009597"
---

最近用这三个东西开发了一个后台管理的程序，现在写出来希望能够讨论谈论，因为我刚开始弄有很多东西都还不知道，在这里写出来望大家发现到问题后能够给我留言，以便完善，呵呵~

第一步：导入工程需要的包，具体需要哪些包，如果有需要的话我可以提供，当然最好的就是去官网下载了，呵呵~

第二步：配置web.xml文件。我的web.xml文件如下：

**\[java]** [view plain](http://blog.csdn.net/xiaojunhu/article/details/5500365 "view plain")[copy](http://blog.csdn.net/xiaojunhu/article/details/5500365 "copy")

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;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"&gt;
03. &lt;!-- 默认i18n资源文件 --&gt;
04. &lt;context-param&gt;
05. &lt;param-name&gt;javax.servlet.jsp.jstl.fmt.localizationContext&lt;/param-name&gt;
06. &lt;param-value&gt;i18n/messages&lt;/param-value&gt;
07. &lt;/context-param&gt;
08. &lt;!--
09. Location of the Log4J config file, for initialization and refresh checks.
10. Applied by Log4jConfigListener.
11. --&gt;
12. &lt;context-param&gt;
13. &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;
14. &lt;param-value&gt;/WEB-INF/classes/log4j.properties&lt;/param-value&gt;
15. &lt;/context-param&gt;
16. &lt;filter&gt;
17. &lt;filter-name&gt;struts2&lt;/filter-name&gt;
18. &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt;
19. &lt;init-param&gt;
20. &lt;param-name&gt;actionPackages&lt;/param-name&gt;
21. &lt;param-value&gt;com.cssweb.tradeadmin.action.trade&lt;/param-value&gt;
22. &lt;/init-param&gt;
23. &lt;/filter&gt;
24. &lt;filter-mapping&gt;
25. &lt;filter-name&gt;struts2&lt;/filter-name&gt;
26. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
27. &lt;/filter-mapping&gt;
28. &lt;!-- 著名 Character Encoding filter --&gt;
29. &lt;filter&gt;
30. &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
31. &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;
32. &lt;init-param&gt;
33. &lt;param-name&gt;encoding&lt;/param-name&gt;
34. &lt;param-value&gt;UTF-8&lt;/param-value&gt;
35. &lt;/init-param&gt;
36. &lt;/filter&gt;
37. &lt;listener&gt;
38. &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
39. &lt;/listener&gt;
40. &lt;context-param&gt;
41. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
42. &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt;
43. &lt;/context-param&gt;
44. &lt;!-- Spring 刷新Introspector防止内存泄露 --&gt;
45. &lt;listener&gt;
46. &lt;listener-class&gt;org.springframework.web.util.IntrospectorCleanupListener&lt;/listener-class&gt;
47. &lt;/listener&gt;
48. &lt;session-config&gt;
49. &lt;session-timeout&gt;30&lt;/session-timeout&gt;
50. &lt;/session-config&gt;
51. &lt;!-- Error Page定义 --&gt;
52. &lt;error-page&gt;
53. &lt;error-code&gt;500&lt;/error-code&gt;
54. &lt;location&gt;/commons/error.jsp&lt;/location&gt;
55. &lt;/error-page&gt;
56. &lt;error-page&gt;
57. &lt;error-code&gt;404&lt;/error-code&gt;
58. &lt;location&gt;/commons/404.jsp&lt;/location&gt;
59. &lt;/error-page&gt;
60. &lt;error-page&gt;
61. &lt;error-code&gt;403&lt;/error-code&gt;
62. &lt;location&gt;/commons/403.jsp&lt;/location&gt;
63. &lt;/error-page&gt;
64. &lt;welcome-file-list&gt;
65. &lt;!-- Redirects to "welcome.htm" for dispatcher handling --&gt;
66. &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
67. &lt;/welcome-file-list&gt;
68. &lt;/web-app&gt;

 

第三步：配置strust.xml文件（由于我用的是注解驱动方式，所以只有这一个文件）

**\[java]** [view plain](http://blog.csdn.net/xiaojunhu/article/details/5500365 "view plain")[copy](http://blog.csdn.net/xiaojunhu/article/details/5500365 "copy")

01. &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
02. &lt;!DOCTYPE struts PUBLIC
03. "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
04. "http://struts.apache.org/dtds/struts-2.1.dtd"&gt;
05. &lt;struts&gt;
06. &lt;constant name="struts.custom.i18n.resources" value="globalMessages" /&gt;
07. &lt;constant name="struts.convention.package.locators" value="action" /&gt;
08. &lt;constant name="struts.i18n.encoding" value="UTF-8" /&gt;
09. &lt;!-- when you used to real please set false --&gt;
10. &lt;constant name="struts.devMode" value="true" /&gt;
11. &lt;!-- 将struts2委托Spring管理 --&gt;
12. &lt;constant name="struts.objectFactory" value="spring" /&gt;
13. &lt;package name="mydefault" extends="struts-default"&gt;
14. &lt;global-results&gt;
15. &lt;!-- 下面定义的结果对所有的Action都有效 --&gt;
16. &lt;result name="exception"&gt;/commons/error.jsp&lt;/result&gt;
17. &lt;result name="login"&gt;/login/login.jsp&lt;/result&gt;
18. &lt;/global-results&gt;
19. &lt;global-exception-mappings&gt;
20. &lt;!-- 指Action抛出Exception异常时，转入名为exception的结果。 --&gt;
21. &lt;exception-mapping exception="java.lang.Exception" result="exception"/&gt;
22. &lt;/global-exception-mappings&gt;
23. &lt;/package&gt;
24. &lt;/struts&gt;

 

第四步：配置spring的xml文件包含hibernate的引入

**\[java]** [view plain](http://blog.csdn.net/xiaojunhu/article/details/5500365 "view plain")[copy](http://blog.csdn.net/xiaojunhu/article/details/5500365 "copy")

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03. xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
04. xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
05. xmlns:aop="http://www.springframework.org/schema/aop"
06. xsi:schemaLocation="
07. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
08. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
09. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
11. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&gt;
12. &lt;context:component-scan base-package="com.cssweb.tradeadmin.action"/&gt;
13. &lt;bean id="propertyConfigurer"
14. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
15. p:location="/WEB-INF/jdbc.properties" /&gt;
16. &lt;bean id="dataSource"
17. class="org.springframework.jdbc.datasource.DriverManagerDataSource"
18. p:driverClassName="${jdbc.driverClassName}"
19. p:url="${jdbc.url}"
20. p:username="${jdbc.username}"
21. p:password="${jdbc.password}" /&gt;
22. &lt;!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) --&gt;
23. &lt;!-- Hibernate SessionFactory --&gt;
24. &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
25. p:dataSource-ref="dataSource"&gt;
26. &lt;property name="hibernateProperties"&gt;
27. &lt;props&gt;
28. &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt;
29. &lt;prop key="hibernate.show\_sql"&gt;${hibernate.show\_sql}&lt;/prop&gt;
30. &lt;prop key="hibernate.generate\_statistics"&gt;${hibernate.generate\_statistics}&lt;/prop&gt;
31. &lt;/props&gt;
32. &lt;/property&gt;
33. &lt;property name="mappingResources"&gt;
34. &lt;list&gt;
35. &lt;value&gt;com/cssweb/tradeadmin/model/UserBasicInfo.hbm.xml&lt;/value&gt;
36. &lt;value&gt;com/cssweb/tradeadmin/model/LogLoginToday.hbm.xml&lt;/value&gt;
37. &lt;value&gt;com/cssweb/tradeadmin/model/CustHostInfo.hbm.xml&lt;/value&gt;
38. &lt;/list&gt;
39. &lt;/property&gt;
40. &lt;property name="eventListeners"&gt;
41. &lt;map&gt;
42. &lt;entry key="merge"&gt;
43. &lt;bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/&gt;
44. &lt;/entry&gt;
45. &lt;/map&gt;
46. &lt;/property&gt;
47. &lt;/bean&gt;
48. &lt;!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --&gt;
49. &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
50. p:sessionFactory-ref="sessionFactory"/&gt;
51. &lt;!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) --&gt;
52. &lt;!--
53. &lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/&gt;
54. --&gt;
55. &lt;!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= --&gt;
56. &lt;!--
57. Activates various annotations to be detected in bean classes:
58. Spring's @Required and @Autowired, as well as JSR 250's @Resource.
59. --&gt;
60. &lt;context:annotation-config/&gt;
61. &lt;!--
62. Instruct Spring to perform declarative transaction management
63. automatically on annotated classes.
64. --&gt;
65. &lt;tx:annotation-driven/&gt;
66. &lt;!--
67. Exporter that exposes the Hibernate statistics service via JMX. Autodetects the
68. service MBean, using its bean name as JMX object name.
69. --&gt;
70. &lt;context:mbean-export/&gt;
71. &lt;aop:aspectj-autoproxy/&gt;
72. &lt;!-- PetClinic's central data access object: Hibernate implementation --&gt;
73. &lt;bean id="clinic" class="com.cssweb.tradeadmin.dao.hibernate.HibernateClinic"/&gt;
74. &lt;/beans&gt;

 

第五步：在action包里面建action类：

**\[java]** [view plain](http://blog.csdn.net/xiaojunhu/article/details/5500365 "view plain")[copy](http://blog.csdn.net/xiaojunhu/article/details/5500365 "copy")

001. /\**
002. * Copyright 2010 CssWeb Microsystems, Inc. All rights reserved.
003. * CssWeb PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
004. \*
005. * @(#)LoginAction.java 1:58:01 PM Apr 15, 2010
006. \*/
007. package com.cssweb.tradeadmin.action;
008. import java.util.List;
009. import java.util.Map;
010. import javax.servlet.http.HttpServletRequest;
011. import org.apache.commons.logging.Log;
012. import org.apache.commons.logging.LogFactory;
013. import org.apache.struts2.ServletActionContext;
014. import org.apache.struts2.convention.annotation.Action;
015. import org.apache.struts2.convention.annotation.Namespace;
016. import org.apache.struts2.convention.annotation.ParentPackage;
017. import org.apache.struts2.convention.annotation.Result;
018. import org.springframework.beans.factory.annotation.Autowired;
019. import org.springframework.context.annotation.Scope;
020. import org.springframework.stereotype.Controller;
021. import com.cssweb.common.exception.BussinessException;
022. import com.cssweb.common.util.MD5;
023. import com.cssweb.tradeadmin.dao.Clinic;
024. import com.cssweb.tradeadmin.model.UserBasicInfo;
025. import com.opensymphony.xwork2.ActionContext;
026. import com.opensymphony.xwork2.ActionSupport;
027. /\**
028. * 交易系统后台登录
029. \*
030. * @author hujun
031. * @version 1.0
032. * @see
033. * @since 1.0
034. \*/
035. @Controller
036. @ParentPackage("mydefault")
037. @Namespace("/user")
038. @Scope("prototype")
039. public class LoginAction extends ActionSupport {
040. /\**
041. \*
042. \*/
043. private static final long serialVersionUID = 7454734463309586123L;
044. private Log log = LogFactory.getLog(LoginAction.class);
045. private final Clinic clinic;
046. private String loginName;
047. private String loginPwd;
048. private String incode;
049. @Autowired
050. public LoginAction(Clinic clinic) {
051. this.clinic = clinic;
052. }
053. @Action(value="login",
054. results={@Result(name="success", location="/index.jsp", type="redirect"),
055. @Result(name="input", location="/login/login.jsp")})
056. public String login() {
057. System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;" + loginName);
058. System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;" + loginPwd);
059. System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;" + incode);
060. String msg = "";
061. try {
062. Map session = ActionContext.getContext().getSession();
063. String vnum = (String)session.get("vnum");
064. if(vnum!=null&&!vnum.toLowerCase().equals(incode.toLowerCase())) {
065. msg="验证码不正确！";
066. }
067. else {
068. MD5 md5 = new MD5();
069. UserBasicInfo user = new UserBasicInfo();
070. user.setUserName(loginName);
071. user.setPassword(md5.getMD5ofStr(loginPwd));
072. List&lt;?&gt; list = this.clinic.queryList(user, 0, 1, null, false);
073. if(list!=null&&list.size()&gt;0) {
074. session.put("userName", loginName);
075. session.put("password", loginPwd);
076. }
077. else {
078. msg="用户和密码不正确！";
079. }
080. }
081. HttpServletRequest request = ServletActionContext.getRequest();
082. request.setAttribute("msg", msg);
083. } catch (BussinessException e) {
084. log.error(e);
085. }
086. System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;##########" + msg);
087. return msg.equals("") ? SUCCESS : "input";
088. }
089. public String getLoginName() {
090. return loginName;
091. }
092. public void setLoginName(String loginName) {
093. this.loginName = loginName;
094. }
095. public String getLoginPwd() {
096. return loginPwd;
097. }
098. public void setLoginPwd(String loginPwd) {
099. this.loginPwd = loginPwd;
100. }
101. public String getIncode() {
102. return incode;
103. }
104. public void setIncode(String incode) {
105. this.incode = incode;
106. }
107. }

 

 

第六步：hibernate类，在这里action中的Clinic是接口，hibernate类集成这个接口

**\[java]** [view plain](http://blog.csdn.net/xiaojunhu/article/details/5500365 "view plain")[copy](http://blog.csdn.net/xiaojunhu/article/details/5500365 "copy")

01. @Autowired
02. private SessionFactory sessionFactory;
03. /\**
04. * 保存（新建或者更新）
05. \*/
06. public void merge(Object obj) throws BussinessException {
07. try {
08. Session session = sessionFactory.openSession();
09. Transaction t=session.beginTransaction();
10. session.merge(obj);
11. t.commit();
12. }catch(RuntimeException e){
13. log.error(e);
14. throw new BussinessException(e);
15. }
16. }
17. /\**
18. * 保存（新建或者更新）
19. \*/
20. public void save(Object obj) throws BussinessException {
21. try {
22. Session session = sessionFactory.openSession();
23. Transaction t=session.beginTransaction();
24. session.save(obj);
25. t.commit();
26. }catch(RuntimeException e){
27. log.error(e);
28. throw new BussinessException(e);
29. }
30. }
31. /\**
32. * 保存（新建或者更新）
33. \*/
34. public void update(Object obj) throws BussinessException {
35. try {
36. Session session = sessionFactory.openSession();
37. Transaction t=session.beginTransaction();
38. session.update(obj);
39. t.commit();
40. }catch(RuntimeException e){
41. log.error(e);
42. throw new BussinessException(e);
43. }
44. }
45. /\**
46. * 保存（新建或者更新）
47. \*/
48. public void saveOrupdate(Object obj) throws BussinessException {
49. try {
50. Session session = sessionFactory.openSession();
51. Transaction t=session.beginTransaction();
52. session.saveOrUpdate(obj);
53. t.commit();
54. }catch(RuntimeException e){
55. log.error(e);
56. throw new BussinessException(e);
57. }
58. }

 

转自：[http://blog.csdn.net/xiaojunhu/article/details/5500365](http://blog.csdn.net/xiaojunhu/article/details/5500365)