Can servlet attribute names contain a hyphen -?

2020-04-20 01:50发布

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.

标签: jsp servlets el
2条回答
甜甜的少女心
2楼-- · 2020-04-20 02:07

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:

查看更多
▲ chillily
3楼-- · 2020-04-20 02:22

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.

查看更多
登录 后发表回答