码迷,mamicode.com
首页 > 其他好文 > 详细

简单ssh框架整合

时间:2015-12-31 22:46:44      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

Struts2+Spring4 +Hibernate4

首先看看建立项目的框架

    技术分享

第一步  建立web项目

第二步  导入相对应需要的jar包(放在项目WEB-INFO/lib下)

  需要导入Spring需要的,Struts2需要的,Hibernate需要的,mysQL连接驱动;

  技术分享

技术分享

第三步  配置ssh各个的xml文件;

    技术分享

第四步 将log4j.dtd与log4j.xml放在WEB-INFO下:

    log4j.xml  

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 3 <log4j:configuration xmlns:log4j=‘http://jakarta.apache.org/log4j/‘>
 4 
 5     <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
 6         <layout class="org.apache.log4j.PatternLayout">
 7             <param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
 8         </layout>
 9     </appender>
10 
11     <appender name="DEBUG" class="org.apache.log4j.RollingFileAppender">
12         <param name="File" value="${sshWeb.root}/sshWeb-debug.log" />
13         <param name="Append" value="true" />
14         <param name="MaxFileSize" value="10240KB" />
15         <param name="MaxBackupIndex" value="1000" />
16         <layout class="org.apache.log4j.PatternLayout">
17             <param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
18         </layout>
19         <filter class="org.apache.log4j.varia.LevelRangeFilter">
20             <param name="LevelMin" value="DEBUG" />
21             <param name="LevelMax" value="DEBUG" />
22         </filter>
23     </appender>
24 
25     <appender name="INFO" class="org.apache.log4j.RollingFileAppender">
26         <param name="File" value="${sshWeb.root}/sshWeb-info.log" />
27         <param name="Append" value="true" />
28         <param name="MaxFileSize" value="10240KB" />
29         <param name="MaxBackupIndex" value="1000" />
30         <layout class="org.apache.log4j.PatternLayout">
31             <param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
32         </layout>
33         <filter class="org.apache.log4j.varia.LevelRangeFilter">
34             <param name="LevelMin" value="INFO" />
35             <param name="LevelMax" value="INFO" />
36         </filter>
37     </appender>
38 
39     <appender name="WARN" class="org.apache.log4j.RollingFileAppender">
40         <param name="File" value="${sshWeb.root}/sshWeb-warn.log" />
41         <param name="Append" value="true" />
42         <param name="MaxFileSize" value="10240KB" />
43         <param name="MaxBackupIndex" value="1000" />
44         <layout class="org.apache.log4j.PatternLayout">
45             <param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
46         </layout>
47         <filter class="org.apache.log4j.varia.LevelRangeFilter">
48             <param name="LevelMin" value="WARN" />
49             <param name="LevelMax" value="WARN" />
50         </filter>
51     </appender>
52 
53     <appender name="ERROR" class="org.apache.log4j.RollingFileAppender">
54         <param name="File" value="${sshWeb.root}/sshWeb-error.log" />
55         <param name="Append" value="true" />
56         <param name="MaxFileSize" value="10240KB" />
57         <param name="MaxBackupIndex" value="1000" />
58         <layout class="org.apache.log4j.PatternLayout">
59             <param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n" />
60         </layout>
61         <filter class="org.apache.log4j.varia.LevelRangeFilter">
62             <param name="LevelMin" value="ERROR" />
63             <param name="LevelMax" value="ERROR" />
64         </filter>
65     </appender>
66 
67     <root>
68         <priority value="INFO" />
69         <appender-ref ref="STDOUT" />
70         <appender-ref ref="DEBUG" />
71         <appender-ref ref="INFO" />
72         <appender-ref ref="WARN" />
73         <appender-ref ref="ERROR" />
74     </root>
75 
76 </log4j:configuration>
View Code

 

    log4j.dtd

