博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java综合(一)spring与struts2整合
阅读量:3530 次
发布时间:2019-05-20

本文共 2454 字,大约阅读时间需要 8 分钟。

学习了spring与strust2后,还没做过整合呢.现在学习下Spring与struts2的整合.

写个小例子Hello World.

1.新建Web工程,加入依赖包.

除了加入各自的核心包以外,还需要加入一个包:struts2-spring-plugin-2.3.24.jar

2.Web.xml配置

struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
WEB-INF/classes/config/applicationContext.xml
通过配置ContextLoaderListener监听器,使容器启动时,自动加载applicationContext配置,
默认情况下,会加载WEB-INF/applicationContext.xml这个文件,我们可以通过配置contextConfigLocation参数改变配置文件的路径

因为它实现了ServletContextListener这个接口,容器启动时会自动执行它实现的方法。

3.java文件:Service,ServiceBean,Action类

package com.skymr.ss2.hello.service;public interface HelloWorldService {	public void say();}
定义了一个接口,指定它具有的功能,那就是说话.

package com.skymr.ss2.hello.service.impl;import com.skymr.ss2.hello.service.HelloWorldService;public class HelloWorldServiceBean implements HelloWorldService{	public void say() {		System.out.println("spring-struts第一个实例:Hello World!!!");	}}
接口的实现类,功能是打印一段话:HelloWorld..

package com.skymr.ss2.hello.action;import com.opensymphony.xwork2.ActionSupport;import com.skymr.ss2.hello.service.HelloWorldService;public class HelloWorldAction extends ActionSupport{	//业务层实例,需要spring 注入实例,这里用setter方法注入,所以要实现getter/setter方法	private HelloWorldService helloWorldService;		public HelloWorldService getHelloWorldService() {		return helloWorldService;	}	public void setHelloWorldService(HelloWorldService helloWorldService) {		this.helloWorldService = helloWorldService;	}	@Override	public String execute() throws Exception {		System.out.println("执行HelloWorldAction execute方法");		//调用业务层方法		helloWorldService.say();		return SUCCESS;	}	}
Action类

4.Spring配置文件 applicationContext.xml

定义了两个 bean, action bean与service bean,把service bean注入到action bean中,以便请求到action时调用业务.

感觉bean属性的name与id没什么区别,都没有错误.

5.struts.xml配置

/index.jsp
必须加入<constant name="struts.objectFactory" value="spring" />,告诉struts2 action的实例由spring申请与管理.

action的class属性 对应 spring配置文件中的action bean的name/id属性

6.部署测试

请求http://localhost:8080/spring_struts2/helloWorld

显示了index.jsp页面

后台打印了业务层方法

执行HelloWorldAction execute方法

spring-struts第一个实例:Hello World!!!

转载地址:http://qjihj.baihongyu.com/

你可能感兴趣的文章
php开启redis扩展包与redis安装
查看>>
php使用openssl来实现非对称加密
查看>>
pdo如何防止 sql注入
查看>>
myisam和innodb的区别
查看>>
MySQL建表规范与注意事项(个人精华)
查看>>
JDK8接口的新特性
查看>>
synchronized的局限性与lock的好处
查看>>
redis和memcached有什么区别?
查看>>
Spring中的设计模式
查看>>
如何设计一个秒杀系统 -- 架构原则
查看>>
如何设计一个秒杀系统 -- 动静分离方案
查看>>
JWT 快速了解
查看>>
实习日志一
查看>>
python math模块功能详解
查看>>
python 打开windows系统上的文件(音频、视频、记事本等)
查看>>
python list类对象的常用方法
查看>>
python将中文汉字转换成拼音
查看>>
python beautifulsoup4解析网页
查看>>
Mysql完整复制表的方法
查看>>
Mysql处理重复数据
查看>>