struts2基础学习二

时间:2023-02-26 19:00:08

1、struts的action请求动态调用方法

package com.action;

import com.model.MessageStore;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{
public String teste(){
System.out.println("执行测试...");
return "test";
}

public String addInput(){
System.out.println("进入添加页面");
return "addInput";
}
public String add(){
System.out.println("执行添加");
return "add";
}
public String updateInput(){
System.out.println("进入更新页面");
return "updateInput";
}
public String update(){
System.out.println("执行更新");
return "update";
}
}

addInput.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

</head>

<body>
<form action="hello.do" method="post">
username:<input type="text" name="username"/><br/>
password:<input type="password" name="password"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

struts.xml


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<consant name="struts.action.extension" value="action,,do"/>
<package name="basicstruts2" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="hello" class="com.action.HelloWorldAction">
<result name="add">/add.jsp</result>
<result name="addInput">/helloworld.jsp</result>
<result name="update">/helloworld.jsp</result>
<result name="updateInput">/helloworld.jsp</result>

</action>
</package>
</struts>

将一个Action类中写入多个方法返回JSP页面的优点是,减少Action类


动态请求addInput.jsp页面

方法:(3中)

    1、在请求地址栏后面加请求方法

          ① 在地址栏里添加要调用的方法

       http://localhost:8080/aa/hello.action?method:addInput  (地址+?+method+:+方法名),使用时切记struts.xml配置文件中的该段代码method不写。

         ②  <form action="hello.do?method:addInput" method="post">

         ③在表单中加入

<input type="hidden" name="method:addInput">

<form action="hello.do" method="post">
<input type="hidden" name="method:addInput">
username:<input type="text" name="username"/><br/>
password:<input type="password" name="password"/><br/>
<input type="submit" value="submit"/>
</form>
    2、 http://localhost:8080/aa/hello!addInput.action

    3、路径:http://localhost:8080/aa/ss/hello_addInput.action   ({1}匹配第一个*)

<action name="hello_*" class="com.action.HelloWorldAction" mothod="{1}">
<result name="add">/add.jsp</result>
<result name="addInput">/helloworld.jsp</result>
<result name="update">/helloworld.jsp</result>
<result name="updateInput">/helloworld.jsp</result>

</action>