SSH는 JavaWeb의 고전적인 프레임워크입니다. 100% 사람들이 SSH 프레임워크를 알아야 한다고 말할 수는 없지만, 대부분의 회사에서는 프레임워크에 관해서라면 ssh를 언급하겠습니다. 매우 간단한 등록 예제를 사용합니다. 프레임워크를 통합할 때는 통합하기 전에 각 프레임워크를 별도로 테스트하는 데 주의해야 합니다. 그렇지 않으면 통합 후 문제를 해결하기가 어렵습니다.
환경: windows + MyEclipse + JDK1.7 + Tomcat7 + MySQL
코드는 테스트를 거쳤습니다. 오류가 있는 경우 군데군데 명확하게 설명하지 않았기 때문일 수 있으니 메시지를 남겨주세요.
(3) 데이터베이스 드라이버
2.스트럿츠2
참고: javassist-3.18.1-GA.jar 패키지와 최대 절전 모드 간의 중복(상위 버전만 유지)
참고: 이 패키지를 가져오면 struts2가 스프링 컨테이너를 찾을 때 시작됩니다. 찾을 수 없으면 예외가 발생합니다
(1) 기본: 4+2
코어 | 컨텍스트 | 로깅 | log4j
(2) 웹 통합: 웹 패키지 spring-web 에서 최대 절전 모드로 초대 jdbc | spring-tx | c3p0 | spring-orm (5) junit4 테스트 통합: 테스트 패키지 spring-test 4. 태그 라이브러리 standard.jar | 3개의 별도 구성 스프링 컨테이너 1. applicationContext.xml 생성 및 제약 조건 가져오기(4) beans | aop | tx<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans" 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/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "><bean name="userAction" class="cn.xyp.web.action.UserAction"></bean></beans>
<!-- 让spring随web启动而创建的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置spring配置文件位置参数 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
1. struts2 기본 구성 파일(struts.xml)을 구성합니다.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="crm" namespace="/" extends="struts-default"><action name="UserAction_*" class="cn.xyp.web.action.UserAction" method="{1}"><result name="success">/success.jsp</result></action></package></struts>
<!-- struts2核心过滤器 --> <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>
### if specified, the default object factory can be overridden here ### Note: short-hand notation is supported in some cases, such as "spring" ### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here # struts.objectFactory = spring ### specifies the autoWiring logic when using the SpringObjectFactory. ### valid values are: name, type, auto, and constructor (name is the default) struts.objectFactory.spring.autoWire = name
<!-- # struts.objectFactory = spring 将action的创建交给spring容器 struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant name="struts.objectFactory" value="spring"></constant>
<!-- 整合方案1:class属性上仍然配置action的完整类名 struts2仍然创建action,由spring负责组装Action中的依赖属性 --><action name="UserAction_*" class="cn.xyp.web.action.UserAction" method="{1}" ><result name="toHome" type="redirect" >/index.htm</result><result name="error" >/login.jsp</result></action>
1. 엔터티 클래스 및 orm 메타데이터 가져오기
예: User .java <!-- action --><!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 --><bean name="userAction" class="cn.itcast.web.action.UserAction" scope="prototype" ><property name="userService" ref="userService" ></property></bean>
<!-- 整合方案2:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action name="UserAction_*" class="userAction" method="{1}" ><result name="toHome" type="redirect" >/index.htm</result><result name="error" >/login.jsp</result></action>
package cn.xyp.web.domain;import java.util.HashSet;import java.util.Set;public class User {private Long user_id;private String user_code;private String user_name;private String user_password;private Character user_state;public Long getUser_id() {return user_id; }public void setUser_id(Long user_id) {this.user_id = user_id; }public String getUser_code() {return user_code; }public void setUser_code(String user_code) {this.user_code = user_code; }public String getUser_name() {return user_name; }public void setUser_name(String user_name) {this.user_name = user_name; }public String getUser_password() {return user_password; }public void setUser_password(String user_password) {this.user_password = user_password; }public Character getUser_state() {return user_state; }public void setUser_state(Character user_state) {this.user_state = user_state; } @Overridepublic String toString() {return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password=" + user_password + "]"; } }
将sessionFactory对象交给spring容器管理
<!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 --><bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" ><property name="configLocation" value="classpath:hibernate.cfg.xml" ></property></bean>
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 --><bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" ><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property name="dataSource" ref="dataSource" ></property><!-- 配置hibernate基本信息 --><property name="hibernateProperties"><props><!-- 必选配置 --><prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop><prop key="hibernate.connection.url" >jdbc:mysql:///crm_32</prop><prop key="hibernate.connection.username" >root</prop><prop key="hibernate.connection.password" >1234</prop> <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop><!-- 可选配置 --><prop key="hibernate.show_sql" >true</prop><prop key="hibernate.format_sql" >true</prop><prop key="hibernate.hbm2ddl.auto" >update</prop></props></property><!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 --><property name="mappingDirectoryLocations" value="classpath:cn/itcast/domain" ></property></bean>
jdbc.jdbcUrl=jdbc:mysql:///xyp_crm jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123456
<!-- 读取db.properties文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 配置c3p0连接池 --><bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" ><property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property><property name="driverClass" value="${jdbc.driverClass}" ></property><property name="user" value="${jdbc.user}" ></property><property name="password" value="${jdbc.password}" ></property></bean>
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" ><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property name="dataSource" ref="dataSource" ></property>
注意:项目中要确保使用统一版本。
//HibernateDaoSupport 为dao注入sessionFactorypublic class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Overridepublic User getByUserCode(final String usercode) {//HQLreturn getHibernateTemplate().execute(new HibernateCallback<User>() { @Overridepublic User doInHibernate(Session session) throws HibernateException { String hql = "from User where user_code = ? "; Query query = session.createQuery(hql); query.setParameter(0, usercode); User user = (User) query.uniqueResult();return user; } });
//CriteriaDetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc); if(list != null && list.size()>0){return list.get(0); }else{return null; }
<!-- Dao --><bean name="userDao" class="cn.xyp.dao.impl.UserDaoImpl" ><!-- 注入sessionFactory --><property name="sessionFactory" ref="sessionFactory"></property></bean>
<!-- 核心事务管理器 --><bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" ><property name="sessionFactory" ref="sessionFactory" ></property></bean>
<!-- 配置通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager" > <tx:attributes><tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" /> <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice>
<!-- 配置将通知织入目标对象 配置切点 配置切面 --><aop:config> <aop:pointcut expression="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))" id="txPc"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" /> </aop:config>
<!-- 开启注解事务 --><tx:annotation-driven transaction-manager="transactionManager" />
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)public class UserServiceImpl implements UserService{
@Override @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)public void saveUser(User u) { ud.save(u); }
为了避免使用懒加载时出现no-session问题.需要扩大session的作用范围。
<!-- 扩大session作用范围 注意: 任何filter一定要在struts的filter之前调用 因为struts是不会放行的 --> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<struts><!-- # struts.objectFactory = spring 将action的创建交给spring容器 struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant name="struts.objectFactory" value="spring"></constant><package name="crm" namespace="/" extends="struts-default" ><global-exception-mappings><exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping></global-exception-mappings> <!-- 整合方案:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action name="UserAction_*" class="userAction" method="{1}" ><result name="toHome" type="redirect" >/index.htm</result><result name="error" >/login.jsp</result></action></package></struts>
public class UserAction extends ActionSupport implements ModelDriven<User> {private User user = new User(); private UserService userService ; public void setUserService(UserService userService) {this.userService = userService; } public String login() throws Exception { // 1 调用Service执行登陆逻辑User u = userService.getUserByCodePassword(user); // 2 将返回的User对象放入session域ActionContext.getContext().getSession().put("user", u);// 3 重定向到项目首页return "toHome"; } @Overridepublic User getModel() {return user; } }
public User getUserByCodePassword(User u) { // 1 根据登陆名称查询登陆用户User existU = ud.getByUserCode(u.getUser_code());// 2 判断用户是否存在.不存在=>抛出异常,提示用户名不存在if (existU == null) {throw new RuntimeException("用户名不存在!"); } // 3 判断用户密码是否正确=>不正确=>抛出异常,提示密码错误if (!existU.getUser_password().equals(u.getUser_password())) {throw new RuntimeException("密码错误!"); } // 4 返回查询到的用户对象return existU; }
public User getByUserCode(final String usercode) { //CriteriaDetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc); if(list != null && list.size()>0){return list.get(0); }else{return null; } }
위 내용은 SSH의 세 가지 주요 프레임워크 통합에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!