JSP文件未在浏览器中加载,但文件名在Spring Boot Application中的浏览器中显示为String

时间:2018-09-17 09:08:47

标签: spring-boot

index.jsp或任何.jsp文件(以及.html文件),我无法在浏览器中显示,但是当我使用字符串类型方法作为索引方法时,文件名在浏览器中显示为字符串。 但是,如果我使用ModelAndView类,则可以正常工作。如何使用字符串类型的方法显示页面? 我浏览了许多示例,并访问了包括stackoverflow.com在内的许多站点。波纹管所有相关文件:

  1. 控制器类

    @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. 输出:

enter image description here

预期页面如下: enter image description here  文件夹位置正常。我尝试使用不同的IDE和文件位置的各种组合以及pom中的所有依赖关系进行了很多次。但是每次都会出错。

2 个答案:

答案 0 :(得分:2)

之所以会这样,是因为@RestController正在将响应发送到浏览器主体,因此要返回JSP页面,请使用@Controller批注。

@RestController更改为@Controller

  • @Controller用于将类标记为Spring MVC Controller。
  • @RestController是一个便捷注释,仅添加了@Controller@ResponseBody注释(请参阅:[Javadoc] [1])

查看两者之间的区别。 Difference between spring @Controller and @RestController annotation

答案 1 :(得分:1)

发生这种情况是由于@RestController注释,因为当我们要以JSON返回内容时会使用此注释。 ->您可以将注释更改为@Controller,否则返回包含您的JSP文件的模型