创建struts2应用程序并添加spring jar文件。
在 web.xml 文件中,定义ContextLoaderListener类。
在 struts.xml 文件中,为操作类定义bean名称。
在 applicationContext.xml 文件中,创建Bean。其类别名称应为动作类别名称,例如com.lidihuo.Login和id应该与struts.xml文件的操作类(例如login)匹配。
在 action类中,定义其他属性,例如消息。
index.jsp
web.xml
struts.xml
applicationContext.xml
Login.java
welcome.jsp
error.jsp
<%@ taglib uri="/struts-tags" prefix="s"%> <s:form action="login"> <s:textfield name="userName" label="UserName"></s:textfield> <s:submit></s:submit> </s:form>
<?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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts public "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="abc" extends="struts-default"> <action name="login" class="login"> <result name="success">welcome.jsp</result> </action> </package> </struts>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="login" class="mypack.Login"> <property name="message" value="Welcome Spring"></property> </bean> </beans>
package mypack; public class Login { private String userName,message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String execute(){ return "success"; } }
<%@ taglib uri="/struts-tags" prefix="s"%> Welcome, <s:property value="userName"/><br/> ${message}
Sorry!