软件要求:jdk7+eclipse+tomcat+PostgreSQL
SSH 环境配置:
一:配置hibernate
1)定义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 基本4项 -->
<property name="connection.driver_class">
org.postgresql.Driver
</property>
<property name="connection.url">
jdbc:postgresql://localhost:5432/chapter17
</property>
<property name="connection.username">postgres</property>
<property name="connection.password">123456</property>
<!-- 2 方言 -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- 3 sql -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 4 取消bean校验 -->
<property name="javax.persistence.validation.mode">none</property>
<!-- 5整合c3p0 -->
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- 使用注解方式 -->
<mapping class="cn.itcast.domain.User"/>
</session-factory>
</hibernate-configuration>
二:配置spring管理hibernate。
配置applicationContext.xml文件(注:xml 文件可以相互引用)
主要ApplicationContext代码
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 使用hibernate.cfg.xml -->
<!-- <import resource="applicationContext1.xml"/> -->
<!-- 不使用hibernate.cfg.xml -->
<!-- <import resource="applicationContext2.xml"/> -->
<!-- 使用注解方式 -->
<import resource="applicationContext3.xml"/>
</beans>
另外注解方式对应的的ApplicationContext3 配置
<?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="true"></constant>
<!-- 开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<package name="ssh" namespace="/" extends="struts-default">
<!-- action的创建交予Sping -->
<action name="userAction_*" class="userAction" method="{1}">
<result name="add">/success.jsp</result>
</action>
</package>
</struts>
我们先进行后台数据库插入操作。
一:实体和表对应
基本思路,通过给Entity注解,并且设置Table属性,可以将表和Entity一一对应。
@entity,在类之前加上这个表示这个是是对应表的实体类
@Table(name=“t_user”)
package cn.itcast.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User1 {
@Id(表示ID)
@GeneratedValue(strategy=GenerationType.AUTO)(主键生成策略)
private Integer id;
@Column(name="username", length=50)(对应表中的列)
private String username;
private String password;(不写的话,表示默认,如果字符完全一样,那就可以不写)
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
上面的注解后,作用相当于配置User.hbm.xml 文件了。
二:注解dao层
增加@Respository
代码如下
接口层定义方法
package cn.itcast.dao;
import java.util.List;
import cn.itcast.domain.User;
public interface UserDao {
public void saveUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
public User findById(Integer id);
public List<User> findAllUser();
}
定义类方法实现
package cn.itcast.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public void saveUser(User user) {
// TODO Auto-generated method stub
this.hibernateTemplate.save(user);
}
@Override
public void updateUser(User user) {
// TODO Auto-generated method stub
this.hibernateTemplate.update(user);
}
@Override
public void deleteUser(User user) {
// TODO Auto-generated method stub
this.hibernateTemplate.delete(user);
}
@Override
public User findById(Integer id) {
// TODO Auto-generated method stub
return this.hibernateTemplate.get(User.class, id);
}
@Override
public List<User> findAllUser() {
// TODO Auto-generated method stub
return this.hibernateTemplate.find("from User");
}
}
三:注解Service 层
接口方法定义代码:
package cn.itcast.service;
import java.util.List;
import cn.itcast.domain.User;
public interface UserService {
public void saveUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
public User findById(Integer id);
public List<User> findAllUser();
}
实现代码
package cn.itcast.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Transactional
@Override
public void saveUser(User user) {
// TODO Auto-generated method stub
this.userDao.saveUser(user);
}
@Transactional
@Override
public void updateUser(User user) {
// TODO Auto-generated method stub
this.userDao.updateUser(user);
}
@Transactional
@Override
public void deleteUser(User user) {
// TODO Auto-generated method stub
this.userDao.deleteUser(user);
}
@Transactional(readOnly=true)
@Override
public User findById(Integer id) {
// TODO Auto-generated method stub
return this.userDao.findById(id);
}
@Transactional(readOnly=true)
@Override
public List<User> findAllUser() {
// TODO Auto-generated method stub
return this.userDao.findAllUser();
}
}
四:注解Action层
代码如下
package cn.itcast.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Namespace("/")
@ParentPackage("struts-default")
@Controller
public class UserAction extends ActionSupport implements ModelDriven<User>{
/** * */
private static final long serialVersionUID = 1L;
private User user = new User();
public User getModel() {
return this.user;
}
// *****************************
@Autowired
private UserService userService;
@Action(value = "userAction_add", results = { @Result(name = "add", location = "/success.jsp") })
public String add() {
this.userService.saveUser(user);
return "add";
}
}
测试类定义:
package cn.itcast.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
public class AppTest {
@Test
public void demo()
{
User user = new User();
user.setUsername("cherry");
user.setPassword("12345678");
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
xmlPath);
UserService userService = applicationContext.getBean("userService",
UserService.class);
userService.saveUser(user);
}
}
结果如下:
现在:链接前端和spring了
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">
<!-- 监听器 -->
<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>
<!--配置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>
</web-app>
设置好web 容器后,设置struts 相应的action
struts代码
<?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="true"></constant>
<!-- 开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<package name="ssh" namespace="/" extends="struts-default">
<!-- action的创建交予Sping -->
<action name="userAction_*" class="userAction" method="{1}">
<result name="add">/success.jsp</result>
</action>
</package>
</struts>
这时,配置好了前端和后端的动作了,可以直接写好前端,写好前端的action,就可以进行插入操作了
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>添加用户</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/userAction_add" method="post">
用户名:<input type="text" name="username" /> <br/>
密   码:<input type="password" name="password" /> <br/>
<input type="submit" value="添加" />
</form>
</body>
</html>
插入成功页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>成功页面</title>
</head>
<body>
<p>insert successfully</p>
</body>
</html>
在服务器上运行项目,输入地址
http://localhost:8080/AnnotationCom/index.jsp
插入成功的话会出现下面的页面
数据库如下:
代码下载:地址
http://download.csdn.net/detail/u010714901/9680878
总结:对于SSH 整合来说,Spring 才是最重要的那个,因为他是管理者,管理Bean的创建,管理后台中所有的东西。在spring采用注解Annotation来管理的时候,struts.xml 文件需要改action中class属性的值,变成在spring中定义的类的id。
Spring是struts和hibernate的中转站。