Spring MVC Pass messages to the view

0

Greetings I want in the index to show the message made in a controller with a background provided by Boostrap. When starting the application the variable message has no content and paints the background of the boostrap.

How do you do it so that it is only painted if you have data?

Index:

 <!-- Mensajes -->
         <div class="alert alert-info">${mensaje}</div>
 <!-- mensajes -->

Controller:

ModelAndView vista = new ModelAndView() ;
vista.setViewName("index");
vista.addObject("mensaje", "Insertado Correctamente");

return vista;

My idea was: But it gives error

<!-- Mensajes -->
         <% if (${mensaje} != null)
             <div class="alert alert-info">${mensaje}</div>
         %>   
     <!-- mensajes -->
    
asked by EduBw 26.02.2018 в 22:13
source

1 answer

3

This <% %> is a scriptlet . Within this block you are working with Java code. The HTML code goes out.

To access an element added to ModelAndView , you make request.getAttribute .

<% if (request.getAttribute("mensaje") != null) { %>
         <div class="alert alert-info">${mensaje}</div>
<% } %>   

That said, scriptlets are considered obsolete and it is strongly recommended to avoid them, especially for new applications. For example, with scriptlets you can not easily verify that you close the block of if , which can lead to problems at runtime.

As an alternative, it is recommended to use the JSTL

 <c:if test="${not empty mensaje}">
      <div class="alert alert-info">${mensaje}</div>
 </c:if>

This can be analyzed to verify that your document is valid XHTML.

Another alternative is JSF, but that is already a very important jump

    
answered by 27.02.2018 / 11:40
source