SSH框架整合2
Posted helloworldlx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH框架整合2相关的知识,希望对你有一定的参考价值。
===========================================web.xml===================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置OpenSessionInView,需要配置在struts过滤器之前,否则会被过滤掉-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts核心过滤器 -->
<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>
=================================================spring.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<context:annotation-config/>
<!--告知spring要去哪个包找注解-->
<context:component-scan base-package="com.ibeifeng.ssh"/>
<aop:aspectj-autoproxy/>
<bean name="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!--配置数据库信息-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/houserent"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置session信息-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<!--由于这里我们使用的是注解的方式得到属性,因此使用packagesToScan,
若在hibernate中使用hibernate.cfg.xml则在此处就使用mappingResources,
作用是指定从哪个包中查找注解的model-->
<property name="packagesToScan">
<value>com.ssh.model</value>
</property>
<!--配置hibernate属性-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<!--注入sessionFactory-->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--配置事务增强,以及哪些方法使用什么样的规则-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!--*号表示所有的方法都加入事务-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--spring事务的实现是基于AOP方式-->
<aop:config>
<!--定义切入点-->
<aop:pointcut id="allMethod" expression="execution(* com.ssh.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethod"/>
</aop:config>
</beans>
============================================struts.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="true"/>
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<package name="default" extends="struts-default">
<!--使用通配符-->
<action name="*_*" class="{1}Controller" method="{2}">
<result name="success">{2}.jsp</result>
</action>
</package>
</struts>
===================================IBaseDao.java()(BaseDao的接口)=======================================
package com.ssh.dao;
public interface IBaseDao<T> {
public void add(T t);
public void update(T t);
public void delete(int id);
public T load(int id);
// public List<T> list();
}
==============================BaseDao.java()(BaseDao实现类)===========================================
package com.ssh.dao;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T> {
/*BaseDao继承了HibernateDaoSupport,在HibernateDaoSupport中存在setSessionFactory方法可以直接
设置SessionFactory,后面就不需要每次都去获取SessionFactory
* */
@Resource(name = "sessionFactory")
private void setSuperSessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
@Override
public void add(T t) {
this.getHibernateTemplate().save(t);
}
@Override
public void update(T t) {
this.getHibernateTemplate().update(t);
}
@Override
public void delete(int id) {
this.getHibernateTemplate().delete(id);
}
public Class<T> getCla(){
return (Class<T>)(((ParameterizedType)
(this.getClass().getGenericSuperclass()))
.getActualTypeArguments()[0]);
}
@Override
public T load(int id) {
/*由于在load()方法中需要给一个类作为参数,但现在还不知道具体是哪个类,因此需要
一个得到类的方法getCla()
*/
//在这里若使用load()方法需要在web.xml里面配置OpenSessionInView的过滤器,若使用get()则不要
//return this.getHibernateTemplate().get(getCla(),id);
return this.getHibernateTemplate().load(getCla(),id);
}
/*由于在Hibernate5中find()方法以及被取消,所以该段注释掉
@Override
public List<T> list() {
return (List<T>)this.getHibernateTemplate().find("Group");
}
*/
}
===============================IGroupDao.java()(GroupDao的接口)====================================
package com.ssh.dao;
import com.ssh.model.Group;
public interface IGroupDao extends IBaseDao<Group>{
}
================================GroupDao.java()(GroupDao实现类)========================================
package com.ssh.dao;
import com.ssh.model.Group;
import org.springframework.stereotype.Repository;
@Repository
public class GroupDao extends BaseDao<Group> implements IGroupDao {
}
======================================IEmpDao.java()(EmpDao接口)==========================================
package com.ssh.dao;
import com.ssh.model.Employee;
public interface IEmpDao extends IBaseDao<Employee> {
}
========================================EmpDao.java()(EmpDao实现类)==========================================
package com.ssh.dao;
import com.ssh.model.Employee;
public class EmpDao extends BaseDao<Employee> implements IEmpDao {
}
==================================IGroupService.java()(GroupService接口)=================================
package com.ssh.service;
import com.ssh.model.Group;
public interface IGroupService {
public void save(Group group);
public Group load(int id);
//GroupService需要使用哪些方法只要在接口中添加即可
}
============================GroupService.java()(GroupService实现类)======================================
package com.ssh.service;
import com.ssh.dao.IGroupDao;
import com.ssh.model.Group;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class GroupService implements IGroupService {
private IGroupDao groupDao;
@Resource
public void setGroupDao(IGroupDao groupDao) {
this.groupDao = groupDao;
}
@Override
public void save(Group group) {
groupDao.add(group);
}
@Override
public Group load(int id) {
return null;
}
}
=======================GroupController.java()(GroupController实现类)======================================
package com.ssh.controller;
import com.ssh.model.Group;
import com.ssh.service.IGroupService;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
@Controller("groupController")
public class GroupController {
private IGroupService groupService;
//需要保存哪些类的数据,就在这里定义哪些类来接收数据
private Group group;
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@Resource
public void setGroupService(IGroupService groupService) {
this.groupService = groupService;
}
public String add(){
groupService.save(group);
return "success";
}
}
===================================Group.java()(Group实现类)==============================================
package com.ssh.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
public Group(){}
public Group(int id, String name) {
this.id = id;
this.name = name;
}
@Id
@GenericGenerator(name = "increment",strategy = "increment")
@GeneratedValue(generator = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Group{" +
"id=" + id +
", name=‘" + name + ‘‘‘ +
‘}‘;
}
}
=================================Employee.java()(Employee实现类)==========================================
package com.ssh.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name = "t_emp")
public class Employee {
private int id;
private String name;
private String salary;
public Employee(){}
public Employee(int id, String name, String salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Id
@GenericGenerator(name = "increment", strategy = "increment")
@GeneratedValue(generator = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "salary")
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name=‘" + name + ‘‘‘ +
", salary=‘" + salary + ‘‘‘ +
‘}‘;
}
}
==================================add.jsp(路径为:/web/group/add.jsp)==========================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>add</title>
</head>
<body>
<form method="post" action="group_add">
组名:<input type="text" name="group.name">
<input type="submit" value="保存">
</form>
</body>
</html>
以上是关于SSH框架整合2的主要内容,如果未能解决你的问题,请参考以下文章