ssh2框架整合+Maven+详细配置、多种方式介绍,中间碰到问题与注意点,部分已有指出。
关于Eclipse中使用Maven详见http://blog.csdn.net/it_faquir/article/details/54562242
步骤一
导入必备junit、javax.servlet相关jar包,maven配置如下:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
由于使用MySQL,因此需要导入相应驱动包,Maven配置如下:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
步骤二
struts2环境配置
maven导入jar包
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.10.1</version>
</dependency>
得到jar包:
配置log文件log4j.properties.与根目录或者config或者resources文件下。
log4j内容
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=G:\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
在web.xml中配置struts2核心过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
添加struts.xml配置文件,与resources或者根目录下
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<package name="ssh" namespace="/" extends="struts-default">
</package>
</struts>
Spring环境配置
maven配置:
<!-- http://projects.spring.io/spring-framework/ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
得到jar包:
在resource或者更目录下配置Spring核心配置文件applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
</beans>
在web.xml文件中配置Spring的监听
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Hibernate环境配置(hibernate.cfg.xml配置的方式)
maven配置:
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
得到jar包:
在resources或者根目录下配置hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1 数据库基本四项配置 -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/dbtest?characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true</property>
<property name="connection.username">root</property>
<property name="connection.password">asd123asd</property>
<!-- 2方言 -->
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 3SQL相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 取消bean校验 -->
<property name="javax.persistence.validation.mode">none</property>
<!-- 添加映射文件 -->
</session-factory>
</hibernate-configuration>
基本环境已经配置好
这里以实现用户名密码登录功能为例,展示ssh2整合。
步骤三
hibernate 与 Spring整合
在Spring 和 Hibernate 的整合时需要了解一下三个对象:
- HibernateTemplate:相当于Hibernate的session可以直接操作PO类,依赖于SessionFactory。
- LocalSessionFactoryBean:获得SessionFactory。
- HibernateTransactionManager:Hibernate的事务管理器。
Spring 和 Hibernate 的整合,需要再添加一个支持整合的JAR包spring-orm-xxx.RELEASE.jar包,
该JAR包。其maven配置:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
以查询用户信息为例
数据库中有表user,字段有:id、username、password
编写一个与数据库映射的实体类user
public class User {
private Integer id;
private String username;
private String password;
public User(){}
... get/set
}
对应的映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-4-29 20:08:33 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="prv.hgs.domain.User" table="USER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" />
</property>
</class>
</hibernate-mapping>
这里仅以用户id查找为例
(方式一) 保留hibernate.cfg.xml方式进行整合。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1 数据库基本四项配置 -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/dbtest?characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true</property>
<property name="connection.username">root</property>
<property name="connection.password">asd123asd</property>
<!-- 2方言 -->
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 3SQL相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 取消bean校验 -->
<property name="javax.persistence.validation.mode">none</property>
<!-- 添加映射文件 -->
<mapping resource="prv/hgs/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
实现DAO层:
public interface UserDao {
User findUserById(Integer id);
}
UserImp实现
@Component
public class UserImp implements UserDao{
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public User findUserById(Integer id) {
return hibernateTemplate.get(User.class, id);
}
}
Spring配置文件,进行配置sessionFactory、hibernateTemplate
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="prv.hgs"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"
>
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
进行测试
@Test
public void testUser() {
ApplicationContext content = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao uDao = (UserDao) content.getBean("userImp");
System.out.println(uDao.findUserById(1));
}
可以正常得到输出结果
(方式二) 利用Spring配置文件继续配置
方式一保留了hibernate原始配置方式,但在实际整合过程中,通常使用Spring进行配置,去掉Hibernate.cfg.xml。如下实现
除了使用方式一中的hibernateTemplate获取方式,也可以userImp改成继承HibernateDaoSupport方式,并删除hibernateTemplate的bean,其具体实现如下:(实际中方式一中hibernateTemplate的获取方式较为常用)。
public class UserImp extends HibernateDaoSupport implements UserDao{
@Override
public User findUserById(Integer id) {
return this.getHibernateTemplate().get(User.class, id);
}
}
在配置中可以加入线程池,这里使用阿里巴巴的druid
需要导入相应jar包,其Maven配置:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
其applicationContext.xml配置如下
<?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:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="prv.hgs">
</context:component-scan>
<!-- load in properties file -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<!-- druid配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<!-- <property name="maxIdle" value="${maxIdle}"></property> -->
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 其它hibernate配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
<property name="mappingResources" value="prv/hgs/domain/User.hbm.xml" />
</bean>
<!-- 设置HibernateDaoSupport抽象类,使实现类无需再每个注入 -->
<bean id="hibernateDaoSupport"
class="org.springframework.orm.hibernate5.support.HibernateDaoSupport"
abstract="true">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userImp" class="prv.hgs.dao.imp.UserImp" parent="hibernateDaoSupport"/>
</beans>
由于spring配置支持占位符的方式进行配置因此上面对数据库及池的配置都使用了占位符,可以方便我们对配置的更改。还需要在Resources或者根目录下创建一个jdbc.properties的文件,其内容如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
#定义连接的URL地址,设置编码集,时间域,允许多条SQL语句操作œ
jdbc.url=jdbc:mysql://localhost:3306/thcardb?characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true
#jdbc:mysql://localhost:3306/thcardb?characterEncoding=utf-8&serverTimezone=UTC&allowMultiQueries=true
jdbc.username=root
#jdbc.password=asd123asd
jdbc.password=StrLDvcH92s8tsn3
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
再继续测试,测试代码与方式一致。依然通过,正常打印出结果。意味着配置通过。
Spring与Struts2整合
Spring与Struts2的整合需要用到struts2-spring-plugin.jar,其Maven配置如下:
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-spring-plugin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.10.1</version>
</dependency>
在struts2-spring-xxx.jar下包含一个struts-plugin.xml文件,该文件是个插件配置文件,打开可以找到如下配置信息
<constant name="struts.objectFactory" value="spring" />
上面配置用于配置struts2框架使用工厂创建自己的Action实例,如果value的值设置成spring,那么将由Spring框架来创建Action实例。
由于加入struts2-spring-plugin.jar 还需要加入如下几个相关jar包,maven配置如下。否则会报ClassNotFoundException
<!-- http://projects.spring.io/spring-framework/ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
Service层实现
和dao层实现基本差不多。
UserService接口实现,基本和UserDao一样
public interface UserService {
User findUserById(Integer id);
}
UserServiceImp实现,这里为了方便,就直接使用注解了,无需在配置文件中配置bean。
@Service
public class UserServiceImp implements UserDao {
@Autowired
private UserDao userDao;
@Override
public User findUserById(Integer id) {
return userDao.findUserById(id);
}
}
action的实现
@Controller
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@Override
public User getModel() {
return user;
}
@Autowired
private UserServiceImp userServiceImp;
public String login() {
// 这里仅举例,以数据库中第一个用户为例
User realUser = userServiceImp.findUserById(1);
if (realUser.getUsername().equals(user.getUsername()) && realUser.getPassword().equals(user.getPassword())) {
System.out.println("login success");
return SUCCESS;
} else{
return ERROR;
System.out.println("login error");
}
}
}
struts.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<package name="default" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="user_*" class="prv.hgs.action.UserAction"
method="{1}">
<result>/index.jsp</result>
<result name="success">/WEB-INF/jsp/success.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>
如果你想使用Action创建交予Spring的情况,则只需将struts.xml的class改成userAction即可。
<action name="user_*" class="userAction"
method="{1}">
<result>/index.jsp</result>
<result name="success">/WEB-INF/jsp/success.jsp</result>
<result name="error">/index.jsp</result>
</action>
NOTE:在struts2.5及以上版本默认不支持通配符,所以要在配置文件中添加全局通配符配置。即
<global-allowed-methods>regex:.*</global-allowed-methods>
否则会报There is no Action mapped for namespace [/] and action name
[user_login] associated with context path [/SSHIntegration]. 错误。
测试:
jsp界面
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<form action="<%=path%>/user_login" method="post">
用户名:<input type="text" name="username" />
密码:<input type="text" name="password" />
<input type="submit" />
</form>
</body>
</html>
在WEB-INF下建立jsp文件,并创建success.jsp
...
<body>
Login Success
</body>
...
将应用部署到服务器上运行测试:
运行截图
其中用户名与密码与数据库相同。则成功登陆
控制台打印出:
Hibernate:
select
user0_.ID as ID1_0_0_,
user0_.USERNAME as USERNAME2_0_0_,
user0_.PASSWORD as PASSWORD3_0_0_
from
USER user0_
where
user0_.ID=?
success
说明SSH2整合成功。
最终Maven的pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>priv.hgs</groupId>
<artifactId>SSHIntegration</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SSHIntegration Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-spring-plugin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5</version>
</dependency>
<!-- http://projects.spring.io/spring-framework/ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- http://projects.spring.io/spring-framework/ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.22.0-CR1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
</dependencies>
<build>
<finalName>SSHIntegration</finalName>
</build>
</project>