Can servlet attribute names contain a hyphen -?

后端 未结 2 1318
自闭症患者
自闭症患者 2021-01-24 03:25

Can servlet attribute names contain a hyphen -?

Because, I tried to retrieve the attributes from the request set in the doPost in my servlet, b

相关标签:
2条回答
  • 2021-01-24 04:08

    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
    0 讨论(0)
  • 2021-01-24 04:11

    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.

    0 讨论(0)
提交回复
热议问题