本文演示了JSP中獲取HTTP參數的幾種方式,還有action中獲取HTTP參數的幾種方式。html
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page isELIgnored="false"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> JSP頁面中三種獲取HTTP Parameter的方法: <br/> 1.<s:property value="#parameters.username"/> <br/> 2.<s:property value="#parameters['remark']"/> <br/> 3.<%=request.getParameter("username")%> <br/> <s:form action="testParam" method="post"> 用戶名:<s:textfield name="username"></s:textfield> <br/> 備註:<s:textfield name="remark"></s:textfield> <br/> <s:submit value="提交"></s:submit> <br/> </s:form> </body> </html>
package com.clzhang.struts2.demo4; import java.util.*; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ActionContext; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; public class ParameterTestAction extends ActionSupport { public static final long serialVersionUID = 1; private String username; private String remark; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String execute() throws Exception { // 方式一:將參數設置爲Action的屬性,OGNL會自動填充它 System.out.println("1.把參數做爲Action的屬性..."); System.out.println("username=" + this.username); System.out.println("remark=" + this.remark); // 方法二:在Action中使用ActionContext獲得包含parameter的Map以獲取參數 ActionContext context = ActionContext.getContext(); Map parameterMap = context.getParameters(); String usernameArray[] = (String[]) parameterMap.get("username"); String remarkArray[] = (String[]) parameterMap.get("remark"); System.out.println("2.經過ActionContext.getContext().getParameters()取得..."); System.out.println("username: " + usernameArray[0]); System.out.println("remark: " + remarkArray[0]); // 方法三:在Action中取得HttpServletRequest對象,常規方法取得 HttpServletRequest request = (HttpServletRequest) context .get(ServletActionContext.HTTP_REQUEST); String username = request.getParameter("username"); String remark = request.getParameter("remark"); System.out.println("3.經過HttpServletRequest對象取得..."); System.out.println("username: " + username); System.out.println("remark: " + remark); return SUCCESS; } }
<action name="testParam" class="com.clzhang.struts2.demo4.ParameterTestAction"> <result name="success">/struts2/demo4/testParam.jsp</result> </action>
打開IE,輸入以下地址:http://127.0.0.1:8080/st/struts2/demo4/testParam.jsp?username=zhang1&remark=that'sokjava
注意URL後面的參數。apache
結果以下:jsp
輸入用戶名:張三,備註:不錯的狀態,提交,結果以下:post
後臺輸出以下:測試