There is a class with private fields. If you pass an object of this class to a JSP page, the JSP page will have access to the private fields of the object. Why it happens?

public class Main { private int value; private String str; public int getValue(){ return value; } public void setValue(int value) { this.value = value; } publi String getStr(){ return str; } public void setStr(String str) { this.str = str; } } // передаем объект jsp странице Main obj = new Obj(); obj.setValue(42); obj.setStr("42"); req.setAttribute("obj", obj); getServletContext().getRequestDispatcher("/jsp/page.jsp").forward(req, resp); // page.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <p><c:out value="${obj.value}"/></p> <p><c:out value="${obj.str}"/></p> </body> </html> 
  • 2
    JSP uses get methods to get private field values. For example, a field called name will be available from JSP via getName () getter, but if you don’t correctly name the method (for example, getNames ()) then the jsp page just won’t find your field! - Andrey Sibirkin

2 answers 2

Nothing like this.

 obj.value; 

This record means that метод-геттер for the value field of the obj object will be called.

Ie a similar entry should be interpreted like this:

obj.get Value ();

  • @Other doing a rollback, because the formatting for the code devoured the fatness of the selected fragment, which I deliberately singled out - dirkgntly
  • In the code it is better not to use such formatting tools, describe the significance of the words, if necessary. But your business. - user207618
  • I usually use comments with arrows aligned in an important section of the code, like // ^^^^^ , something like the Clang error output format (in the screenshot below). - D-side

Access to private fields is possible in this case, because for these fields there are public getters. This is the same as the ability of the heir to access the private fields of the ancestor through public ancestor getters that the heir inherited.