1. 程式人生 > >MyEclipse10+Struts2.1+Spring3.3+Hibernate3.3全註解框架搭建.docx

MyEclipse10+Struts2.1+Spring3.3+Hibernate3.3全註解框架搭建.docx

一、新建web專案

1.        File-->New-->web project


2.        工程名稱:king-back-->點選Java EE 6.0標準

 

二、新增ssh2支援

1.        新增struts2

工程上點右鍵-->myeclipse-->add struts capabilites

點選struts2.1-->url模式點選 /*


新增struts2 core lib和struts2 spring lib


新建LoginAction類                

packagecom.frank.action;

importcom.opensymphony.xwork2.ActionSupport;

/**

 * @author steve frank

 *

 */

publicclass LoginAction extends ActionSupport {

         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(Stringpassword) {

                   this.password = password;

         }

         public String execute() {

                   if (name.equals("steve")&& password.equals("123"))

                            return SUCCESS;

                   else

                            return INPUT;

         }

}

修改struts.xml

<?xmlversion="1.0" encoding="UTF-8" ?>

<!DOCTYPEstruts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

         <package name="default"namespace="/" extends="struts-default">

                   <actionname="login" class="com.frank.action.LoginAction">

                            <resultname="success">/success.jsp</result>

                            <resultname="input">/fail.jsp</result>

                   </action>

         </package>

</struts>  

修改index.jsp

<%@page language="java" import="java.util.*"pageEncoding="UTF-8"%>

<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>MyJSP 'index.jsp' starting page</title>

</head>

<body>

         <s:form action="login">

                   <s:textfieldname="name" value="steve"></s:textfield>

                   <s:textfieldname="password" value="123"></s:textfield>

                   <s:submit></s:submit>

         </s:form>

</body>

</html>

新增success.jsp

<%@page language="java" import="java.util.*"pageEncoding="UTF-8"%>

<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>MyJSP 'success.jsp' starting page</title>

</head>

<body>

         <s:text name="password"/>

         <hr />

         <s:propertyvalue="password" />

         <hr />

         ${password}

         <hr />

</body>

</html>

新增fail.jsp

<%@page language="java" import="java.util.*"pageEncoding="UTF-8"%>

<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>MyJSP 'fail.jsp' starting page</title>

</head>

<body>登入失敗,使用者名稱或密碼錯誤.

</body>

</html>

當前web.xml如下,直接啟動會報spring監聽錯誤,因為剛才已經添加了spring支援struts的lib包。

                           

新增spring監聽,重新啟動會提示找不到spring配置檔案。



2.        新增spring

右鍵-->myeclipse-->add spring capabilities


勾選spring 3.0 aop lib,spring 3.0 core lib,spring 3.0 persistence corelib,spring 3.0 persistence jdbc lib,spring 3.0 web lib;

點選copy checked library contents to project folder


當前web.xml如下,重新啟動tomcat,成功。



直接點選submit,成功跳轉到success.jsp,介面如下。


如果修改使用者名稱為frank,如下


點選submit後跳轉到fail.jsp如下


3.        新增hibernate

先配置好資料來源驅動,如下


右鍵-->myeclipse-->add hibernate capabilities


點選hibernate 3.3,勾選enable hibernate annotations support;

勾選hibernate 3.3 annotations&entity manager,hibernate 3.3 core lib;

點選copy checked library jars to project folder and add to build-path


點選spring configuration file,交給spring配置資料來源


勾選existing spring configuration file


選擇配置好的資料來源驅動


去掉create seesionfactory class的勾。然後點選完成。


三、資料反向生成

1.        新建資料夾com.frank.model,準備放置生成的實體類和dao類

2.        在專案中新建data.sql檔案,內容如下,連線mysql的test庫,新建表student

DROPTABLE IF EXISTS `student`;

