SSH配置(三)-Spring配置

一、Spring配置

Spring包:hibernate-release-4.2.1.Final.zip

1、在WebContent->WEB-INF->lib下导入Spring所需jar包

路径:spring-framework-3.2.2.RELEASE\libs

另:还要导入struts2的spring插件struts2-spring-plugin-2.3.14.jar:


2、在src下添加dao,service的接口文件及实现类文件

①添加dao的接口及实现类文件


CommonDao.java代码:

import java.util.HashMap;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public interface CommonDao {

	public void setSupperSessionFactory(SessionFactory sessionFactory);
		
	public String save(Object object);
	
	public void update(Object object);
	
	public void delete(Object object);
	
	public void delete(Class clazz, Serializable id);
	
	public <T>T get(Class<T> clazz, Serializable id);
	
	public List queryList(String hsql, HashMap<String, Object> params);
	

}

CommonDaoImpl.java代码:

package com.jjh.ssh.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.jjh.ssh.dao.CommonDao;

@Repository
public class CommonDaoImpl implements CommonDao {

	private SessionFactory sessionFactory;
	
	@Override
	@Resource(name="sessionFactory")
	public void setSupperSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public String save(Object object) {
		return (String)getSession().save(object);
	}

	@Override
	public void update(Object object) {
		getSession().update(object);
	}

	@Override
	public void delete(Object object) {
		getSession().delete(object);
	}

	@Override
	public void delete(Class clazz, Serializable id) {
		Object o = getSession().load(clazz, id);
		getSession().delete(o);
	}

	@Override
	public <T> T get(Class<T> clazz, Serializable id) {
		Object o = getSession().get(clazz,id);
		return (T)o; 
	}

	@Override
	public List queryList(String hsql, HashMap<String, Object> params) {
		Query q = createQuery(hsql, params);
		List l = q.list();
		return l;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Query createQuery(final String hsql, final HashMap<String, Object> params){
		Query q = getSession().createQuery(hsql);
		String[] keys = q.getNamedParameters();
		if(null != keys && null != params){
			for(String key : keys){
				if(!params.containsKey(key)){
					throw new RuntimeException("没有设置query语句中参数"+key+"的值");
				}
				Object v = params.get(key);
				q.setParameter(key, v);
			}
		}
		return q;
	}

}

②添加service的接口及实现类文件


UserService.java代码:

package com.jjh.ssh.service;

import java.util.List;

import com.jjh.ssh.model.TaUser;

public interface UserService {
	
	public void saveUser(TaUser user)throws Exception;
	
	public void deleteUser(TaUser user)throws Exception;
	
	public void deleteUser(String uid)throws Exception;
	
	public List<TaUser> listUsers()throws Exception;
	
	public TaUser getUser(String uid)throws Exception;
}

UserServiceImpl.java代码:


package com.jjh.ssh.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jjh.ssh.dao.CommonDao;
import com.jjh.ssh.model.TaUser;
import com.jjh.ssh.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private CommonDao commonDao;
	
	@Override
	public void saveUser(TaUser user) throws Exception {
		if(null == user){
			throw new Exception("参数user为空");
		}
		commonDao.save(user);
	}

	@Override
	public void deleteUser(TaUser user) throws Exception {
		// TODO Auto-generated method stub
		if(null == user){
			throw new Exception("参数user为空");
		}
		commonDao.delete(user);
	}

	@Override
	public void deleteUser(String uid) throws Exception {
		if(null == uid || uid.length() == 0){
			throw new Exception("参数uid为空");
		}
		commonDao.delete(TaUser.class, uid);
	}

	@Override
	public List<TaUser> listUsers() throws Exception {
		StringBuilder hsql = new StringBuilder("select u from TaUser u");
		List l = commonDao.queryList(hsql.toString(), null);
		return l;
	}

	@Override
	public TaUser getUser(String uid) throws Exception {
		if(null != uid || uid.length() == 0){
			throw new Exception("参数uid为空");
		}
		TaUser u = commonDao.get(TaUser.class, uid);
		return u;
	}

	public CommonDao getCommonDao() {
		return commonDao;
	}

	public void setCommonDao(CommonDao commonDao) {
		this.commonDao = commonDao;
	}

	
}

3、在src下添加spring-base.xml配置文件


spring-base.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: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-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/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" default-autowire="byName" default-lazy-init="true">
	<description>Spring公共配置文件</description>
	<!-- 使用Spring的注解 -->
	<context:annotation-config />
	<!-- 扫描包,根据注解,实例化bean,并自动装配 -->
	<context:component-scan base-package="com.jjh" />
	
	<!-- 会话工厂bean -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="configLocation">
			 <value>classpath:hibernate.cfg.xml</value>
		</property>
	</bean>
	 <!-- 事务管理者 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 配置事务的传播特性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="get*" propagation="REQUIRED" />
			<tx:method name="make*" propagation="REQUIRED" />
			<tx:method name="list*" propagation="REQUIRED" />
			<tx:method name="login*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 那些类的哪些方法参与事务 -->
	<aop:config>
		<aop:pointcut id="allServiceMethod" expression="execution(public * com.jjh.ssh..*Service.*(..))" />
		<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
	</aop:config>
	<aop:aspectj-autoproxy proxy-target-class="true"/>    
	
</beans>

4、在WebContent->WEB-INf下的web.xml中添加spring的相关配置

web.xml中添加内容如下:

<!-- 上下文参数 -->
	<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> 
	 
	 <!-- 编码过滤器 -->
	<filter>
	<filter-name>encodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
	  	<url-pattern>/*</url-pattern>
	</filter-mapping>

二、验证

1、修改UserAction.java文件如下:

package com.jjh.ssh.web;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jjh.ssh.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/user")
@Result(name = "userlist", location = "userlist.jsp")

public class UserAction extends ActionSupport {

	@Autowired
	UserService userService;
	
	private List userList;
	
	/**
	 * 获取用户列表
	 * @return
	 * @throws Exception
	 */
	public String listUsers() throws Exception{
		System.out.println("-------listuser action begin-------");
		try {
			this.userList = userService.listUsers();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------listuser action end-------");
		
		return "userlist";
	}

	public List getUserList() {
		return userList;
	}

	public void setUserList(List userList) {
		this.userList = userList;
	}

	
}

2、修改userlist.jsp文件如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>Insert title here</title>
</head>
<body>
	userlist for this!
	<s:iterator value="userList" var="users">
		<s:property value="#users.name" /> | <s:property value="#users.chname" />
	</s:iterator>
</body>
</html>

3、浏览器输入:http://localhost:8080/SSHFW/user/user!listUsers.do

显示结果如下:




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值