SSH는 JavaWeb의 고전적인 프레임워크입니다. 100% 사람들이 SSH 프레임워크를 알아야 한다고 말할 수는 없지만, 대부분의 회사에서는 프레임워크에 관해서라면 ssh를 언급하겠습니다. 매우 간단한 등록 예제를 사용합니다. 프레임워크를 통합할 때는 통합하기 전에 각 프레임워크를 별도로 테스트하는 데 주의해야 합니다. 그렇지 않으면 통합 후 문제를 해결하기가 어렵습니다.
환경: windows + MyEclipse + JDK1.7 + Tomcat7 + MySQL
코드는 테스트를 거쳤습니다. 오류가 있는 경우 군데군데 명확하게 설명하지 않았기 때문일 수 있으니 메시지를 남겨주세요.
1. 통합 원리
2. 가이드 패키지(41)
1. hibernate persist api java 지속성 사양(인터페이스)
(3) 데이터베이스 드라이버
2.스트럿츠2
(1) struts-blank.war/WEB-INF/lib/*
참고: javassist-3.18.1-GA.jar 패키지와 최대 절전 모드 간의 중복(상위 버전만 유지)
( 2) struts 통합 스프링 플러그인 패키지
참고: 이 패키지를 가져오면 struts2가 스프링 컨테이너를 찾을 때 시작됩니다. 찾을 수 없으면 예외가 발생합니다
3. spring
(1) 기본: 4+2
코어 | 컨텍스트 | 로깅 | log4j
<?xml version="1.0" encoding="UTF-8"?><beans><bean></bean></beans>
2. 프로젝트로 시작하도록 spring 구성 )
<!-- 让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>
4. struts2를 별도로 구성합니다
1. struts2 기본 구성 파일(struts.xml)을 구성합니다.
<?xml version="1.0" encoding="UTF-8"?> nbsp;struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package><action><result>/success.jsp</result></action></package></struts>2. struts2 코어 필터를 web.xml
<!-- 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>으로 구성합니다. 5 . struts2를 spring과 통합 1. 패키지 가져오기(이미 가져옴) struts2-spring-plugin-2.3.24.jar 2. 구성 상수 31번째 줄부터 시작하는 기본 구성 파일을 보고 변수를 찾습니다. 구성됩니다.
### 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
Spring은 액션의 수명주기를 완벽하게 관리합니다. Spring의 기능만 Action에 적용됩니다.
4. 통합 솔루션 2: Spring은 액션 생성과 어셈블리를 담당합니다. (권장) ApplicationContext.xml:<!-- # struts.objectFactory = spring 将action的创建交给spring容器 struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant></constant>struts.xml:
<!-- 整合方案1:class属性上仍然配置action的完整类名 struts2仍然创建action,由spring负责组装Action中的依赖属性 --><action><result>/index.htm</result><result>/login.jsp</result></action>
6. 구성 별도로 최대 절전 모드
1. 엔터티 클래스 및 orm 메타데이터 가져오기
예: User .java <!-- action --><!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 --><bean><property></property></bean>
User. hbm.xml:
<!-- 整合方案2:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action><result>/index.htm</result><result>/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 + "]"; } }
七、spring整合hibernate
1.整合原理
将sessionFactory对象交给spring容器管理
2.在spring中配置sessionFactory
(1)配置方案一:(了解)
<!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 --><bean><property></property></bean>
(2)配置方案二:(推荐)
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 --><bean><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property></property><!-- 配置hibernate基本信息 --><property><props><!-- 必选配置 --><prop>com.mysql.jdbc.Driver</prop><prop>jdbc:mysql:///crm_32</prop><prop>root</prop><prop>1234</prop> <prop>org.hibernate.dialect.MySQLDialect</prop><!-- 可选配置 --><prop>true</prop><prop>true</prop><prop>update</prop></props></property><!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 --><property></property></bean>
八、spring整合c3p0连接池
1.配置db.properties
jdbc.jdbcUrl=jdbc:mysql:///xyp_crm jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123456
2.引入连接池到spring中
<!-- 读取db.properties文件 --><property-placeholder></property-placeholder><!-- 配置c3p0连接池 --><bean><property></property><property></property><property></property><property></property></bean>
3.将连接池注入给SessionFactory
<bean><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property></property></bean>
九、spring整合hibernate环境操作数据库
1.Dao类创建:继承HibernateDaoSupport
注意:项目中要确保使用统一版本。
//HibernateDaoSupport 为dao注入sessionFactorypublic class UserDaoImpl extends HibernateDaoSupport implements UserDao {
2.hibernate模板的操作
(1)execute
@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; } });</user>
(2)findByCriteria
//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; }</user></user>
3.spring中配置dao
<!-- Dao --><bean><!-- 注入sessionFactory --><property></property></bean>
十、spring的aop事务
1.准备工作
<!-- 核心事务管理器 --><bean><property></property></bean>
2.xml配置aop事务
(1)配置通知
<!-- 配置通知 --><advice> <attributes><method></method> <method></method> <method></method> <method></method> <method></method> <method></method> <method></method> <method></method> </attributes> </advice>
(2)配置织入
<!-- 配置将通知织入目标对象 配置切点 配置切面 --><config> <pointcut></pointcut> <advisor></advisor> </config>
3.注解配置aop事务
(1)开启注解事务
<!-- 开启注解事务 --><annotation-driven></annotation-driven>
(2)Service类中使用注解
@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); }
十一、扩大session作用范围
1.配置filter
为了避免使用懒加载时出现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>
十二、练习:用户登录
1.struts.xml核心配置
<struts><!-- # struts.objectFactory = spring 将action的创建交给spring容器 struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant></constant><package><global-exception-mappings><exception-mapping></exception-mapping></global-exception-mappings> <!-- 整合方案:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action><result>/index.htm</result><result>/login.jsp</result></action></package></struts>
2.Action代码
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; } }</user>
2.Service核心代码
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; }
3.Dao核心代码
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; } }</user></user>
위 내용은 SSH의 세 가지 주요 프레임워크 통합에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

드림위버 CS6
시각적 웹 개발 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
