hello struts2

万事开头难。入手struts2最简单的例子,过程为:
(1)浏览器请求http://localhost:8080/hello.action,服务器通过web.xml文件发现,所有的请求都要通过filter过滤器
web.xml中与过滤器有关的代码为:

     <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>

(2)服务器开始在struts.xml文件中找hello.action对应的class

<struts>
    <package name="test" extends="struts-default">
        <action name="hello" class="test.Hello">
            <result>/index.jsp</result>
        </action>
    </package>
</struts>

根据文件,hello.action对应的class为test包下的Hello.class

(3)于是执行Hello.class(Hello.java)中的execute方法,Hello.java代码如下:

package test;
public class Hello extends ActionSupport{
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    @Override
    public String execute() throws Exception {
        String str="hello Struts2";
        setMessage(str);
        System.out.println(str);
        return SUCCESS;
    }
}

执行成功后,message的内容为“hello Struts2”,并返回SUCCESS;

(4)struts.xml中写到,成功的result就是转到index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <title>hello</title>
  </head>
  <body>
        <s:property value="message"/>
  </body>
</html>

其中,s: 为struts2的标签,<s:property value="message"/>即调用Hello.java中的getMessage()方法,得到的是”hello Struts2”。

根据以上的各步骤,浏览器http://localhost:8080/hello.action的请求最终在窗口显示hello Struts2。

PS:目录要放对,我用的是IDEA,它隐藏了web-inf下的classes文件夹。Hello.java编译的结果和struts.xml文件都在classes文件夹下,忘了就出错了。
这里写图片描述

另外,jsp在写时注意将该放的包放好。我会说其实我还不清楚这些包具体作用,只是统统放进来了么

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值