引述
SSH,是最简单的Struts2+Spring3+Hibernate3 数据库使用的是[MySQL。分别列出整合需要的jar 包.
** struts2.5**:
asm-5.1.jar
asm-commons-5.1.jar
asm-tree-5.1.jar
commons-fileupload-1.3.2.jar
commons-io-2.4.jar
commons-lang-2.4.jar
commons-lang3-3.4.jar
commons-logging-1.1.3.jar
freemarker-2.3.23.jar
javassist-3.20.0-GA.jar
json-lib-2.3-jdk15.jar
list.txt
log4j-api-2.7.jar
log4j-core-2.3.jar
ognl-3.1.12.jar
slf4j-api-1.7.12.jar
struts2-convention-plugin-2.5.10.1.jar
struts2-core-2.5.10.1.jar
struts2-json-plugin-2.5.10.1.jar
struts2-spring-plugin-2.5.10.1.jar
Hibernate5:
antlr-2.7.7.jar
cdi-api-1.1.jar
classmate-1.3.0.jar
dom4j-1.6.1.jar
el-api-2.2.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.2.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.0.Final.jar
javassist-3.20.0-GA.jar
javax.inject-1.jar
jboss-interceptors-api_1.1_spec-1.0.0.Beta1.jar
jboss-logging-3.3.0.Final.jar
jsr250-api-1.0.jar
list.txt
mysql-connector-java-5.1.7-bin.jar
spring 4.3.8
aopalliance.jar
aspectjweaver.jar
commons-logging-1.1.1.jar
list.txt
spring-aop-4.3.8.RELEASE.jar
spring-aspects-4.3.8.RELEASE.jar
spring-beans-4.3.8.RELEASE.jar
spring-context-4.3.8.RELEASE.jar
spring-context-support-4.3.8.RELEASE.jar
spring-core-4.3.8.RELEASE.jar
spring-expression-4.3.8.RELEASE.jar
spring-instrument-4.3.8.RELEASE.jar
spring-instrument-tomcat-4.3.8.RELEASE.jar
spring-jdbc-4.3.8.RELEASE.jar
spring-jms-4.3.8.RELEASE.jar
spring-messaging-4.3.8.RELEASE.jar
spring-orm-4.3.8.RELEASE.jar
spring-oxm-4.3.8.RELEASE.jar
spring-test-4.3.8.RELEASE.jar
spring-tx-4.3.8.RELEASE.jar
spring-web-4.3.8.RELEASE.jar
spring-webmvc-4.3.8.RELEASE.jar
spring-webmvc-portlet-4.3.8.RELEASE.jar
spring-websocket-4.3.8.RELEASE.jar
配置web.xml
<?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/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SSH2</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>
<!-- struts2 全局过滤器 -->
<filter>
<filter-name>action2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>action2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring framework 配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
配置struts2.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>
<!-- 配置为开发模式 -->
<constant name="struts.devMode" value="false" />
<!-- 把扩展名配置为action -->
<constant name="struts.action.extension" value="action" />
<!-- 把主题配置为simple -->
<constant name="struts.ui.theme" value="simple" />
<constant name="struts.i18n.encoding" value="GBK" />
<package name="struts2" extends="struts-default" namespace="/">
<action name="dgw" class="registerAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
配置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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- jdbc 数据配置 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/wsy_student?useUnicode=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<!-- Action 配置 交给spring来管理-->
<bean id="registerAction" class="action.registerAction" scope="prototype">
<property name="indexService" ref="indexService"></property>
</bean>
<!-- DAO类 -->
<bean id="myDao" class="ssh.daoimpl.UserDaoimpl" scope="prototype">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<!-- Services类 -->
<bean id="indexService" class="ssh.serviceimpl.IndexServiceImpl" scope="prototype">
<property name="dao" ref="myDao"></property>
</bean>
<!-- 会话工厂 -->
<bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置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.connection.autocommit">false</prop>
<!-- <prop key="current_session_context_class">thread</prop> -->
<!-- 开机自动生成表 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<!-- 路径错了容易出现 erros create 。。。。。 -->
<value>ssh/entity/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
采用最新的SSH配置需要配置log,避免输出警告
- log4j.properties
<?xml version="1.0" encoding="UTF-8"?>
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
- log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
在环境搭建完成以后编写测试文件
package test;
import org.hibernate.SessionFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class testdemo {
@SuppressWarnings("resource")
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
SessionFactory bean = (SessionFactory) context.getBean("mysessionFactory");
System.out.println(bean);
}
}
进行项目分层
- 实体User
// default package
// Generated 2017-6-3 22:03:50 by Hibernate Tools 5.2.3.Final
package ssh.entity;
import java.util.Date;
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String password;
private Integer qqnumber;
private String username;
private Date time;
public User() {
}
public User(String password, Integer qqnumber, String username, Date time) {
this.password = password;
this.qqnumber = qqnumber;
this.username = username;
this.time = time;
}
@Override
public String toString() {
return "User [id=" + id + ", password=" + password + ", qqnumber="
+ qqnumber + ", username=" + username + ", time=" + time + "]";
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getQqnumber() {
return this.qqnumber;
}
public void setQqnumber(Integer qqnumber) {
this.qqnumber = qqnumber;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getTime() {
return this.time;
}
public void setTime(Date time) {
this.time = time;
}
}
- 实体映射
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generated 2017-6-3 22:03:50 by Hibernate Tools 5.2.3.Final --><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-access="property"
default-cascade="none" default-lazy="true">
<!-- 如果是hibernate tools 自动生成的hbm 容易出现 exception is org.hibernate.MappingException: -->
<class catalog="wsy_student" dynamic-insert="false"
dynamic-update="false" mutable="true" name="ssh.entity.User"
optimistic-lock="version" polymorphism="implicit"
select-before-update="false" table="user">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned" />
</id>
<property generated="never" lazy="false" name="password"
optimistic-lock="true" type="string" unique="false">
<column name="password" />
</property>
<property generated="never" lazy="false" name="qqnumber"
optimistic-lock="true" type="java.lang.Integer" unique="false">
<column name="qqnumber" />
</property>
<property generated="never" lazy="false" name="username"
optimistic-lock="true" type="string" unique="false">
<column name="username" />
</property>
<property generated="never" lazy="false" name="time"
optimistic-lock="true" type="date" unique="false">
<column length="10" name="time" />
</property>
</class>
</hibernate-mapping>
- DAO层实现类
package ssh.daoimpl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import ssh.dao.UserDao;
import ssh.entity.User;
//创建IndexDaoImpl(实现类)实现IndexDao接口
@Transactional
public class UserDaoimpl implements UserDao {
// 在SSH的设计理念:要使用某个实例,那么就定义声明一个对象,然后
// 给它添加set方法(用于spring注入进来)
// 实现不要关注这个实例来自于那里,以及怎么创建,或者它是谁
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("deprecation")
@Override
public List<User> getAllUser() {
// sessionFactory这个实例可以自己按常规的hibernate传统写法创建
// 也可以交给spring去托管
/*
* onfiguration cfg = new Configuration().configure(); sessionFactory =
* cfg.buildSessionFactory();
*/
// 获取session
Session session = sessionFactory.getCurrentSession();
// 后面当使用JPA的时候,EntityManager 类似于 Session
List<User> list = session.createQuery("from User").list();
for (User user : list) {
System.out.println(user.toString());
}
return list;
}
}
- Sevices实现类
package ssh.serviceimpl;
import java.util.List;
import ssh.dao.UserDao;
import ssh.entity.User;
import ssh.service.IndexService;
//创建IndexServiceImpl(实现类)实现IndexService接口
public class IndexServiceImpl implements IndexService {
// dao实例使用注入方式
private UserDao dao;
// 用于注入使用
public void setDao(UserDao dao) {
this.dao = dao;
}
// 本类应该编写业务逻辑的代码,
// 但本例没有业务逻辑,就不用写。
// 访问数据库的代码,不会出现在service这一层
// 交给dao来操作数据库
@Override
public List<User> getAllUser() {
// 进行其它的业务逻辑操作,比如增加多一个选项,是否过期
// 本例不需要
// ....
List<User> list = dao.getAllUser();
return list;
}
}
- Action 实现类 这里采用的spring来管理的action的实例,主要可以进行aop加强操作
package action;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import ssh.entity.User;
import ssh.service.IndexService;
public class registerAction extends ActionSupport{
//声明service,但不给它创建具体的实现类的实例,
private IndexService indexService;
//添加set()方法
public void setIndexService(IndexService indexService) {
this.indexService = indexService;
}
/**
* //编写execute()方法
*/
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
List<User> list = indexService.getAllUser();
ActionContext context = ActionContext.getContext();
context.put("userlist", list);
return ActionSupport.SUCCESS;
}
}
- jsp显示层
<%@ page language="Java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>??</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:iterator begin="0" step="1" var="log" value="userlist">
<table>
<tbody>
<tr>
<td>
<s:property value="#log.username"/>
</td>
</tr>
</tbody>
</table>
</s:iterator>
</body>
</html>
网友评论