`

spring hibernate struts 整合开发(3) - Struts集成Spring

阅读更多
一. spring hibernate struts 整合开发(1) - 搭建环境
二. spring hibernate struts 整合开发(2) - Spring集成的Hibernate编码和测试
三. spring hibernate struts 整合开发(3) - Struts集成Spring
四. spring hibernate struts 整合开发(4) - Struts与Spring集成2
五. spring hibernate struts 整合开发(5) - Hibernate二级缓存
六. spring hibernate struts 整合开发(6) - 额外功能



1. 在web容器中实例化spring容器

  spring自带的实例化容器方法是:
 
  AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  


  在web.xml中,通过配置listener和context param:
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath前缀指定从类路径下寻找 -->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


查看ContextLoaderListener源码,可以看到spring把上下文放到servletContext里:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);


2. Struts配置

a. 在web.xml中,加入struts配置段:
<servlet>
  <servlet-name>struts</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>
  <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>struts</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

 
b. 新建struts-config.xml文件,加入下面配置:

<?xml version="1.0" encoding="utf-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
   <action-mappings>
     <action path="/person/list" type="cn.john.web.action.PersonAction" validate="false">
         <forward name="list" path="/WEB-INF/page/person_list.jsp"/>
     </action>
</struts-config>


3. 新建com.john.web.action.PersonAction类,重载execute方法:
public class PersonAction extends Action{

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// Spring provides us a util to get the context
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
		PersonService personService = (PersonService)ctx.getBean("personService");
		request.setAttribute("persons", personService.getPersons());
		return mapping.findForward("list");
	}
}


4. 新建person_list.jsp文件,加入下面内容:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<body>
	<c:forEach items="${persons}" var="person">
		${person.id} ${person.name}
	</c:forEach>
</body>


开启Web服务(Tomcat, jetty等)测试

整理自:传智播客spring教程
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics