Can servlet attribute names contain a hyphen -?

不打扰是莪最后的温柔 提交于 2020-03-16 08:17:07

问题


Can servlet attribute names contain a hyphen -?

Because, I tried to retrieve the attributes from the request set in the doPost in my servlet, but the result is not what I'm looking for.

In my servlet I have this :

String X_USER = request.getParameter("X-User");
request.setAttribute("X-User", X_USER);

String YYYY_YYYY = request.getParameter("Y_CODE");
request.setAttribute("Y-Code", YYYY_YYYY);

In my JSP where I want to show these attributes I do this:

<li>${X-User}</li>
<li>${Y-Code}</li>

The problem is that I'm getting 0 instead of the parameter value.


回答1:


Your concrete problem is not the HTTP request parameter, but the EL variable name. All Java keywords and identifiers are illegal in EL variable names.

The - is a subtraction operator in Java (and also in EL). How should the EL processor know if you meant to use an attribute with the literal name X-User or the result of an integer subtraction of ${User} from ${X}? It's by specification interpreted as latter which also explains the numeric result of 0.

Just use underscore or camelcase instead, like as in normal Java.

request.setAttribute("Y_User", X_USER);
request.setAttribute("Y_Code", Y_CODE);
${X_User}
${Y_Code}

If you absolutely need to access a request attribute containing a hyphen in EL, then use the brace notationon the request scope map:

${requestScope['X-User']}
${requestScope['Y-User']}

The same applies to request parameters, by the way, which you don't necessarily need to copy over into the request scope in the servlet:

${param['X-User']}
${param['Y-Code']}

See also:

  • EL 3.0 specification
  • Our EL wiki page



回答2:


You can use implicit object of jsp as

response.getAttribute("X-User");
response.getAttribute("Y-Code");

As you're setting attribute from servlet there is no need to get it via jstl.



来源:https://stackoverflow.com/questions/32228010/can-servlet-attribute-names-contain-a-hyphen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!