一:struts整合spring不单单需要各自的jar包,还需要struts-spring-plugin-2.1.6.jar将struts与spring建立联系
二:web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
三.有一个loginaction,struts和spring配置文件怎么写
LoginAction.java
package com.test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.test.service.LoginService;
public class LoginAction extends ActionSupport
{
private String username;
private String password;
private LoginService loginService;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public LoginService getLoginService()
{
return loginService;
}
public void setLoginService(LoginService loginService)
{
this.loginService = loginService;
}
@Override
public String execute() throws Exception
{
if(loginService.isLogin(username,password))
{
return SUCCESS;
}
else
{
return ERROR;
}
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="strutsspring" extends="struts-default">
<action name="login" class="loginAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
struts.xml中action的class不用真实的,指向spring配置文件的id
SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="loginService" class="com.test.service.impl.LoginServiceImpl" scope="singleton"></bean>
<!-- 对于action来说,一定要将其scope配置成prototype或是request -->
<bean id="loginAction" class="com.test.action.LoginAction" scope="prototype">
<property name="loginService" ref="loginService"></property>
</bean>
</beans>
对于spring配置文件的bean属性,其scope属性有以下几个值
1.singleton 单实例 适用:所有无状态的对象
2.prototype 表示每次从容器中取出bean时,都会生成一个新实例。相当与new出来一个新对象
3.request 该属性基于web,表示每次接受一个新的请求时,都会生成一个新实例。在这个情况下,request与prototype 一样
4.session 表示在每个session中该对象只有一个
5.globalSession