好久没用过struts2和Hibernate框架了,闲来无事,搭建一个简单SSH框架,回顾学习下。
一、SSH整合需要的包
二、项目结构
三、配置文件
1.spring配置文件(放在src目录下,或者重新创建一个名为“config”ResourceFolder )
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" 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/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.gs"></context:component-scan>
<!-- 引入jdbc配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- qa数据源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.qa.url}" />
<property name="user" value="${jdbc.qa.user}" />
<property name="password" value="${jdbc.qa.password}" />
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="5"/>
<property name="acquireRetryDelay" value="1000" />
<property name="autoCommitOnClose" value="true" />
</bean>
<!-- dev数据源配置 -->
<!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.dev.url}" />
<property name="user" value="${jdbc.dev.user}" />
<property name="password" value="${jdbc.dev.password}" />
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="2"/>
<property name="initialPoolSize" value="2"/>
<property name="acquireRetryDelay" value="1000" />
<property name="autoCommitOnClose" value="false" />
</bean> -->
<!-- 持久层使用jdbcTemplate模板 -->
<!-- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean> -->
<!-- 配置我们的回话工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- hibernate映射配置
<property name="mappingLocations">
<list>
<value>classpath:cn/itcast/entity/*.hbm.xml</value>
</list>
</property>
-->
<property name="packagesToScan" value="com.gs.bean" /><!-- 配置需要扫描的包路径,在该包下,所有的类注解配置都会被扫描 -->
<!-- <property name="annotatedClasses">
<list>
<value>com.gs.bean.Users</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<!-- MySQL的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<!-- <prop key="javax.persistence.validation.mode">none</prop> -->
<!-- 必要时在数据库新建所有表格 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- 配置current session的上下文环境,方便我们调用sessionFactory获取当前线程统一个session对象 -->
<prop key="current_session_context_class">thread</prop>
<!-- 用更漂亮的格式显示sql语句-->
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class=" org.springframework.orm.hibernate4.HibernateTemplate">
<!-- 通过工厂获得Session,操作PO类 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
2.jdbc配置(位置同spring配置)
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.qa.url=jdbc:oracle:thin:@******
jdbc.qa.user=
jdbc.qa.password=
jdbc.dev.url=jdbc:oracle:thin:@******
jdbc.dev.user=
jdbc.dev.password=
配置下面一个就可以
jdbc.qa.url=jdbc:oracle:thin:@******
jdbc.qa.user=
jdbc.qa.password=
3.struts.xml(位置同spring配置)
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Struts 2配置文件的DTD信息 -->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<!-- Struts 2配置文件的根元素 -->
<struts>
<include file="struts-default.xml" />
<!-- 配置了系列常量 -->
<!-- <constant name="struts.i18n.encoding" value="GBK"/> -->
<!-- <constant name="struts.devMode" value="true"/> -->
<package name="leaf" extends="struts-default" namespace="/test">
<!-- 定义处理用户请求的Action -->
<action name="hereAction" class="indexAction">
<result name="success">/jsp/hello.jsp</result>
</action>
</package>
</struts>
4.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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_001</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>
<!-- <filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
<!-- struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<!-- <init-param>
<param-name>config</param-name>
<param-value>/struts.xml</param-value>
</init-param> -->
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring listener-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
</web-app>
5.配置文件目录
四、代码
1.dao层
package com.gs.dao;
import java.util.List;
import com.gs.bean.Users;
public interface UsersDAO {
public Users getUserById(Long id) throws Exception;
//public List<Users> queryUserList() throws Exception;
}
package com.gs.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.gs.bean.Users;
import com.gs.dao.UsersDAO;
@Repository
public class UsersDAOImpl implements UsersDAO {
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public Users getUserById(Long id) throws Exception {
return (Users) hibernateTemplate.get(Users.class, id);
}
/*
@Override
public List<Users> queryUserList() throws Exception {
return null;
}
*/
}
2.service层
package com.gs.service;
import com.gs.bean.Users;
public interface UsersService {
public Users getUserById(Long id);
}
package com.gs.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gs.bean.Users;
import com.gs.dao.UsersDAO;
import com.gs.service.UsersService;
@Service
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersDAO usersDAO;
@Transactional(readOnly=true)
@Override
public Users getUserById(Long id) {
try {
return usersDAO.getUserById(id);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3.action层
package com.gs.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.gs.bean.Users;
import com.gs.service.UsersService;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class IndexAction extends ActionSupport {
@Autowired
private UsersService usersService;
private static final long serialVersionUID = 1L;
public String execute(){
Users u = usersService.getUserById(Long.parseLong("8807670604"));
System.out.println(u);
System.out.println("Here is IndexAction.....");
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("user", u);
return "success";
}
}
4.bean(实体类)
package com.gs.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
public Users() {
}
@Id
@Column(name="user_id")
public Long userId;
@Column(name="login_name")
public String loginName;
@Column(name="password")
public String password;
@Column(name="email_addr")
public String emailAddr;
@Column(name="mobile_num")
public String mobileNum;
@Column(name="reg_status")
public String regStatus;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmailAddr() {
return emailAddr;
}
public void setEmailAddr(String emailAddr) {
this.emailAddr = emailAddr;
}
public String getMobileNum() {
return mobileNum;
}
public void setMobileNum(String mobileNum) {
this.mobileNum = mobileNum;
}
public String getRegStatus() {
return regStatus;
}
public void setRegStatus(String regStatus) {
this.regStatus = regStatus;
}
@Override
public String toString() {
return "Users [userId=" + userId + ", loginName=" + loginName
+ ", password=" + password + ", emailAddr=" + emailAddr
+ ", mobileNum=" + mobileNum + ", regStatus=" + regStatus + "]";
}
}
6.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.net.URLEncoder" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:wb="http://open.weibo.com/wb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta property="wb:webmaster" content="34025854146b6a59" />
<title>Insert title here</title>
</head>
<body>
Here is my want!
<table>
<tr>
<td>ID</td>
<td>LoginName</td>
<td>Email</td>
<td>Phone</td>
</tr>
<tr>
<td>${user.userId}</td>
<td>${user.loginName}</td>
<td>${user.emailAddr}</td>
<td>${user.mobileNum}</td>
</tr>
</table>
</body>
</h
五、测试
访问:http://localhost:8080/ssh_001/test/hereAction
结果:
六、结语
上面就是简单的ssh框架搭建过程,struts2、hibernate4 很多东西都没有详细描述,后面有机会在学习下,详细补充一下!
需要下载jar 包可以去http://mvnrepository.com 这个网站。