17.11.18

Ejemplo de uso Spring vista JSP

Versión Spring Boot 2.1.0.RELEASE

Añadir las dependencias (no poner <scope>provided</scope> si no es para un WAR que se desplegara en un servidor de aplicaciones):

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

Luego, crear el ViewResolver con el sufijo y el directorio dentro de src/main/webapp:

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    
    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
    @Bean
    public Operacion operacionSuma5en5 ()
    {
        return new Operacion() {
            private int a=0;
            private int b=0;
            @Override
            public void establecerValorA(int a) {
                this.a=a;
            }

            @Override
            public void establecerValorB(int b) {
                this.b=b;
            }

            @Override
            public double realizarCalculo() {
                return IntStream.rangeClosed(Math.min(a,b),Math.max(a,b))
                        .filter(i->(i-a)%5==0).sum();
            }
            
        };
    }
    
}

También se podrían añadir en application.properties en la carpeta src/main/resources.

Ver este post para componentes Operacion.

Después, controlador sin @ResponseBody (se enviará a vista):

@Controller
public class BasicController implements ApplicationContextAware  {
    
    AtomicInteger i;
  
    ApplicationContext ac;
    
    @Autowired
    @Qualifier("sumarRango")
    private Operacion op1;

    @Autowired
    @Qualifier("sumarPares")
    private Operacion op2;
       
    private Operacion op3;    
    
    @PostConstruct
    public void init()
    {
        i=new AtomicInteger(0);
        op3=ac.getBean("operacionSuma5en5", Operacion.class);
        op1.establecerValorA(0);
        op2.establecerValorA(0);
        op3.establecerValorA(0);
    }

    @RequestMapping("/")
    public String index(Model model) {
        int i=this.i.getAndIncrement();
        op1.establecerValorB(i);
        op2.establecerValorB(i);
        op3.establecerValorB(i);
        String[] results=new String[3];
        results[0]="The sum from "+0+" to "+i+" is " + op1.realizarCalculo()+".";
        results[1]="The sum of even numbers from "+0+" to "+i+" is " + op2.realizarCalculo()+".";
        results[2]="The sum of numbers every 5 from "+0+" to "+i+" is " + op3.realizarCalculo()+".";        
        model.addAttribute("resultados", results);        
        return "home";
    }    
    
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac=ac;
    }

}

Añade atributo a través de "addAttibute" de model y retorna el nombre de la vista.

Y por último, la vista (home.jsp en este caso):

<%   
    String[] resultados=(String[])request.getAttribute("resultados");    
%>
<html>
    <body>
        <H1>Lista de resultados</H1>
        <ul>
            <% for(String resultado:resultados) { %>
                <li><%=resultado%></li>
            <% } %>
        </ul>
    </body>
</html>

Y esto es todo.

No hay comentarios :