JSP/Servlet expression language private variable access
Asked Answered
S

1

5

I am learning JSP and Servlet and I found something odd - If I use the following code:

request.setAttribute("m", m);
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);

where request is an HttpServletRequest object and m is an object of the Model class, I can access and display the values of the private variables of m in my JSP page (welcome.jsp).

Relevant JSP code for welcome.jsp:

Hello, <strong>${m.name}</strong>! Your data has been validated and is displayed below:<br/>
<br/>
Number: <strong> ${m.number} </strong>
<br/>
<br/>
Birth Month: <strong> ${m.month} </strong>

Relevant Java code for the Model class:

public class Model {
    private String name;
    private String number;
    private String[] hobby;
    private int month;
    // remaining code...
Stott answered 22/1, 2014 at 11:51 Comment(0)
F
8
${m.name}

does basically the same as the following in "raw" scriptlet code

<%
  Model m = (Model) pageContext.findAttribute("m");
  if (m != null) {
  String name = m.getName();
   if (name != null) {
    out.print(name);
   }
 }
%> 

${m.name} calls getName() which is public in class Model.
Do not get confused it is not accessing private variable name directly.

Referred link

Frig answered 22/1, 2014 at 12:10 Comment(2)
Just to clarify, you mean to say that accessing a private variable in EL is not done directly, rather the getter is called internally at runtime?Stott
@Stott : Yes. To learn more please refer above mentioned link.Frig

© 2022 - 2024 — McMap. All rights reserved.