How to get attribute of the one session Java, Spring

-1

I want to create a final variable, but get its value from a session started, for example

final static String variable = (String) new HttpServletRequest.getSession().getAttribute("codigoVerificacion");

I hope you can help me, since that code marks error.

    
asked by WaSoM 14.11.2016 в 22:04
source

2 answers

1

I do not know why you do new HttpServletRequest when the request should already be defined

String codigoVerificacion = (String)request.getAttribute("codigoVerificacion");
    
answered by 14.11.2016 в 22:13
1

In Spring, you can use @SessionAttributes , to put the object to the session first, as shown below:

@Controller
@SessionAttributes({"estudiante"})
public class Three {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        EstudianteDTO estudiante = new EstudianteDTO();
        estudiante.setNombre("Juan");
        model.addAttribute("greeting", "Hola");
        model.addAttribute("estudiante",estudiante);
        return "holamundo";
    }

}

This is the DTO:

public class EstudianteDTO implements Serializable {

    private static final long serialVersionUID = -5801289994733718288L;
    private String nombre;

    public String getNombre() {
        return nombre;
    }
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}

And to obtain the student attribute of the session with @SessionAttributes and @ModelAttribute in another Controller as follows:

@Controller
@SessionAttributes({"estudiante"})
public class Obtener {

    @RequestMapping(value="/obtener.htm", method=RequestMethod.GET)
    public String handleRequest(ModelMap model,@ModelAttribute("estudiante") EstudianteDTO estudiante){
        String datoNombre = "Nombre Estudiante:"+estudiante.getNombre();
        model.addAttribute("datoNombre", datoNombre);
        return "hola";
    }

}

to use it in a jsp, as shown below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HelloWorld page</title>
</head>
<body>
    Hola: ${estudiante.nombre}
</body>
</html>
    
answered by 16.11.2016 в 23:21