1. 程式人生 > >ssh全註解整合

ssh全註解整合

dialect BE pen intercept 監聽 head oca resource ansi

使用註解的方式,配置文件最少可以精簡到三個,web.xml、applicationContext.xml和struts.xml。Hibernate可以完全交給Spring來管理,這樣連hibernate.cfg.xml也省了。下面就一起看看這些基本的配置吧!

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--Spring配置
1.上下文 識別applicationContext.xml

2.監聽器 在Tomcat容器啟動的時候,幫我創建Spring容器,並且放入application中-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--Struts2配置 核心過濾器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

  

web.xml中包含了Spring和struts的基本配置,自動掃描Action的配置就是告訴tomcat,我要使用註解來配置struts。

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<context:component-scan base-package="cn.baby"></context:component-scan>


<!--
1.數據源 c3p0
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!--
2.識別到jdbc.properties
-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--
3.形成SessionFactory
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!--方言-->
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<!--自動建表-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--是否打印sql-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!--關聯小配置-->
<property name="packagesToScan" value="cn.baby.entity"></property>
</bean>

<!--
7.事務管理器
-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--
8.事務真實配置
-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

  User實體

package com.tgb.ssh.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Entity(name="t_user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	private String name;
	private String password;	
	 
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

  dao層實現一個增加的方法

package com.tgb.ssh.dao;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.tgb.ssh.model.User;

@Repository
public class UserDao {
	@Resource(name="sessionFactory") 
	private SessionFactory sessionFactory;
	
	public void addUser(User user ) {
		Session session = sessionFactory.getCurrentSession();
		session.save(user);
	}

}

  service層

package com.tgb.ssh.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tgb.ssh.dao.UserDao;
import com.tgb.ssh.model.User;

@Service
@Transactional
public class UserManager {
	@Resource
	UserDao userDao;
	
	public void addUser(User user) {
		userDao.addUser(user);
	}
	
}

  action層

UserAction通過註解配置Action的名字和返回的頁面,通過@Resource活動Spring註入的UserManager對象,然後進行相應的操作。Action裏還有@Namespace、@InterceptorRef等很多註解可以用,根據自己需要選擇吧。

package com.tgb.ssh.action;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.tgb.ssh.model.User;
import com.tgb.ssh.service.UserManager;


@Results( { @Result(name="success",location="/success.jsp"),
        @Result(name="failure",location="/failure.jsp") }) 
public class UserAction extends ActionSupport {
    @Resource
    private UserManager userManager;
    private User user;
    
    @Action(value="addUser")
    public String addUser() {
        try {
            userManager.addUser(user);        
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
        return "success";
        
    }    

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    
    
}

  頁面jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>添加用戶</title>
  </head>
  
  <body>
      <form method="post" action="addUser">
        用戶名:<input type="text" name="user.name"><br>
        密碼:<input type="password" name="user.password"><br>        
        <input type="submit" value="登錄"/>
    </form>    
  </body>
</html>

  

ssh全註解整合