在struts.xml配置文件里对action实现类中的多个方法进行配置方式有哪些?

2025-03-01 03:49:40
推荐回答(2个)
回答1:

action的配置中,有一个为"redirectAction”(重定向到一个Action)和chain(就是所谓的action请求链)的action类型
顺便说一下struts2的action type:
chain 用来处理Action链
dispatcher 用来转向页面,通常处理JSP
redirect 重定向到一个URL
redirectAction(或redirect-action) 重定向到一个Action

回答2:

1.采用DMI动态调用方法。

  该方法的主要思想是在一个 Action 类中实现多个方法,然后每个 action 请求中表明要调用该类中的哪个方法。使用 actionname!method 方式调用。

  (1)LoginAction 类代码如下:

复制代码
1 package com.main.action;
2
3 import com.opensymphony.xwork2.ActionSupport;
4
5 public class LoginAction extends ActionSupport {
6 private String username;
7 private String psd;
8
9 public String login(){
10 if ("lihui".equals(username) && "xhh".equals(psd)) {
11 return SUCCESS;
12 } else {
13 return ERROR;
14 }
15 }
16
17 public String regist(){
18 return "regist";
19 }
20
21 public void setUsername(String username){
22 this.username = username;
23 }
24
25 public String getUsername(){
26 return this.username;
27 }
28
29 public void setPsd(String psd){
30 this.psd = psd;
31 }
32
33 public String getPsd(){
34 return this.psd;
35 }
36 }
复制代码
  (2)struts.xml 配置如下:  

复制代码
1
2 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6
7
8
9 /success.jsp
10 /error.jsp
11 /regist.jsp
12

13

14

复制代码
  (3)在jsp中的action请求代码如下:

复制代码
1
2
9


10 姓名:

11 密码:

12
13
14

15
复制代码
2.直接指定 Action 元素的 method 属性

  使用这个方法就不必用 ! 将action和method连接后调用了,struts.xml 配置如下:

复制代码
1
2
3
4 /success.jsp
5 /error.jsp
6

7
8 /regist.jsp
9

10

11

复制代码
3.使用通配符处理

  的属性name class method 都支持通配符。struts.xml 配置如下:

复制代码
1
2
3
4 /success.jsp
5 /error.jsp
6 /regist.jsp
7

8

9

复制代码
  关键就在于第三行代码, login_* 使用了通配符,所以接收所有类似的action请求,至于调用该类中的哪个方法,就看method="{1}",表示使用name属性第一个*的值。例如,在本例中,form的action属性值设置为 login_regist,则调用com.main.action.LoginAction类中的regist()方法。

此外,Struts支持默认 Action 请求。当系统找不到指定的Action时,则交给默认的Action去处理。在struts.xml中的配置为: