Struts2项目地址:http://struts.apache.org
为项目添加Struts2支持:
- 下载Strust2资源包,选择All版本
- 使用struts2源文件app/sturts-blank示例中的所有jar包
- 在web.xml中添加Struts2的核心过滤器
- 添加Struts2的配置文件,在apps/struts-blank/WEB-INF/classes
实例:
新建HelloStruts2Action.java类:
package com.web.action; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport{ public final static String MESSAGE = "Hello Struts2!"; private String message; public String getMessage(){ return message; } public void setMessage(String message){ this.message = message; } public String execute() throws Exception{ setMessage(MESSAGE); return SUCCESS; } }
在src资源目录下修改struts2.xml配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- Struts2中的常量属性 --> <!-- 是否支持动态方法调用,默认值为true --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!-- 开发模式:在应用出错时,显示更多/更友好的出错提示 --> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!--调用HelloWorld--> <action name="HelloStruts2Action" class="com.web.action.HelloStruts2Action"> <result>/HelloStruts2Action.jsp</result> </action> <!-- 动态方法调用 --> <action name="log" class="com.web.action.HelloStruts2Action"> <result name="success">/helloStruts2.jsp</result> <result name="input" type="redirect">/login.jsp</result> </action> </package> </struts>
编写HelloStruts2Action.jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Hello Struts2!</title> </head> <body> <h2><s:property value="message" /></h2> </body> </html>