背景
使用 Eclipse Helios、Apache Tomcat、JSP 和 JBoss RichFaces。
输入参数编码如下:
<h:inputHidden name="system_REPORT_RESOURCE" value="city" />
<h:inputHidden name="system_REPORT_FILENAME" value="city" />
<h:inputHidden name="report_REPORT_TITLE" value="City Listing" />
... and others ...
问题
以下代码显示键的值:
@SuppressWarnings( "unchecked" )
protected void setInputParameters() {
HttpServletRequest request = getServletRequest();
Enumeration<String> keys = request.getParameterNames();
while( keys.hasMoreElements() ) {
String key = keys.nextElement();
for( String value : request.getParameterValues( key ) ) {
System.out.println( "KEY: " + key + " VALUE: " + value );
}
}
}
框架修改键名:
KEY: j_id2:report_city VALUE: ab
KEY: j_id2:system_REPORT_RESOURCE VALUE: city
KEY: j_id2:j_id11 VALUE: Report
KEY: j_id2:report_REPORT_TITLE VALUE: City Listing
KEY: j_id2:report_int_max_longitude VALUE:
KEY: j_id2:report_int_min_latitude VALUE:
KEY: javax.faces.ViewState VALUE: j_id28
KEY: j_id2:system_REPORT_FILENAME VALUE: city
KEY: j_id2 VALUE: j_id2
更新
改变 <h:form>
标签包含 id="form"
属性结果:
KEY: form:system_REPORT_FILENAME VALUE: city
KEY: form VALUE: form
KEY: form:report_city VALUE: ab
KEY: form:report_int_max_longitude VALUE:
KEY: form:report_REPORT_TITLE VALUE: Canadian City List
KEY: form:system_REPORT_RESOURCE VALUE: city
KEY: form:report_int_min_latitude VALUE:
KEY: form:j_id10 VALUE: Report
KEY: javax.faces.ViewState VALUE: j_id1
这样更好,但仍不理想。
更新2
代码需要通用解析输入表单参数名称。到目前为止,以下代码可以删除前缀(但感觉有点老套):
/**
* Appends the list of HTTP request parameters to the internal parameter
* map of user input values. Some frameworks prepend the name of the HTML
* FORM before the name of the input. This method detects the colon and
* removes the FORM NAME, if present. This means that input parameter
* names assigned by developers should not contain a colon in the name.
* (Technically, it is possible, but to avoid potential confusion it
* should be avoided.)
*/
protected void setInputParameters() {
HttpServletRequest request = getServletRequest();
Iterator<String> keys = getExternalContext().getRequestParameterNames();
Parameters p = getParameters();
while( keys.hasNext() ) {
String key = keys.next();
for( String value : request.getParameterValues( key ) ) {
int i = key.indexOf( ':' );
if( i >= 0 ) {
key = key.substring( i + 1 );
}
p.put( key, value );
}
}
}
问题
什么 API 调用返回没有 j_id2
的参数名称前缀?
删除 j_id2
前缀(和可选的完整冒号)可能会引入依赖于框架的代码。
谢谢!
最佳答案
我不认为有 API 可以做到这一点,j_id2:XXX 是实际的请求参数名称。
关于HttpServletRequest 中的 JSP 参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411767/