标签:比较 autowired jdbc 4.0 ati lis package 提交 tco
前言
SSH不是一个框架,而是多个框架(struts+spring+hibernate)的集成,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活、易于扩展的多层Web应用程序。
集成SSH框架的系统从职责上分为四层:表示层、业务逻辑层、数据持久层和域模块层(实体层)。
Struts作为系统的整体基础架构,负责MVC的分离,在Struts框架的模型部分,控制业务跳转,利用Hibernate框架对持久层提供支持。Spring一方面作为一个轻量级的IoC容器,负责查找、定位、创建和管理对象及对象之间的依赖关系,另一方面能使Struts和Hibernate更好地工作。
使用MyEclipse整合SSH三大框架,并实现一个模拟用户注册的Demo,对应版本:
Struts版本:2.1;
Spring版本:3.1;
Hibernate版本:3.3;
注意:支持action的包名必须是“action”,且action类必须是以Action结尾,即形如XxxAction这种形式,如上图中所示
CREATE DATABASE sshdemo; CREATE table t_user( id INT PRIMARY KEY, username VARCHAR(10), password VARCHAR(20) )
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> </struts>
完成上述步骤,三大框架基本就搭建起来了,接下来整合它们。
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- sessionFactory 配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- dataSource的属性会在applicationContext.xml文件中配置,在这里先引用 --> <property name="dataSource" ref="dataSource"></property> <!-- 设置hibernate相关的配置项 --> <property name="hibernateProperties"> <!-- props标签是为了注入Properties这个类型的属性 --> <!-- key必须加上hibernate.前缀 --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- show_sql目的是打印sql语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 美化SQL的打印格式 --> <prop key="hibernate.format_sql">true</prop> <!-- a) create-drop:在执行程序的时候创建数据表,在执行完了之后删除表,实际开发中,常用于测试 b) create:在每次执行程序的时候重新创建数据表 c) update:在执行程序的时候会判断,如果存在,不创建表,否则创建数据表,并且会根据实体类中的属性的增加,而自动增加数据表中的字段(开发环境) d) validate:在执行程序的时候会判断,如果实体类中的属性与表中的字段不一致,那么就报错(生产环境) --> <prop key="hibernate.hbm2ddl.auto">validate</prop> </props> </property> <!-- 配置hibernate的实体类 --> <property name="packagesToScan"> <!--list标签是用来注入String[]类型的属性 ,其值一般是对应的bean包的全限名,而bean包中的类一般又是与数据库中的表对应--> <list> <value>com.beauxie.bean</value> </list> </property> </bean> <!-- 配置 hibernateTemplate模板 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> </bean> <!-- 导入其他的spring配置文件 ,如果都放在一个文件里,会看起来比较臃肿--> <import resource="hibernateContext.xml"/> </beans>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl"> <!--如果直接用value属性,而不用value标签,则需要将“&”转义(&) ,用value标签,<span style="color:#FF0000;">标签中一定不能含有空格、回车,因为它会将空格转换成" "</span>,导致数据库会连接不上,除非重写数据源 --> <value><![CDATA[jdbc:mysql://localhost:3306/sshdemo?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=true]]></value> </property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="acquireIncrement" value="3"></property> <property name="initialPoolSize" value="10"></property> <property name="minPoolSize" value="2"></property> <property name="maxPoolSize" value="10"></property> </bean>
<!-- 配置spring的扫描器,然后给我们的类加上spring组件注解,就可以实现bean的自动载入--> <context:component-scan base-package="com.beauxie.action,com.beauxie.service,com.beauxie.dao"> </context:component-scan>
至此ssh三大框架环境搭建完毕,接下来是在ssh框架基础上实现用户注册
<%@ page language="java" import="java.util.*" 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">
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath }/user/regist" method="POST">
<!-- 也可以使用user.username自动装入user属性,但在这里不是重点,所以就在后台手动获取其值-->
用户名:<input type="text" name="username"><br> 密
码:<input type="password" name="password"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
package com.beauxie.bean;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Beauxie
* 在这里User的属性应当与t_user表中的字段相同,
* 否则就需要手动为不相同的属性指定对应表中的字段
*/
@Entity//映射数据库表
@Table(name="t_user")//不加这个注解,默认对应的是user表
public class User {
@Id//对应t_user表中的主键
private int id;//用户ID
private String username;//用户名
private String password;//密码
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.beauxie.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.beauxie.bean.User;
/**
* @author Beauxie
* Dao层,对数据库进行操作
*/
@Repository//这个属性对应的是持久层(一般为Dao层),说明交给spring管理,而对应的包下的类名也会有一个"S"
public class UserDao {
@Autowired//自动注入,不需要设值,因为在spring配置文件中已经配置过
private HibernateTemplate template;
/**
* 用户注册,即向表中添加一条新的记录
* @param user
*/
public void addUser(User user){
//往数据库中添加一条数据,一句话就可以搞定
template.save(user);
}
}
package com.beauxie.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beauxie.bean.User;
import com.beauxie.dao.UserDao;
/**
* @author Beauxie
* Service层
*/
@Service//这个属性对应的是业务层一般为Service层),说明交给spring管理,而对应的包下的类名也会有一个"S"
public class UserService {
@Autowired//同样是自动注入
private UserDao userDao;
public void addUser(User user){
//调用Dao层的addUser方法
userDao.addUser(user);
}
}
package com.beauxie.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.beauxie.bean.User;
import com.beauxie.service.UserService;
/**
* @author Beauxie
*
*/
@Controller//用于标注控制层组件
@Namespace("/user")//url前缀
@Scope("prototype")//Action默认是单例,但实际开发中,一般是多例,因为一般一个Action可能会对应多个不同的请求
//@ParentPackage("struts-default")//继承特定的package,默认是“struts-default”,因此可以省略不写
@Results({
@Result(name="registSuccess",location="/msg.jsp")
})
public class UserAction {
@Autowired//自动注入
private UserService service ;
//struts默认拦截“.action以及不加任何后缀”
@Action(value="regist")//访问:/user/regist.action 或 /user/regist
public String regist(){
//获取request
HttpServletRequest request = ServletActionContext.getRequest();
//获取表单提交的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装userBean
User user = new User();
user.setId(1000);
user.setUsername(username);
user.setPassword(password);
//调用service层的方法,向数据库中增加一条记录
service.addUser(user);
//将提示信息存入request域中,用以前台显示
request.setAttribute("msg", "恭喜您,注册成功!<br>注册名:"+username);
return "registSuccess";
}
}
<%@ page language="java" import="java.util.*" 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">
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
${msg }
</body>
</html>
到此这个简单的案例就已经结束了,关于表单提交数据校验、以及乱码问题并未涉及,后续应该会更新吧、、、
1.三大框架的整合,应该先引入每个框架以后,再整合;
2.一定要记得导入数据库jar包;
3.Action类应该要放在包名为"action"的包下,并且类名应当要以Action结尾,形如“XxxAction”;
4.在配置Hibernate时,一定要导入支持“@Entity”注解的jar包;
5.可以再struts.xml文件中定义struts拦截的请求类型,默认为.action与不加后缀
6.可以再web.xml文件中定义struts过滤器的过滤类型,默认为*.action,应当改为/*;
7.在applicationContext.xm文件中需要配置:sessionFactory、hibernate的实体类、hibernateTemplate模板 、数据源dataSource、spring扫描器五部分(包含hibernateContext.xml);
8.各个类中一定要加上对应的注解,以及Action中的方法上也要加注解。
实例源码下载:http://download.csdn.net/detail/beauxie/9665583
使用MyEclipse整合ssh(Struts、Spring、Hibernate)三大框架(环境搭载+实例源码下载)
标签:比较 autowired jdbc 4.0 ati lis package 提交 tco
原文地址:http://blog.csdn.net/beauxie/article/details/52937644