万事开头难。入手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在写时注意将该放的包放好。我会说其实我还不清楚这些包具体作用,只是统统放进来了么