2

I am trying to develop web application using Spring WebFlux5.0.1 and Spring boot v2.0 M6 version. Requirement is to store objects in session and use it in subsequent pages/controllers.

Controller

@Controller
public class TestController {

    @RequestMapping("/")
    public Mono<String> testSession(Model model,ServerWebExchange swe){
        Mono<WebSession> session = swe.getSession();
        System.out.println("In testSession "+session);

        model.addAttribute("account", new Account());
        return Mono.just("account");
    }
}

I was able to get Websession object from ServerWebExchange but i dont see methods to set/get attributes

Need help to understand how to use WebSession object in reactive world

codependent
  • 23,193
  • 31
  • 166
  • 308

2 Answers2

3

Is it what you want to do ?

swe.getSession().map(
    session -> { 
        session.getAttribute("foo"); // GET
        session.getAttributes().put("foo", "bar") // SET
    }
);
3

The accepted solution is incomplete in my opinion since it doesn't show the whole controller method, here it is how it would be done:

@PostMapping("/login")
fun doLogin(@ModelAttribute credentials: Credentials, swe: ServerWebExchange): Mono<String> {
    return swe.session.flatMap {
        it.attributes["userId"] = credentials.userId
        "redirect:/globalPosition".toMono()
    }
}
codependent
  • 23,193
  • 31
  • 166
  • 308