JSP file does not load in browser but file name is displayed as String in browser in spring Boot Application

Viewed 823

index.jsp or any .jsp file (.html files as well), I can't display in the browser rather file name is displayed as a string in the browser when I use string type method for index method. However, if I use ModelAndView class then it works fine. How I can display a page using string type method ? I have gone through lots of examples and visited many sites including stackoverflow.com. Bellow all related files:

  1. Controller Class

    @SpringBootApplication
    public class DemoApplication {
    
    public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);}
    
  2. @RestController
    public class AppController extends SpringBootServletInitializer {
    
    /*following method don't works*/
    @RequestMapping("/home")
    public String index(){
    return "index";
    }
    /*following method works fine*/
    /*   @RequestMapping("/home")
    public ModelAndView modelAndView(){
    return new ModelAndView("index");
    }*/
    }
    
  3. POM.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- JSTL for JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    
    <!-- Need this to compile JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    
  4. Application.properties

    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
    
  5. Output:

enter image description here

The expected page should be as follows: enter image description here Folder location is ok. I tried many times with different IDE and various combination of file location, and all dependency in pom. But every time getting error.

2 Answers

This is happening because the @RestController is sending the response to the browser body so to return JSP page use @Controller annotation instead.

Change @RestController to @Controller.

  • @Controller is used to mark classes as Spring MVC Controller.
  • @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations (see: [Javadoc][1])

See difference between both. Difference between spring @Controller and @RestController annotation

This happens due to @RestController annotation as this is used when we want to return things in JSON. --> You can change the annotation to @Controller else return Model containing your JSP file

Related