`
activemq
  • 浏览: 26469 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

整合小结

阅读更多
spring 与 struts 整合 有3 种方法
实质是 spring 的 ContextLoader (org.springframework.web.context.ContextLoader) 在ContextLoaderServlet加载  ,由ContextLoader的initWebApplicationContext(ServletContext)初始化WebApplicationContext;
本质将spring context 放置于 servletContext对象范围内
servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
贴出spring 框架源码 如下 :

ContextLoaderServlet.class :
public class ContextLoaderServlet extends HttpServlet {

private ContextLoader contextLoader;


/**
* Initialize the root web application context.
*/
public void init() throws ServletException {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(getServletContext());
}

/**
* Create the ContextLoader to use. Can be overridden in subclasses.
* @return the new ContextLoader
*/
protected ContextLoader createContextLoader() {
return new ContextLoader();
}

/**
* Return the ContextLoader used by this servlet.
* @return the current ContextLoader
*/
public ContextLoader getContextLoader() {
return this.contextLoader;
}


/**
* Close the root web application context.
*/
public void destroy() {
if (this.contextLoader != null) {
this.contextLoader.closeWebApplicationContext(getServletContext());
}
}


/**
* This should never even be called since no mapping to this servlet should
* ever be created in web.xml. That's why a correctly invoked Servlet 2.3
* listener is much more appropriate for initialization work ;-)
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
getServletContext().log(
"Attempt to call service method on ContextLoaderServlet as [" +
request.getRequestURI() + "] was ignored");
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}


public String getServletInfo() {
return "ContextLoaderServlet for Servlet API 2.2/2.3 " +
    "(deprecated in favor of ContextLoaderListener for Servlet API 2.4)";
}

}

ContextLoader.class :

public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
throws IllegalStateException, BeansException {

if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}

servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();

try {
// Determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);

// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
this.context = createWebApplicationContext(servletContext, parent);
servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);


if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}

return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}


配置 web.xml 文件

<context-param> 
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

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

   或者 
struts在此被装载org.apache.struts.action.ActionServlet,还有它的配置参数config文件struts-config.xml,spring在此被装载org.springframework.web.context.ContextLoaderServlet还有它的配置文件applicationContext.xml

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>contextLoaderServlet</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

spring 加载log4j  把log4j.properties文件放到 WEB-INF下面
再加上如下配置即可

<context-param> 
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>org.springframework.web.util.Log4jConfigServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

spring + struts + hibernate +dwr 整合

Web.xml  :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!--
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>contextLoaderServlet</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
-->
<filter>
<filter-name>myfilter</filter-name>
<filter-class>com.jeny.filter.MyFilter</filter-class>

<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>

</filter>

    <filter-mapping>
    <filter-name>myfilter</filter-name>
    <url-pattern>*.do</url-pattern>
    </filter-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

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

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>
org.springframework.web.util.Log4jConfigServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet>
<servlet-name>dwr</servlet-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/dwr.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dwr</servlet-name>
<url-pattern>/lixing/*</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>

<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>

<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

Dwr.xml  :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr20.dtd">

<dwr>

  <allow>
    <create creator="new" javascript="hello">
      <param name="class" value="com.dwr.Getpwd"/>
    </create>
    
  </allow>

</dwr>

Condb.properties 文件 放置于 WEN-INF目录下 :
Condriver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://127.0.0.1:1433;Databasename=mypubs
uid=sa
pwd=

applicationContext.xml  :
这个是spring的专有配置文件,里面配置代理hibernate资源和struts的action

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="configbean" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/Condb.properties</value>
</list>
</property>
</bean>
<!--
由 Condb.properties文件 获得 数据库连接 的 DriverClass , url 等…-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName">
<value>${Condriver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${uid}</value>
</property>
<property name="password">
<value>${pwd}</value>
</property>

</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/com/form/</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   <property name="sessionFactory">
       <ref local="sessionFactory" />
   </property>
</bean>

<bean id="UserDAO" class="com.jeny.util.UserDAO">
  <property name="sessionFactory">
    <ref local="sessionFactory"/>
  </property>
</bean>
transactionAttributes是对所代理的方法哪些方法提供事务,比如你定义一个以add开头的方法,那它就可以有事务管理了,对于它里面的所有操作,都可以实现事务机制,若有异常就回滚事务
target它是指向要注入的类,代理这个类所实现的接口
<bean id="userDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  <property name="transactionManager">
    <ref bean="transactionManager" />
  </property>
  <property name="target">
    <ref local="UserDAO" />
  </property>
  <property name="transactionAttributes">
    <props>
      <prop key="insert*">PROPAGATION_REQUIRED</prop>
      <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
      <prop key="update*">PROPAGATION_REQUIRED</prop>
    </props>
  </property>
</bean>



<bean name="/registion" class="com.action.RegistionAction">
<property name="user">
<ref bean="userDAOProxy"/>
</property>
</bean>
</beans>

Struts-config.xml 中的action 的type 值必须是  : org.springframework.web.struts.DelegatingActionProxy

<action path="/updatepwd"
type="org.springframework.web.struts.DelegatingActionProxy"
name="password" attribute="pwd">

DAO 层
Hibernate 框架源码 
public abstract class HibernateDaoSupport extends DaoSupport {

private HibernateTemplate hibernateTemplate;


/**
* Set the Hibernate SessionFactory to be used by this DAO.
* Will automatically create a HibernateTemplate for the given SessionFactory.
* @see #createHibernateTemplate
* @see #setHibernateTemplate
*/
public final void setSessionFactory(SessionFactory sessionFactory) {
  this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
/**
* Create a HibernateTemplate for the given SessionFactory.
* Only invoked if populating the DAO with a SessionFactory reference!
* <p>Can be overridden in subclasses to provide a HibernateTemplate instance
* with different configuration, or a custom HibernateTemplate subclass.
* @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for
* @return the new HibernateTemplate instance
* @see #setSessionFactory
*/
protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
return new HibernateTemplate(sessionFactory);
}

由上可看出 注  : 要获得getHibernateTemplate 必须在UserDAO bean内 注入 SessionFactory
<bean id="UserDAO" class="com.jeny.util.UserDAO">
  <property name="sessionFactory">
    <ref local="sessionFactory"/>
  </property>
</bean>



   DAO 继承HibernateDaoSupport
      HibernateDaoSupport实现了HibernateTemplate和SessionFactory实例的关联, HibernateTemplate对Hibernate Session操作进行了封装,HibernateTemplate.execute方法则是一封装机制的核心. 借助HibernateTemplate我们可以脱离每次数据操作必须首先获得Session实例、启动事务、提交/回滚事务以及烦杂的try/catch/finally的繁琐操作.
        Spring中的事务管理实际上是基于动态AOP机制实现

public class UserDAO extends HibernateDaoSupport  implements IUserDAO{

private SessionFactory sessionFactory;

public boolean insertUser(UserInfo userinfo) {

this.getHibernateTemplate().save(userinfo);
return true;
}

public boolean checkLogin(User user) {

try {
List list = this.getHibernateTemplate().find("from UserInfo as u where ( u.cardnum ="+ user.getCardnum().trim() +" and u.password = "+ user.getPassword().trim() +")");
if(list.size()==0){
return false;
}
} catch (Exception e) {
return false;
}
return true;
}

public boolean updatePwd(Integer id,String pwd) {
UserInfo ui = (UserInfo)this.getHibernateTemplate().get(UserInfo.class,id);
ui.setPassword(pwd);
return true;
}

public boolean updateInfo(Integer id, Info in) {
UserInfo u = (UserInfo)this.getHibernateTemplate().get(UserInfo.class,id);
u.setName(……);
return true;
}

Spting ioc 的serter 与getter 将biz注入到业务action中

public class UpdatePwdAction extends Action {

private IUserDAO muuser;
public IUserDAO getMuuser() {
return muuser;
}
public void setMuuser(IUserDAO muuser) {
this.muuser = muuser;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Password password = (Password)form;
String oldpwd = password.getOldpassword().trim();
String pwd = password.getPassword().trim();

UserInfo c = (UserInfo)request.getSession().getAttribute("userinfo");
Integer id = c.getId();
boolean b = muuser.updatePwd(id,pwd);
if(b){
return mapping.findForward("updatepwdsucess");
}else{
return mapping.findForward("updatepwdfail");
}
}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics