首页 > 学院 > 开发设计 > 正文

struts2入门笔记(1)

2019-11-06 06:22:11
字体:
来源:转载
供稿:网友

一、在 src(classes) 目录下新建 struts.xml,在 web.xml 中配置核心控制器(说白了就是一过滤器 ) org.apache.struts2.dispatcher.ng.filter.StrutsPRepareAndExecuteFilter

二、编写 struts.xml,其大体结构如下:

<package name= namespace= extends="struts-default"> <action name= class= method= > <result name= >xxx</result> </action></package>

pageckage:方便管理动作元素 name:必须有。包的名称,配置文件中必须保证唯一。 namespace:该包的名称空间,一般是以”/”开头 extends:集成的父包的名称。struts-default名称的包是struts2框架已经命名好的一个包。(在struts2-core.jar中有一个struts-default.xml中) abstract:是否是抽象包。没有任何action元素的包就是抽象包(java类)

action:代表一个请求动作 name:同包中必须唯一。动作的名称 class:负责处理的JavaBean的类全名 method:JavaBean中的对应处理方法。(动作方法:特点是,public String 方法名(){})

result:结果类型 name:动作方法返回的字符串 主体内容:View的具体地址。

三、根据配置文件,创建需要的javabean和对应的动作方法, 在动作方法中完成你的逻辑调用。

public class HelloWorldAction extends ActionSupport implements Serializable { private static final long serialVersionUID = -3458082853638450597L; private String message; public String sayHello() { message = "Hello By Struts2!"; return SUCCESS; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }}

四、访问helloworld动作的方式: http://localhost:8080/struts2day01/test/helloworld 应用名称/包的名称空间/动作的名称 默认情况下:访问动作名helloworld,可以直接helloworld,或者helloworld.action

http://localhost:8080/struts2day01/test/a/b/c/helloworld /test/a/b/c:名称空间 helloworld:动作名称 搜索顺序:名称空间 /test/a/b/c 没有helloworld /test/a/b 没有helloworld /test/a 没有helloworld /test 有了,调用执行

五、Struts2配置文件的详解 Struts配置文件中的各种默认值: action: class:默认值是com.opensymphony.xwork2.ActionSupport method:默认值是public String execute(){}

实际开发中:自己编写的动作类一般情况下继承 com.opensymphony.xwork2.ActionSupport

result: type:转到目的地的方式。默认值是转发,名称是dispatcher (注:type的取值是定义好的,不是瞎写的。在struts-default.xml中的package中有定义)

dispatcher:普通的转发到某个页面 chain:普通的抓发到某个动作名称 redirect:重定向到一个页面 redirectAction:重定向到一个动作名称 plainText:以纯文本的形式输出jsp内容

result元素的写法: 方式一: <result type="chain" name="success">a2</result> 方式二:

<result type="chain" name="success"> <param name="actionName">a2</param> <!--name对应的chain的处理器中的setActionName()方法--></result>

注意:如果要转向的是在另外一个名称空间的动作,那么只能使用方式二

<package name="p1" namespace="/namespace1" extends="struts-default"> <action name="a2"> <result type="dispatcher" name="success">/3.jsp</result> </action></package><package name="p2" namespace="/namespace2" extends="struts-default"> <action name="a1"> <result type="chain" name="success"> <param name="namespace">/namespace1</param> <param name="actionName">a2</param> </result> </action></package>

开发中配置文件的更改,在访问时让框架自动重新加载: struts.devMode = false(org.apache.struts2/default.properties)

利用strutx.xml中的constant元素来覆盖掉default.properties默认行为

<struts> <constant name="struts.devMode" value="true"></constant></struts>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表