轉自:http://blog.csdn.net/ererfei/article/details/46800415
1. 項目目錄以及資料表結構
2. 準備jar包
下面是我開發項目準備的jar包,可能有一些是項目依賴的,例如其中的druid-1.0.13.jar、ftplet-api-1.0.6.jar ftpserver-core-1.0.6.jar、junit-4.1.1.jar、slf4j-api-1.7.12這幾個包就是根據需要添加的,分别是阿裡巴巴開源資料庫連接配接池、兩個ftp檔案伺服器、單元測試以及slf4j用于log跟蹤記錄資料庫操作資訊,其他的都是SSH中的jar包,到百度共享下載下傳下圖中的所有包。
(jar包下載下傳 連結: http://pan.baidu.com/s/1pJ42207 提取密碼: c5yh)
3. 配置struts2
配置代碼如下(所有的配置屬性都可以在struts2-core-×××.jar包中org.apache.struts2下的default.properties中找到)
【struts.xml】
[html] view plain copy
- <?xml version="1.0"encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN"
- "http://struts.apache.org/dtds/struts-2.3.dtd">
- <struts>
- <constant name="struts.enable.DynamicMethodInvocation"value="false" />
- <constant name="struts.devMode" value="true" />
- <!-- 指定由spring負責action對象的建立 -->
- <constant name="struts.objectFactory" value="spring" />
- <!-- 國際化設定,請求參數為utf-8編碼 -->
- <constant name="struts.i18n.encoding" value="utf-8" />
- <!-- 指定被struts2處理的請求字尾類型,如果有多個,用逗号隔開 -->
- <constant name="struts.action.extension" value="action" />
- <!-- 指定上傳檔案的大小上限 -->
- <constant name="struts.multipart.maxSize" value="209715200" />
- <!-- 當配置檔案改動後是否重新加載,生産環境下需要設定為false -->
- <constant name="struts.configuration.xml.reload" value="false" />
- <!-- 是否使用struts2的開發模式,生産環境下需要設定為false -->
- <constant name="struts.devMode" value="false" />
- <!-- 浏覽器是否緩存靜态内容,生産環境下需要設定為true -->
- <constant name="struts.serve.static.browserCache" value="true" />
- <!-- <includefile="example.xml"/> -->
- </struts>
4. 配置Spring+Hibernate
4.1 編寫Spring配置檔案applicationContext.xml
【applicationContext.xml】
[html] view plain copy
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:task="http://www.springframework.org/schema/task"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd
- http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-4.1.xsd">
- <!-- 掃描base-package下的檔案,并注冊bean,同時激活已注冊的bean,就是掃描那些用@Service,@component,@Repositiry辨別的那些類 -->
- <context:component-scan base-package="com.mlq.love" />
- </beans>
4.2編寫Hibernate配置檔案applicationContext-hibernate.xml
首先編寫配置檔案dbconfig.properties,這樣提取出來配置資訊可以比較直覺的檢視和維護
【dbconfig.properties】
[plain] view plain copy
- url=jdbc\:mysql\://localhost\:3306/test
- driverClassName=com.mysql.jdbc.Driver
- username=root
- password=centerm
- initialSize=10
- minIdle=5
- maxActive=50
- maxWait=60000
- timeBetweenEvictionRunsMillis=60000
- minEvictableIdleTimeMillis=300000
- poolPreparedStatements=true
- maxPoolPreparedStatementPerConnectionSize=100
- validationQuery=SELECT'x'
- testWhileIdle=true
- testOnBorrow=false
- testOnReturn=false
- maxOpenPreparedStatements=20
- removeAbandoned=false
- removeAbandonedTimeout=1800
- logAbandoned=true
【applicationContext-hibernate.xml】
[html] view plain copy
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"
- xmlns:task="http://www.springframework.org/schema/task"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd
- http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-4.1.xsd">
- <bean id="propertyConfigurer"
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>/WEB-INF/classes/dbconfig.properties</value>
- </list>
- </property>
- </bean>
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
- <property name="url" value="${url}"/>
- <!--可以省略這個driveerClassName的指定,因為Druid提供了N個資料庫的支援-->
- <property name="driverClassName" value="${driverClassName}" />
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- <!-- 配置初始化大小、最小、最大 -->
- <property name="initialSize" value="${initialSize}" />
- <property name="minIdle" value="${minIdle}"/>
- <property name="maxActive" value="${maxActive}"/>
- <!-- 配置擷取連接配接等待逾時的時間 -->
- <property name="maxWait" value="${maxWait}"/>
- <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒 -->
- <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
- <!-- 配置一個連接配接在池中最小生存的時間,機關是毫秒 -->
- <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
- <!-- 打開PSCache(PreparedStatementCache),并且指定每個連接配接上PSCache的大小 -->
- <property name="poolPreparedStatements" value="${poolPreparedStatements}" />
- <property name="maxPoolPreparedStatementPerConnectionSize"value="${maxPoolPreparedStatementPerConnectionSize}"/>
- <property name="validationQuery" value="${validationQuery}" />
- <property name="testWhileIdle" value="${testWhileIdle}" />
- <property name="testOnBorrow" value="${testOnBorrow}" />
- <property name="testOnReturn" value="${testOnReturn}" />
- </bean>
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <!-- entity包掃描範圍 -->
- <property name="packagesToScan">
- <list>
- <value>com.mlq.love.entity</value>
- </list>
- </property>
- <property name="dataSource" ref="dataSource" />
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.hbm2ddl.auto">update</prop>
- <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
- <prop key="hibernate.show_sql">true</prop>
- <prop key="hibernate.format_sql">true</prop>
- <prop key="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
- <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
- </props>
- </property>
- </bean>
- <!-- 事務配置 -->
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <!-- 開啟注解配置事務 -->
- <tx:annotation-driven transaction-manager="transactionManager" />
- </beans>
5. 修改web.xml檔案
主要是增加Struts2和Spring的配置資訊
【web.xml】
[html] view plain copy
- <?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/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
- <display-name>SSH搭建(注解)</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- </welcome-file-list>
- <!-- spring配置檔案路徑 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/applicationContext*.xml</param-value>
- </context-param>
- <!-- spring監聽器 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
6. 編寫實體類、DAO類、Service類以及Action
【User.java】
[java] view plain copy
- @Entity
- @Table(name="user")
- public class User {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name="userid")
- private Integer userId;
- @Column(name="username")
- private String userName;
- @Column(name="password")
- private String passWord;
- @Column(name="birthday")
- private Date birthday;
- @Column(name="age")
- private Integer age;
- @Column(name="sex")
- private String sex;
- getters setters......
- }
【BaseDao.java】
[java] view plain copy
- public class BaseDao<T> {
- @Resource(name = "sessionFactory")
- protected SessionFactory sessionFactory;
- protected Class<?> entityClass;
- public BaseDao()
- {
- ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
- entityClass = (Class<?>)type.getActualTypeArguments()[0];
- }
- protected Session getSession()
- {
- return sessionFactory.getCurrentSession();
- }
- public Serializable save(T t){
- return getSession().save(t);
- }
- }
【UserDao.java】
[java] view plain copy
- @Repository("userDao")
- public class UserDao extends BaseDao<User>{
- @SuppressWarnings("unchecked")
- public User checkUser(User user){
- String hql = "from User where userId = :id and password = :password";
- Query query = getSession().createQuery(hql)
- .setParameter("id", user.getUserId())
- .setParameter("password", user.getPassWord());
- List<User> userList = (List<User>)query.list();
- if(userList != null && userList.size() > 0){
- System.out.println("wocao");
- return userList.get(0);
- }
- return null;
- }
- }
【UserService.java】
[java] view plain copy
- @Service("userService")
- public class UserService {
- @Resource
- private UserDao userDao;
- public Serializable save(User user){
- return userDao.save(user);
- }
- @Transactional(readOnly = true, rollbackFor = Exception.class)
- public User checkUser(User user){
- return userDao.checkUser(user);
- }
- }
【LoginAction.java】
[java] view plain copy
- @Controller("loginAction")
- @Scope("prototype")
- @Namespace("")
- @ParentPackage("struts-default")
- public class LoginAction extends ActionSupport implements SessionAware{
- private static final long serialVersionUID = 6473585621724667329L;
- @Resource(name = "userService")
- private UserService userService;
- private Map<String, Object> session;
- private String id;
- private String password;
- @Action
- (
- value="login",
- results =
- {
- @Result(name = "success", location = "/main.jsp"),
- @Result(name = "error", location = "/login.jsp")
- }
- )
- public String login(){
- User user = (User)session.get("user");
- if(user == null){
- user = new User();
- user.setUserId(Integer.parseInt(id));
- user.setPassWord(password);
- }
- user = userService.checkUser(user);
- if(user == null){
- return "error";
- }else {
- session.put("user", user);
- return "success";
- }
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- @Override
- public void setSession(Map<String, Object> session) {
- this.session = session;
- }
- }
7. 測試頁面
【login.java】
[html] view plain copy
- <body>
- <form action="login.action" method="post">
- <label>姓名:</label><input name="id" type="text" value="" />
- <label>密碼:</label><input name="password" type="password" value="" />
- <input type="submit" value="登陸" />
- </form>
- </body>
【main.java】
[html] view plain copy
- <body>
- <label>姓名: ${sessionScope.user.userName}</label>
- <label>出生日期 : ${sessionScope.user.birthday}</label>
- <label id="skill">展示技能</label>
- </body>
至此,基于注解方式的SSH架構搭建完成~