技术分享
  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!--
  3  Licensed to the Apache Software Foundation (ASF) under one or more
  4  contributor license agreements.  See the NOTICE file distributed with
  5  this work for additional information regarding copyright ownership.
  6  The ASF licenses this file to You under the Apache License, Version 2.0
  7  (the "License"); you may not use this file except in compliance with
  8  the License.  You may obtain a copy of the License at
  9 
 10       http://www.apache.org/licenses/LICENSE-2.0
 11 
 12  Unless required by applicable law or agreed to in writing, software
 13  distributed under the License is distributed on an "AS IS" BASIS,
 14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 15  See the License for the specific language governing permissions and
 16  limitations under the License.
 17 -->
 18 
 19 <!-- Authors: Chris Taylor, Ceki Gulcu. -->
 20 
 21 <!-- Version: 1.2 -->
 22 
 23 <!-- A configuration element consists of optional renderer
 24 elements,appender elements, categories and an optional root
 25 element. -->
 26 
 27 <!ELEMENT log4j:configuration (renderer*, throwableRenderer?,
 28                                appender*,plugin*, (category|logger)*,root?,
 29                                (categoryFactory|loggerFactory)?)>
 30 
 31 <!-- The "threshold" attribute takes a level value below which -->
 32 <!-- all logging statements are disabled. -->
 33 
 34 <!-- Setting the "debug" enable the printing of internal log4j logging   -->
 35 <!-- statements.                                                         -->
 36 
 37 <!-- By default, debug attribute is "null", meaning that we not do touch -->
 38 <!-- internal log4j logging settings. The "null" value for the threshold -->
 39 <!-- attribute can be misleading. The threshold field of a repository     -->
 40 <!-- cannot be set to null. The "null" value for the threshold attribute -->
 41 <!-- simply means don‘t touch the threshold field, the threshold field   --> 
 42 <!-- keeps its old value.                                                -->
 43      
 44 <!ATTLIST log4j:configuration
 45   xmlns:log4j              CDATA #FIXED "http://jakarta.apache.org/log4j/" 
 46   threshold                (all|trace|debug|info|warn|error|fatal|off|null) "null"
 47   debug                    (true|false|null)  "null"
 48   reset                    (true|false) "false"
 49 >
 50 
 51 <!-- renderer elements allow the user to customize the conversion of  -->
 52 <!-- message objects to String.                                       -->
 53 
 54 <!ELEMENT renderer EMPTY>
 55 <!ATTLIST renderer
 56   renderedClass  CDATA #REQUIRED
 57   renderingClass CDATA #REQUIRED
 58 >
 59 
 60 <!--  throwableRenderer allows the user to customize the conversion
 61          of exceptions to a string representation.  -->
 62 <!ELEMENT throwableRenderer (param*)>
 63 <!ATTLIST throwableRenderer
 64   class  CDATA #REQUIRED
 65 >
 66 
 67 
 68 <!-- Appenders must have a name and a class. -->
 69 <!-- Appenders may contain an error handler, a layout, optional parameters -->
 70 <!-- and filters. They may also reference (or include) other appenders. -->
 71 <!ELEMENT appender (errorHandler?, param*,
 72       rollingPolicy?, triggeringPolicy?, connectionSource?,
 73       layout?, filter*, appender-ref*)>
 74 <!ATTLIST appender
 75   name         CDATA     #REQUIRED
 76   class     CDATA    #REQUIRED
 77 >
 78 
 79 <!ELEMENT layout (param*)>
 80 <!ATTLIST layout
 81   class        CDATA    #REQUIRED
 82 >
 83 
 84 <!ELEMENT filter (param*)>
 85 <!ATTLIST filter
 86   class        CDATA    #REQUIRED
 87 >
 88 
 89 <!-- ErrorHandlers can be of any class. They can admit any number of -->
 90 <!-- parameters. -->
 91 
 92 <!ELEMENT errorHandler (param*, root-ref?, logger-ref*,  appender-ref?)> 
 93 <!ATTLIST errorHandler
 94    class        CDATA   #REQUIRED 
 95 >
 96 
 97 <!ELEMENT root-ref EMPTY>
 98 
 99 <!ELEMENT logger-ref EMPTY>
