首页 > 代码库 > 初学Struts2

初学Struts2

1、新建工程,引用Struts2

项目结构如下:

2、Web配置,web.xml:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"         version="3.1">    <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>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>

3、Struts配置:

<?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>    <package name="demo.controllers" extends="struts-default">        <action name="HelloWord" class="demo.controllers.HelloWord"> --配置Action名称            <result>helloword.jsp</result>  --配置action 执行成功后返回的页面            <result name="error">error.jsp</result> --配置Action执行返回error时的页面        </action>    </package></struts>

4、Controller:

package demo.controllers;import com.opensymphony.xwork2.ActionSupport;import java.text.DateFormat;import java.util.Date;/** * Created by Administrator on 2014/11/13. */public class HelloWord extends ActionSupport{    private String message;    public String getMessage() {        return message;    }    public String execute(){        message="hello word now is:"+ DateFormat.getInstance().format(new Date());        return ERROR;  --由Struts中HelloWord 中result name="error" 指定页面显示
} }

 说明:Action返回一个结果的名字字符串,如SUCCESS,ERROR;从Struts中读取映射信息。一个给定的结果字符串将返回指定的资源返回给客户端

初学Struts2