Programing

Spring-mvc에서 세션 속성을 사용하는 방법

lottogame 2020. 8. 24. 20:50
반응형

Spring-mvc에서 세션 속성을 사용하는 방법


이 코드의 봄 mvc 스타일 아날로그를 작성하는 데 도움을 줄 수 있습니까?

 session.setAttribute("name","value");

그리고 주석으로 @ModelAttribute주석 이 달린 요소 를 세션에 추가하고 액세스하는 방법은 무엇입니까?


세션이 필요하지 않은 각 응답 후 객체를 삭제하려면

사용자 세션 동안 개체를 유지하려면 몇 가지 방법이 있습니다.

  1. 세션에 하나의 속성을 직접 추가하십시오.

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";
    }
    

    다음과 같이 컨트롤러에서 가져올 수 있습니다.

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
    
  2. 컨트롤러 세션 범위 지정

    @Controller
    @Scope("session")
    
  3. 예를 들어 매번 세션에 있어야하는 사용자 개체가 있습니다.

    @Component
    @Scope("session")
    public class User
     {
        String user;
        /*  setter getter*/
      }
    

    그런 다음 원하는 각 컨트롤러에 클래스를 삽입하십시오.

       @Autowired
       private User user
    

    수업을 계속 진행합니다.

  4. AOP 프록시 주입 : spring -xml :

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
      <bean id="user"    class="com.User" scope="session">     
          <aop:scoped-proxy/>
      </bean>
    </beans>
    

    그런 다음 원하는 각 컨트롤러에 클래스를 삽입하십시오.

    @Autowired
    private User user
    

5. HttpSession을 메서드에 전달합니다.

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";
        }

6. @SessionAttributes ( "ShoppingCart")로 세션에서 ModelAttribute 만들기 :

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();
}

또는 전체 컨트롤러 클래스에 모델을 추가 할 수 있습니다.

@Controller
    @SessionAttributes("ShoppingCart")
    @RequestMapping("/req")
    public class MYController {

        @ModelAttribute("ShoppingCart")
        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session
        }  
      }

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.

To access session jsp

<%=session.getAttribute("ShoppingCart.prop")%>

in Jstl :

<c:out value="${sessionScope.ShoppingCart.prop}"/>

in Thymeleaf:

<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.


SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation. In below eg, personObj will be available in session.

@Controller
@SessionAttributes("personObj")
public class PersonController {

    @RequestMapping(value="/person-form")
    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());
    }

    @RequestMapping(value="/process-person")
    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("person-result-page");

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;
    }

}

The below annotated code would set "value" to "name"

@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";
  }
}

To access the same in JSP use ${sessionScope.name}.

For the @ModelAttribute see this link


Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:

@GetMapping
public String hello(HttpSession session) {
    session.setAttribute("name","value");
    return "hello";
}

p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.


Try this...

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")

    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

When I trying to my login (which is a bootstrap modal), I used the @sessionattributes annotation. But problem was when the view is a redirect ("redirect:/home"), values I entered to session shows in the url. Some Internet sources suggest to follow http://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#mvc-redirecting But I used the HttpSession instead. This session will be there until you close the browsers. Here is sample code

        @RequestMapping(value = "/login")
        @ResponseBody
        public BooleanResponse login(HttpSession session,HttpServletRequest request){
            //HttpServletRequest used to take data to the controller
            String username = request.getParameter("username");
            String password = request.getParameter("password");

           //Here you set your values to the session
           session.setAttribute("username", username);
           session.setAttribute("email", email);

          //your code goes here
}

You don't change specific thing on view side.

<c:out value="${username}"></c:out>
<c:out value="${email}"></c:out>

After login add above codes to anyplace in you web site. If session correctly set, you will see the values there. Make sure you correctly added the jstl tags and El- expressions (Here is link to set jstl tags https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/)


Use This method very simple easy to use

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

in jsp once use then remove

<c:remove var="errorMsg" scope="session"/>      

In Spring 4 Web MVC. You can use @SessionAttribute in the method with @SessionAttributes in Controller level

@Controller
@SessionAttributes("SessionKey")
public class OrderController extends BaseController {

    GetMapping("/showOrder")
    public String showPage(@SessionAttribute("SessionKey") SearchCriteria searchCriteria) {
     // method body
}

참고URL : https://stackoverflow.com/questions/18791645/how-to-use-session-attributes-in-spring-mvc

반응형