1

Hello all I am working on java using thymeleaf.

this is my method to load dashbaord page:

@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        mav = new ModelAndView("index.html");
    } else {
        mav = new ModelAndView("dashbaord.html");
    }
    return mav;
}

In above method if user is logged in it will load dashbaord.html page which is designed to render layouts/default.html BUT if user is not logged in and tries to load dashboard page, it should go to index.html

BUT in my case index page doesn't contain any layout and when user tries to load dashboard page without login it gives me rendering error for layouts/default.html because index page is not designed to render anything from layouts. it is a separate page with no layout.

I have followed this configuration for my layouts rendering.

Index Page RequestHandler:

@Layout(Layout.NONE)
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = null;
    mav = new ModelAndView("index.html");
    return mav;
}

Any idea, how can I set the layout conditionally ?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
Bilal Zafar
  • 447
  • 7
  • 20
  • maybe you should redirect the request from `/dashboard` to `/` if user is not logged – neo Dec 06 '17 at 11:17

2 Answers2

2

try this:

@Layout("layouts/default.html")
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String Dashboard() {
    ModelAndView mav = null;
    if (session.getAttribute("loginStatus") != "1") {
        return "redirect:/";
    } else {
        return "dashbaord.html";
    }

}
neo
  • 604
  • 3
  • 10
0

Correct answer :

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView Dashboard(HttpSession session) {

    ModelAndView mav = null;
    mav = new ModelAndView("dashbaord.html");
    if (session.getAttribute("loginStatus") != "1") {
        mav=new ModelAndView("redirect:/");
    } else {
        mav=new ModelAndView("dashbaord.html");
    }
    return mav;
}
Bilal Zafar
  • 447
  • 7
  • 20