Spring/Struts2整合项目

来源:互联网 发布:重庆医疗程序员招聘 编辑:程序博客网 时间:2024/05/21 16:55

1、新建web项目

2、导入Struts2所需jar(jar包稍后与项目一起提供下载

3、配置web.xml,添加struts2用到的核心过滤器

<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>*.htm</url-pattern></filter-mapping>

4、在web项目的src路径下新建struts.xml

5、导入spring所需jar以及添加struts2-spring整合的插件struts2-spring-plugin-2.x.xx.jar

6、添加spring配置文件application.xml,放在项目WEB-INF目录下

7、在web.xml里面配置spring用到的监听器

<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 默认applicationContext.xml文件放置在工程的WEB-INF目录下。修改如下:--><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/application.xml</param-value></context-param>

8、编写HsunService接口

public interface HsunService {public List<String> getList();}

9、编写HsunService接口实现HsunServiceImpl

public class HsunServiceImpl implements HsunService {public List<String> getList() {System.out.println("000000");List<String> list = new ArrayList<String>();for (int i = 0; i < 10; i++) {list.add(i+""+Math.random());}return list;}}

10、编写请求Action,HsunAction

public class HsunAction extends ActionSupport {@Overridepublic String execute() throws Exception {this.setRlist(hsunService.getList());return SUCCESS;}private HsunService hsunService;private List<String> rlist;public HsunService getHsunService() {return hsunService;}public void setHsunService(HsunService hsunService) {this.hsunService = hsunService;}public List<String> getRlist() {return rlist;}public void setRlist(List<String> rlist) {this.rlist = rlist;}}

11、配置application.xml,注入service

    <bean name="hsunService" class="com.hsun.service.impl.HsunServiceImpl" />    <bean name="hsunaction" class="com.hsun.action.HsunAction" scope="prototype">    <property name="hsunService" ref="hsunService"/>    </bean>
12、配置struts.xml

<!--增加struts的扩展名--><constant name="struts.action.extension" value="htm" /><package name="hsun" namespace="" extends="struts-default"><action name="hello" class="hsunaction"><result name="success">/WEB-INF/html/hello.jsp</result></action></package>

13、编写返回页面hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>Home</title>  </head>    <body>    Hello World! <br>    ${rlist }  </body></html>

14、部署项目,启动tomcat,在地址栏中输入http://localhost:8080/hello.htm


OK! SUCCESS~~~


项目源码下载地址