本文演示了JSP中获取HTTP参数的几种方式,还有action中获取HTTP参数的几种方式。
1. 创建JSP页面(testParam.jsp)
<%@ 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>
2. 创建Action类(ParameterTestAction.java)
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;} }
3. 修改struts.xml文件
<action name="testParam" class="com.clzhang.struts2.demo4.ParameterTestAction"><result name="success">/struts2/demo4/testParam.jsp</result></action>
4. 测试
打开IE,输入如下地址:http://127.0.0.1:8080/st/struts2/demo4/testParam.jsp?username=zhang1&remark=that'sok
注意URL后面的参数。
结果如下:
输入用户名:张三,备注:不错的状态,提交,结果如下:
后台输出如下: