1. 程式人生 > >Struts2配置一個Action實現多個請求

Struts2配置一個Action實現多個請求

struts2中的Action預設執行方法為execute(),儘管可以通過<action name="addUser" class="addUser" method="doFun">設定預設執行方法,但也難以改變一個<action>一個方法的窘境。

那麼,一個Action中多個方法,如何配置呢?

先上方法,簡單舉例:使用者管理

UserManagerAction.java

public class UserManagerAction extends ActionSupport implements RequestAware {

	private User user;
	
	@Resource
	private UserManager userManager; 
	
	private Map<String, Object> request;
	
	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String addUser() throws Exception {
		System.out.println("-----UserManagerAction.addUser()-----");
		userManager.addUser(user);
		return "success";
	}
	
	public String modifyUser() {
		System.out.println("-----UserManagerAction.modifyUser()-----");
		userManager.modifyUser(user);
		return "success";
	}
	
	public String delUser() {
		System.out.println("-----UserManagerAction.delUser()-----");
		userManager.delUser(user.getUsername());
		return "success";
	}
	
	public String queryUser() {
		System.out.println("-----UserManagerAction.queryUser()-----");
		User user1 = userManager.queryUser(user.getUsername());
		request.put("user1", user1);
		return "success";
	}

	public String queryAllUser() {
		System.out.println("-----UserManagerAction.queryAllUser()-----");
		List<User> userList = userManager.queryAllUser();
		request.put("userList", userList);
		return "success";
	}
}


struts.xml配置,一個Action處理多個請求的配置

1.第一種方法:多個<action>標籤,設定不同的method屬性

	<package name="userManager" namespace="/user" extends="struts-default">
		<action name="addUser" class="com.ys.action.UserManagerAction" method="addUser" />
		<action name="modifyUser" class="com.ys.action.UserManagerAction" method="modifyUser" />
		<action name="delUser" class="com.ys.action.UserManagerAction" method="delUser" />
	</package>


2.第二種方法:採用!的方式訪問請求,例如:user/userManager!addUser

	<package name="userManager" namespace="/user" extends="struts-default">
		<action name="userManager" class="com.ys.action.UserManagerAction">
			<result name="success">/success.jsp</result>
			<result name="error" type="redirect">/error.jsp</result>
		</action>    
	</package>

*.jsp頁面請求如:myForm.action = "user/userManager!addUser";

3.第三種方法:採用萬用字元的方式(推薦)

	<package name="userManager" namespace="/user" extends="struts-default">
		<action name="*User_*" class="UserManagerAction" method="{1}User">
			<result name="success">/{2}.jsp</result>
			<result name="error" type="redirect">/error.jsp</result>
		</action>
	</package>

({1}匹配第一個*,{2}匹配第二個*)

*.jsp頁面請求如:myForm.action = "user/addUser_success";