100 <!ATTLIST logger-ref
101   ref CDATA #REQUIRED
102 >
103 
104 <!ELEMENT param EMPTY>
105 <!ATTLIST param
106   name        CDATA   #REQUIRED
107   value        CDATA    #REQUIRED
108 >
109 
110 
111 <!-- The priority class is org.apache.log4j.Level by default -->
112 <!ELEMENT priority (param*)>
113 <!ATTLIST priority
114   class   CDATA    #IMPLIED
115   value      CDATA #REQUIRED
116 >
117 
118 <!-- The level class is org.apache.log4j.Level by default -->
119 <!ELEMENT level (param*)>
120 <!ATTLIST level
121   class   CDATA    #IMPLIED
122   value      CDATA #REQUIRED
123 >
124 
125 
126 <!-- If no level element is specified, then the configurator MUST not -->
127 <!-- touch the level of the named category. -->
128 <!ELEMENT category (param*,(priority|level)?,appender-ref*)>
129 <!ATTLIST category
130   class         CDATA   #IMPLIED
131   name        CDATA    #REQUIRED
132   additivity    (true|false) "true"  
133 >
134 
135 <!-- If no level element is specified, then the configurator MUST not -->
136 <!-- touch the level of the named logger. -->
137 <!ELEMENT logger (param*,level?,appender-ref*)>
138 <!ATTLIST logger
139   class         CDATA   #IMPLIED
140   name        CDATA    #REQUIRED
141   additivity    (true|false) "true"  
142 >
143 
144 
145 <!ELEMENT categoryFactory (param*)>
146 <!ATTLIST categoryFactory 
147    class        CDATA #REQUIRED>
148 
149 <!ELEMENT loggerFactory (param*)>
150 <!ATTLIST loggerFactory
151    class        CDATA #REQUIRED>
152 
153 <!ELEMENT appender-ref EMPTY>
154 <!ATTLIST appender-ref
155   ref CDATA #REQUIRED
156 >
157 
158 <!-- plugins must have a name and class and can have optional parameters -->
159 <!ELEMENT plugin (param*, connectionSource?)>
160 <!ATTLIST plugin
161   name         CDATA        #REQUIRED
162   class     CDATA  #REQUIRED
163 >
164 
165 <!ELEMENT connectionSource (dataSource?, param*)>
166 <!ATTLIST connectionSource
167   class        CDATA  #REQUIRED
168 >
169 
170 <!ELEMENT dataSource (param*)>
171 <!ATTLIST dataSource
172   class        CDATA  #REQUIRED
173 >
174 
175 <!ELEMENT triggeringPolicy ((param|filter)*)>
176 <!ATTLIST triggeringPolicy
177   name         CDATA  #IMPLIED
178   class     CDATA  #REQUIRED
179 >
180 
181 <!ELEMENT rollingPolicy (param*)>
182 <!ATTLIST rollingPolicy
183   name         CDATA  #IMPLIED
184   class     CDATA  #REQUIRED
185 >
186 
187 
188 <!-- If no priority element is specified, then the configurator MUST not -->
189 <!-- touch the priority of root. -->
190 <!-- The root category always exists and cannot be subclassed. -->
191 <!ELEMENT root (param*, (priority|level)?, appender-ref*)>
192 
193 
194 <!-- ==================================================================== -->
195 <!--                       A logging event                                -->
196 <!-- ==================================================================== -->
197 <!ELEMENT log4j:eventSet (log4j:event*)>
198 <!ATTLIST log4j:eventSet
199   xmlns:log4j             CDATA #FIXED "http://jakarta.apache.org/log4j/" 
200   version                (1.1|1.2) "1.2" 
201   includesLocationInfo   (true|false) "true"
202 >
203 
204 
205 
206 <!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?, 
207                        log4j:locationInfo?, log4j:properties?) >
208 
209 <!-- The Date format is application dependent. -->
210 <!ATTLIST log4j:event
211     logger     CDATA #REQUIRED
212     level      CDATA #REQUIRED
213     thread     CDATA #REQUIRED
214     Date  CDATA #REQUIRED
215     time       CDATA #IMPLIED
216 >
217 
218 <!ELEMENT log4j:message (#PCDATA)>
219 <!ELEMENT log4j:NDC (#PCDATA)>
220 
221 <!ELEMENT log4j:throwable (#PCDATA)>
222 
223 <!ELEMENT log4j:locationInfo EMPTY>
224 <!ATTLIST log4j:locationInfo
225   class  CDATA    #REQUIRED
226   method CDATA    #REQUIRED
227   file   CDATA    #REQUIRED
228   line   CDATA    #REQUIRED
229 >
230 
231 <!ELEMENT log4j:properties (log4j:data*)>
232 
233 <!ELEMENT log4j:data EMPTY>
234 <!ATTLIST log4j:data
235   name   CDATA    #REQUIRED
236   value  CDATA    #REQUIRED
237 >
View Code

 

第五步 配置web.xml文件

技术分享
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSH</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- web应用一启动,便加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
    
 <!-- 动态设置项目的运行路径 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>sshWeb.root</param-value>
    </context-param>
    
     <!-- 加载LOG4J -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>

    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    
    <!-- 配置Hibernate过滤器 -->
    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>flushMode</param-name>
            <param-value>AUTO</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 字符集过滤 -->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 登录过滤  -->
    <filter>
         <filter-name>loginFilter</filter-name>
         <filter-class>com.cy.ssh.filter.LoginFilter</filter-class>
     </filter>
 
     <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
    <!-- 加载spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 加载log4j文件 -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
     
</web-app>
View Code

 

第六步 来配置ssh各个的xml文件,

先配置 applicationContext.xml 

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" 
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4      xmlns:p="http://www.springframework.org/schema/p" 
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6      xmlns:tx="http://www.springframework.org/schema/tx" 
 7      xmlns:mvc="http://www.springframework.org/schema/mvc" 
 8     xmlns:context="http://www.springframework.org/schema/context" 
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans
10                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
11                         http://www.springframework.org/schema/context
12                         http://www.springframework.org/schema/context/spring-context-3.0.xsd 
13                         http://www.springframework.org/schema/aop
14                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
15                         http://www.springframework.org/schema/tx
16                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
17                         http://www.springframework.org/schema/mvc
18                         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
19 <!-- 开启spring自动扫描功能,适用注解 -->
20     <context:component-scan base-package="com.cy.ssh" />
21     
22     <!-- 配置C3P0数据源 -->
23     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
24         <property name="driverClass" value="com.mysql.jdbc.Driver" />
25         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
26         <property name="user" value="root" />
27         <property name="password" value="root" />
28         <property name="minPoolSize" value="1" />
29         <property name="maxPoolSize" value="20" />
30         <property name="initialPoolSize" value="1" />
31         <property name="maxIdleTime" value="60" />
32         <property name="acquireIncrement" value="5" />
33         <property name="automaticTestTable" value="c3p0TestTable" />
34         <property name="idleConnectionTestPeriod" value="60" />
35         <property name="checkoutTimeout" value="3000" />
36     </bean>
37     
38     <!-- 配置SessionFactory -->    
39     <bean id="sessionFactory"
40         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
41         <!-- 向SessionFactory中注入数据源 -->
42         <property name="dataSource" ref="dataSource" />
43         <property name="hibernateProperties">
44             <props>
45                 <!-- 定义Hibernate的方言 -->
46                 <prop key="hibernate.dialect">
47                     org.hibernate.dialect.MySQLDialect
48                 </prop>
49                 <!-- 是否根据需要每次自动更新数据库
50                 <prop key="hibernate.hbm2ddl.auto">update</prop> -->
51                 <!-- 控制台显示SQL -->
52                 <prop key="hibernate.show_sql">true</prop>
53                 <prop key="hibernate.format_sql">true</prop>
54                 <!-- 使用SQL注释 -->
55                 <prop key="hibernate.use_sql_comments">true</prop>
56             </props>
57         </property>
58         
59         <!-- 浏览bean包下的所有使用Hibernate注解的JavaBean -->
60         <property name="packagesToScan">
61             <list>
62                 <value>com.cy.ssh.beans</value>
63             </list>
64         </property>
65     </bean>    
66     
67     <!-- spring通过声明式方式来进行事务管理-->
68     <bean id="transactionManager"
69         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
70         <property name="sessionFactory" ref="sessionFactory"/>
71     </bean>
72     
73     
74     <!-- 定义个通知,指定事务管理器 -->
75     <tx:advice id="txAdvice" transaction-manager="transactionManager">
76         <tx:attributes>
77             <tx:method name="delete*" propagation="REQUIRED" read-only="false"
78                 rollback-for="java.lang.Exception" />
79             <tx:method name="save*" propagation="REQUIRED" read-only="false"
80                 rollback-for="java.lang.Exception" />
81             <tx:method name="update*" propagation="REQUIRED" read-only="false"
82                 rollback-for="java.lang.Exception" />
83             <tx:method name="load*" propagation="SUPPORTS" read-only="true"/>
84             <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
85             <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
86             <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
87         </tx:attributes>
88     </tx:advice>
89     
90     <aop:config>
91         <!-- 配置一个切入点 -->
92         <aop:pointcut id="serviceMethods"
93             expression="execution(* com.cy.ssh.service.impl.*ServiceImpl.*(..))" />
94         <aop:advisor advice-ref="txAdvice"
95             pointcut-ref="serviceMethods" />
96     </aop:config>    
97 
98 </beans>
View Code

 

 配置都差不多了。

来写个登录案例

User.java   使用Hibernate注解  

技术分享
 1 package com.cy.ssh.beans;
 2 
 3 import java.io.Serializable;
 4 import javax.persistence.Column;
 5 import javax.persistence.Entity;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.Id;
 8 import javax.persistence.Table;
 9 
10 import org.hibernate.annotations.GenericGenerator;
11 /**
12  * 用户
13  * @author acer
14  *
15  */
16 @Entity
17 @Table(name="t_user")
18 public class User implements Serializable {
19 
20     private static final long serialVersionUID = 1L;
21     @Id
22     @Column(name="id")
23     @GenericGenerator(name="hbincrement", strategy="increment")
24     @GeneratedValue(generator="hbincrement")
25     private int id;
26     @Column(name="username",length=20)
27     private String username;
28     @Column(name="password",length=32)
29     private String password;
30     @Column(name="age")
31     private int age;
32     @Column(name="flag")
33     private int flag;
34     
35     public User(){
36       
37     }
38 
39     public int getId() {
40         return id;
41     }
42 
43     public void setId(int id) {
44         this.id = id;
45     }
46 
47     public String getUsername() {
48         return username;
49     }
50 
51     public void setUsername(String username) {
52         this.username = username;
53     }
54 
55     public String getPassword() {
56         return password;
57     }
58 
59     public void setPassword(String password) {
60         this.password = password;
61     }
62 
63     public int getAge() {
64         return age;
65     }
66 
67     public void setAge(int age) {
68         this.age = age;
69     }
70 
71     public int getFlag() {
72         return flag;
73     }
74 
75     public void setFlag(int flag) {
76         this.flag = flag;
77     }
78 
79     @Override
80     public String toString() {
81         return "User [id=" + id + ", username=" + username + ", password="
82                 + password + ", age=" + age + ", flag=" + flag + "]";
83     }
84   
85     
86 
87 }
View Code

 

 

工具类:

HibernateTools.java

技术分享
 1 package com.cy.ssh.tools;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.beans.factory.annotation.Qualifier;
 7 import org.springframework.stereotype.Component;
 8 /**
 9  * 
10  * @author acer
11  *
12  */
13 @Component
14 public class HibernateTools {
15     
16     @Autowired
17     @Qualifier("sessionFactory")
18     private SessionFactory sessionFactory;
19     public void setSessionFactory(SessionFactory sessionFactory) {
20         this.sessionFactory = sessionFactory;
21     }
22     
23     public Session getSession(){
24         return sessionFactory.getCurrentSession();
25     }
26     
27     public Session getNewSession(){
28         return sessionFactory.openSession();
29     }
30     
31 }
View Code

 

StringTools.java

技术分享
 1 package com.cy.ssh.tools;
 2 /**
 3  * 判断是否为空
 4  * @author acer
 5  *
 6  */
 7 public class StringTools {
 8 
 9     public static boolean isNull(String str){
10         if(str == null || "".equals(str)){
11             return true;
12         }
13         return false;
14     }
15 }
View Code

 

 

持久层

IUserDao.java

技术分享
 1 package com.cy.ssh.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.cy.ssh.beans.User;
 6 
 7 public interface IUserDao {
 8     /**
 9      * 查询用户
10      * @param hql
11      * @return
12      */
13     public List<?> find(String hql);
14     /**
15      * 新增user
16      * @param u
17      */
18     public void saveUser(User u);
19     
20     /**
21      * 修改user
22      * @param u
23      */
24     public void updateUser(User u);
25     
26     /**
27      * 删除user
28      * @param u
29      */
30     public void updateDeleteUser(User u);
31 
32 }
View Code

 

UserServiceImpl.java

技术分享
 1 package com.cy.ssh.dao.impl;
 2 
 3 import java.util.List;
 4 
 5 
 6 
 7 
 8 import org.hibernate.Query;
 9 import org.springframework.stereotype.Repository;
10 
11 import com.cy.ssh.beans.User;
12 import com.cy.ssh.dao.IUserDao;
13 import com.cy.ssh.tools.HibernateTools;
14 @Repository
15 public class UserDaoImpl extends HibernateTools implements IUserDao{
16 
17     @Override
18     public List<?> find(String hql) {
19         Query query= getSession().createQuery(hql);
20         return query.list();
21     }
22 
23     @Override
24     public void saveUser(User u) {
25         getSession().save(u);
26         
27     }
28 
29     @Override
30     public void updateUser(User u) {
31         getSession().update(u);
32         
33     }
34 
35     @Override
36     public void updateDeleteUser(User u) {
37         getSession().update(u);
38         
39     }
40 
41 }
View Code

 

 

业务层

IUserService.java

技术分享
 1 package com.cy.ssh.service;
 2 
 3 import com.cy.ssh.beans.User;
 4 
 5 public interface IUserService {
 6     /**
 7      * 
 8      * @param user
 9      * @return
10      */
11     public User getUser(User user);
12     /**
13      * 新增user
14      * @param u
15      */
16     public void saveUser(User u);
17     
18     /**
19      * 修改user
20      * @param u
21      */
22     public void updateUser(User u);
23     
24     /**
25      * 删除user
26      * @param id
27      */
28     public void updateDeleteUser(int id);
29 }
View Code

 

IUserServiceImpl.java

技术分享
 1 package com.cy.ssh.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.springframework.stereotype.Service;
 8 
 9 import com.cy.ssh.beans.User;
10 import com.cy.ssh.dao.IUserDao;
11 import com.cy.ssh.service.IUserService;
12 @Service
13 public class UserServiceImpl implements IUserService{
14     @Resource
15     private IUserDao userDaoImpl;
16     
17     @Override
18     public User getUser(User user) {
19         
20         User ret = null;
21         String hql = "from User as u where (1=1) and u.username = ‘"+user.getUsername()+"‘ and u.flag = 1";
22         List<?> list = userDaoImpl.find(hql);
23         if(list != null && !list.isEmpty()){
24             ret = (User) list.get(0);
25         }
26         return ret;    
27         }
28 
29     @Override
30     public void saveUser(User u) {
31     
32         userDaoImpl.saveUser(u);
33     }
34 
35     @Override
36     public void updateUser(User u) {
37          userDaoImpl.updateUser(u);
38     }
39 
40     @Override
41     public void updateDeleteUser(int id) {
42 
43     }
44 
45 }
View Code

 

 

LoginAction.java

技术分享
 1 package com.cy.ssh.action;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.apache.struts2.ServletActionContext;
 6 import org.springframework.context.annotation.Scope;
 7 import org.springframework.stereotype.Controller;
 8 
 9 import com.cy.ssh.beans.User;
10 import com.cy.ssh.service.IUserService;
11 import com.cy.ssh.tools.StringTools;
12 import com.opensymphony.xwork2.ActionSupport;
13 @Controller
14 @Scope("prototype")
15 public class LoginAction extends ActionSupport {
16 
17     
18     private static final long serialVersionUID = 1L;
19     private User user;
20     @Resource
21     private IUserService userServiceImpl;
22     
23     
24     @Override
25     public void validate() {
26         if(StringTools.isNull(user.getUsername())){
27             this.addFieldError("dataErr", "用户名不能为空");
28         }
29         if(StringTools.isNull(user.getPassword())){
30             this.addFieldError("dataErr", "密码不能为空");
31         }
32         
33     }
34     @Override
35     public String execute() throws Exception {
36         User u=userServiceImpl.getUser(user);
37         if(u!=null){
38             ServletActionContext.getRequest().getSession().setAttribute("user", user);
39             return SUCCESS;
40         }else{
41             return ERROR;
42         }
43     }
44 
45     public User getUser() {
46         return user;
47     }
48     public void setUser(User user) {
49         this.user = user;
50     }
51     
52     
53 
54 }
View Code

 

 

login.jsp

技术分享
 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <%@ taglib uri="/struts-tags" prefix="s" %> 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP ‘login.jsp‘ starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26   <s:fielderror></s:fielderror>
27     <form action="<%=basePath%>login.do" method="post">
28       <table>
29         <tr>
30           <td>用户名:</td>
31           <td><input type="text" name="user.username"/></td>
32         </tr>
33          <tr>
34            <td>密码:</td>
35            <td><input type="password" name="user.password"/></td>
36         </tr>
37         <tr>
38            <td colspan="2"><input type="submit" value="登录"/></td>
39         </tr>
40       </table>
41     
42     </form>
43   </body>
44 </html>
View Code

 

 

配置struts.xml

技术分享
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6          <!-- 告诉struts框架,我们的Action类的实例化来源于Spring容器 -->
 7              <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
 8          <!-- 指定需要Struts 2处理的请求后缀 -->
 9              <constant name="struts.action.extension" value="action,do" />
10   
11        <package name="default" namespace="/" extends="struts-default">
12        
13       
14         <action name="login" class="loginAction">
15            
16             <result name="success">/success.jsp</result>
17             <result name="input">/login.jsp</result>
18         </action>
19         
20         
21         
22         
23     </package>
24     
25 
26 </struts>
View Code

 

 差不多就完成了! 

 

简单ssh框架整合

标签:

原文地址:http://www.cnblogs.com/hellokitty1/p/5092659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!