Pergunta

If I have a bean that contains the following code:

private String method;

public String getMethod() {
    return method;
}

public void setMethod(String method) {
    this.method = method;
}

Is it necessary to:

request.setAttribute("method", method );

For every variable that I want to be visible from the JSP?

Foi útil?

Solução 3

If method attribute is not set in request the evaluated ${method} expression will be null in jsp. If you need some value then you have to set it to that value.


There are 3 ways of doing this:

  1. With a session

    request.getSession().setAttribute("method", this); and <c:out value="${mycontroller.method}"/>

  2. Set a single attribute

    request.setAttribute("method", method); and <c:out value="${method}"/>

  3. Set all attributes in the bean simultaneously by assigning the object to the bean

    request.setAttribute("mycontroller", this); and <c:out value="${mycontroller.method}"/>

Outras dicas

If method attribute is not set in request the evaluated ${method} expression will be null in jsp. If you need some value then you have to set it to that value.

In your servlert do post method;

public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException 
{       
 String formParameter = req.getParameter("someParameterName");
 //Your logic dependen on form parameter

 FormObject fo = new FormObject();
 fo.setMethod("new value"); 
 req.setAttribute("formObject", fo);
 req.getRequestDispatcher("/WEB-INF/yourJspPage.jsp").forward(req, res);
}

You java object:

public class FormObject{
      String method;

      public String getMethod(){
         return method;
      }

      public void setMethod(String method){
         return this.method = method;
      }
    }

in your yourJspPage.jsp:

<div>${fo.method}</div>

P.S. I haven't tried this example but the idea should be clear. you can search for jsp + servlet tutorial to understand what you are doing. There is similar what you want : enter link description here

session is similar to request just attributes added to this object last longer (different scope). But I think you should read more documentation and tutorials before asking help for every step.

For every variable that I want to be visible from the JSP?

No. You just have to set an instance of the bean as request attribute. With that available in JSP page, you can access the properties of that bean, with EL - ${beanInstance.method}.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top