所有的MVC框架都需要负责解析HTTP的请求参数,并对请求参数进行封装和解析处理,Struts2自带有很强大的类型转换器,能够将前端传来的参数自动转换成Action类中成员变量(基于OGNL的类型转换),所以,使用Struts2来接收前端传来的基本类型参数的时候,只需要在Action类中定义与传来参数对应名称的成员变量,并提供getter和setter方法,就可以接收参数;而对于复杂类型的参数的封装的时候,前端提供的请求参数名需要按照OGNL表达式的形式进行传参。
接收基本类型
首先,定义一个Action类ParamterAction,接收前端传来的name和password参数,并打印到控制台
package com.bran.g_paramter;
import com.opensymphony.xwork2.ActionSupport;
//struts2如何获得参数
public class ParamterAction extends ActionSupport {
//准备与参数键名称相同的属性
private String name;
private String password;
@Override
public String execute() throws Exception {
System.out.println("用户名:"+name);
System.out.println("密码:"+password);
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在struts.xml中对该Action进行配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="paramter" namespace="/" extends="struts-default">
<action name="ParamterAction"
class="com.bran.g_paramter.ParamterAction" method="execute">
<result name="success" type="dispatcher">/form/form1.jsp</result>
</action>
</package>
</struts>
再定义一个表单form1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>接收参数</title>
<style type="text/css">
.a {
width: 300px;
height: 30px;
}
#b {
width: 500px;
text-align: right;
}
#b button {
width: 60px;
margin-right: 120px;
}
</style>
</head>
<body>
<div id="b">
<form action="${pageContext.request.contextPath }/ParamterAction">
<strong>用户名:</strong><input type="text" class="a" name="name" /><br/><br/>
<strong>密 码:</strong><input type="password" class="a" name="password" /><br/><br/>
<button type="submit">提交</butt