CREATETABLE `student` (

  `id` int(11) NOT NULL,

  `name` varchar(20) default NULL,

  `role_id` int(11) default NULL,

  PRIMARY KEY (`id`)

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

------------------------------

--Records of student

-- ----------------------------

INSERTINTO `student` VALUES ('1', '張三', '1');

INSERTINTO `student` VALUES ('2', '李四', '2');

INSERTINTO `student` VALUES ('3', '王五', '1');

SELECT * FROM student;

3.        生成Dao和實體類過程如下

開啟Test庫,選擇student表,右鍵hibernate reverse engineering


出現如下檢視,通過browse選擇king-back專案和com.frank.model資料夾

結果如下,

勾選create pojo<> db table mapping informationà點選addhibernate mapping annotations to pojoà保留update hibernate configurationwith mapping resource location;

去掉create abstract class勾;

勾選java data access object(dao) à勾選generate precisefindby methodsà點選spring dao

Id generator 選擇native

結果如下

四、編寫測試

1.        新建test類

packagetest;

importjava.util.List;

importorg.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

importcom.frank.model.Student;

importcom.frank.model.StudentDAO;

publicclass Test {

         public static void main(String[] args){

                   ApplicationContext context =new ClassPathXmlApplicationContext(

                                     "applicationContext.xml");

                   StudentDAO dao = (StudentDAO)context.getBean("StudentDAO");

                   List<Student> list =dao.findAll();

                   int n = list.size();

                   for (int i = 0; i < n;i++) {

                            Student c =list.get(i);

                            String name =c.getName();

                            System.out.println(name);

                   }

         }

}

執行結果如下,說明專案基本上是ok的。

2.        修改action類

publicString execute() {

                   getData();

                   if(name.equals("steve") && password.equals("123"))

                            return SUCCESS;

                   else

                            return INPUT;

         }

         private void getData() {

                   ApplicationContext context =new ClassPathXmlApplicationContext(

                                     "applicationContext.xml");

                   StudentDAO dao = (StudentDAO)context.getBean("StudentDAO");

                   List<Student> list =dao.findAll();

                   int n = list.size();

                   for (int i = 0; i < n;i++) {

                            Student c =list.get(i);

                            String name =c.getName();

                            System.out.println(name);

                   }

         }

重新整理瀏覽器,檢視控制檯列印結果。

五、添加註解配置

1.        修改struts.xml

<?xmlversion="1.0" encoding="UTF-8" ?>

<!DOCTYPEstruts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

         <!-- 開啟使用開發模式,詳細錯誤提示-->

         <constantname="struts.devMode" value="true" />

         <!-- 將物件交給spring管理 -->

         <constantname="struts.objectFactory" value="spring" />

         <!-- 指定資源編碼型別 -->

         <constant name="struts.i18n.encoding"value="UTF-8" />

         <!-- 指定每次請求到達,重新載入資原始檔-->

         <constantname="struts.i18n.reload" value="true" />

         <!-- 指定每次配置檔案更改後,自動重新載入-->

         <constantname="struts.configuration.xml.reload" value="false" />

         <!-- 國際化資原始檔 -->

         <constant name="struts.custom.i18n.resources"value="content/Language" />

         <!-- 瀏覽器快取 -->

         <constantname="struts.serve.static.browserCache" value="false" />

         <!-- 預設字尾名 -->

         <constantname="struts.action.extension" value="do,action,jhtml,,"/>

         <!-- Struts Annotation -->

         <constantname="actionPackages" value="com.frank.action" />

</struts>

2.        修改LoginAction,在execute方法上新增

@Action(value= "login", results = {

                            @Result(name =INPUT, location = "/index.jsp"),

                            @Result(name= SUCCESS, location = "/WEB-INF/content/success.jsp") })

3.        action註解完成,可以測試通過,接下來新增service註解等

4.        修改applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="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"

         xsi:schemaLocation="http://www.springframework.org/schema/beans

          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

          http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource">

                   <propertyname="driverClassName" value="com.mysql.jdbc.Driver">

                   </property>

                   <propertyname="url"value="jdbc:mysql://localhost:3306/test"></property>

                   <propertyname="username" value="root"></property>

                   <propertyname="password" value="admin"></property>

         </bean>

         <bean id="sessionFactory"

                   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

                   <propertyname="dataSource">

                            <refbean="dataSource" />

                   </property>

                   <propertyname="hibernateProperties">

                            <props>

                                     <propkey="hibernate.dialect">

                                               org.hibernate.dialect.MySQLDialect

                                     </prop>

                            </props>

                   </property>

                   <propertyname="annotatedClasses">

                            <list>

                                     <value>com.frank.model.Student</value>

                            </list>

                   </property>

         </bean>

         <!-- 使用 annotation 自動註冊bean,並檢查@Controller,@Service, @Repository註解已被注入 -->

         <context:component-scanbase-package="com.frank" />

</beans>

5.        Service、dao 的介面和實現類

StudentService.java

public interfaceStudentService {

         /**

          * 根據主鍵查詢Student

          * @param id

          * @return

          */

         public Student findById(Integer id);

}

StudentServiceImpl.java

@Service

public classStudentServiceImpl implements StudentService {

         @Resource

         private StudentDAO studentDAO;

         @Override

         public Student findById(Integer id) {

                   // TODO Auto-generated methodstub

                   returnstudentDAO.findById(id);

         }

}

StudentDAO.java

public interfaceStudentDAO{

         public abstract void save(StudenttransientInstance);

         public abstract void delete(StudentpersistentInstance);

         public abstract StudentfindById(java.lang.Integer id);

         public abstract List<Student>findByExample(Student instance);

         public abstract ListfindByProperty(String propertyName, Object value);

         public abstract List<Student>findByName(Object name);

         public abstract List findAll();

         public abstract Student merge(StudentdetachedInstance);

         public abstract voidattachDirty(Student instance);

         public abstract voidattachClean(Student instance);

}

StudentDAOImpl.java

@Repository

public classStudentDAOImpl extends HibernateDaoSupport implements StudentDAO {

         private static final Logger log =LoggerFactory

                            .getLogger(StudentDAOImpl.class);

         // property constants

         public static final String NAME ="name";

         private SessionFactory sessionFacotry;

         @Resource

         public voidsetSessionFacotry(SessionFactory sessionFacotry) {

                   super.setSessionFactory(sessionFacotry);

         }

         protected void initDao() {

                   // do nothing

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#save(com.frank.model.Student)

          */

         @Override

         public void save(StudenttransientInstance) {

                   log.debug("savingStudent instance");

                   try {

                            getHibernateTemplate().save(transientInstance);

                            log.debug("savesuccessful");

                   } catch (RuntimeException re){

                            log.error("savefailed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#delete(com.frank.model.Student)

          */

         @Override

         public void delete(StudentpersistentInstance) {

                   log.debug("deletingStudent instance");

                   try {

                            getHibernateTemplate().delete(persistentInstance);

                            log.debug("deletesuccessful");

                   } catch (RuntimeException re){

                            log.error("deletefailed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#findById(java.lang.Integer)

          */

         @Override

         public StudentfindById(java.lang.Integer id) {

                   log.debug("gettingStudent instance with id: " + id);

                   try {

                            Student instance =(Student) getHibernateTemplate().get(

                                               "com.frank.model.Student",id);

                            return instance;

                   } catch (RuntimeException re){

                            log.error("getfailed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#findByExample(com.frank.model.Student)

          */

         @Override

         public List<Student>findByExample(Student instance) {

                   log.debug("findingStudent instance by example");

                   try {

                            List<Student>results = (List<Student>) getHibernateTemplate()

                                               .findByExample(instance);

                            log.debug("findby example successful, result size: "

                                               +results.size());

                            return results;

                   } catch (RuntimeException re){

                            log.error("findby example failed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#findByProperty(java.lang.String,

          * java.lang.Object)

          */

         @Override

         public List findByProperty(StringpropertyName, Object value) {

                   log.debug("findingStudent instance with property: " + propertyName

                                     + ",value: " + value);

                   try {

                            String queryString ="from Student as model where model."

                                               +propertyName + "= ?";

                            returngetHibernateTemplate().find(queryString, value);

                   } catch (RuntimeException re){

                            log.error("findby property name failed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#findByName(java.lang.Object)

          */

         @Override

         public List<Student>findByName(Object name) {

                   return findByProperty(NAME,name);

         }

         /*

          * (non-Javadoc)

          *

          * @see com.frank.dao.impl.S#findAll()

          */

         @Override

         public List findAll() {

                   log.debug("finding allStudent instances");

                   try {

                            String queryString ="from Student";

                            returngetHibernateTemplate().find(queryString);

                   } catch (RuntimeException re){

                            log.error("findall failed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#merge(com.frank.model.Student)

          */

         @Override

         public Student merge(StudentdetachedInstance) {

                   log.debug("mergingStudent instance");

                   try {

                            Student result =(Student) getHibernateTemplate().merge(

                                               detachedInstance);

                            log.debug("mergesuccessful");

                            return result;

                   } catch (RuntimeException re){

                            log.error("mergefailed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#attachDirty(com.frank.model.Student)

          */

         @Override

         public void attachDirty(Studentinstance) {

                   log.debug("attachingdirty Student instance");

                   try {

                            getHibernateTemplate().saveOrUpdate(instance);

                            log.debug("attachsuccessful");

                   } catch (RuntimeException re){

                            log.error("attachfailed", re);

                            throw re;

                   }

         }

         /*

          * (non-Javadoc)

          *

          * @seecom.frank.dao.impl.S#attachClean(com.frank.model.Student)

          */

         @Override

         public void attachClean(Studentinstance) {

                   log.debug("attachingclean Student instance");

                   try {

                            getHibernateTemplate().lock(instance,LockMode.NONE);

                            log.debug("attachsuccessful");

                   } catch (RuntimeException re){

                            log.error("attachfailed", re);

                            throw re;

                   }

         }

六、附加功能完善

1.        新增log日誌輸出

log4j.rootLogger=WARN,console, logFile

#Console

log4j.appender.console=org.apache.log4j.ConsoleAppender

log4j.appender.console.layout=org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern=%d%p [%c] - <%m>%n

#RollingFile

log4j.appender.logFile=org.apache.log4j.DailyRollingFileAppender

log4j.appender.logFile.File=../logs/king.log

log4j.appender.logFile.layout=org.apache.log4j.PatternLayout

log4j.appender.logFile.layout.ConversionPattern=%d %p [%c] -<%m>%n

2.        新增編碼轉換web.xml

<filter>

                   <filter-name>SetCharacter Encoding</filter-name>

                   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

                   <init-param>

                            <param-name>encoding</param-name>

                            <param-value>UTF-8</param-value>

                   </init-param>

                   <init-param>

                            <param-name>forceEncoding</param-name>

                            <param-value>true</param-value>

                   </init-param>

         </filter>

         <filter-mapping>

                   <filter-name>SetCharacter Encoding</filter-name>

                   <url-pattern>/*</url-pattern>

         </filter-mapping>

3.        實體類配置修改

<property name="annotatedClasses">

                            <list>

                                     <value>com.frank.model.Student</value>

                            </list>

                   </property>

                   修改為

                   <propertyname="packagesToScan" value="com.*.model" />

4.        資料來源新增連線池資訊

<!-- Connection Pooling Info -->

                   <propertyname="initialSize" value="5" />

                   <propertyname="maxActive" value="100" />

                   <propertyname="maxIdle" value="30" />

                   <propertyname="maxWait" value="500" />

                   <propertyname="defaultAutoCommit" value="false" />

5.        新增事務和aop支援

<beansxmlns="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">

6.        配置事務管理

<!-- 配置事務管理 -->

         <beanid="transactionManager"

                   class="org.springframework.orm.hibernate3.HibernateTransactionManager">

                   <propertyname="sessionFactory" ref="sessionFactory" />

         </bean>

         <!-- 配置註解實現管理事務(cglib:proxy-target-class="true") -->

         <tx:annotation-driventransaction-manager="transactionManager"

                   proxy-target-class="true"/>

七、到此,專案搭建已完成,自己可以做一下其它方面的優化和配置,接下來可以做自己喜歡的專案開發了。

不知道為什麼word裡的“-->”到這裡成“à”了,另外圖片也沒有了。