Home > Software engineering >  spring boot MVC: how to redirect to a view
spring boot MVC: how to redirect to a view

Time:05-25

I try to do a java web application using SpringBoot and the MVC pattern. How to redirect to a view (html page) from this kind of function located in my controller:

@RequestMapping(value="/authentification", method= RequestMethod.POST)
    public @ResponseBody void logData(LoginForm lgf){
        if(diaDao.loggin(lgf.getMail(), lgf.getMdp()))
            //home
        else
            //loginPage
 
    }

CodePudding user response:

you won't be able to redirect to a page this way, you're returning the body of a response. you must not include @ResponseBody in the method signature, so that spring understands that it should look for a page.

your method needs to be like:

@RequestMapping(value="/authentification", method= RequestMethod.POST)
public String logData(LoginForm lgf){
    if(diaDao.loggin(lgf.getMail(), lgf.getMdp()))
        return "page_name";
    else
        return "page_name";

}

you can also use ModelAndView to redirect to a page and still send data to the page. thus:

@RequestMapping(value="/authentification", method= RequestMethod.POST)
public ModelAndView logData(LoginForm lgf){
    ModelAndView mv = new ModelAndView("page_name1");
    if(diaDao.loggin(lgf.getMail(), lgf.getMdp())) {
        mv.addObject("objectX", "objectValueX");
    } else {
        mv.setViewName("page_name2");
        mv.addObject("objectY", "objectValueY");
    }
    return mv;
}

CodePudding user response:

You have to add this library to your pom.xml :

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper</artifactId>
    <version>10.0.6</version>
</dependency>

And then you can do as below on your controller:

@RequestMapping(value="/authentification", method= RequestMethod.POST)
    public @ResponseBody void logData(LoginForm lgf){
        if(diaDao.loggin(lgf.getMail(), lgf.getMdp()))
            return "home.jsp";
        else
            return "loginPage.jsp";
 
    }
  • Related