代码之家  ›  专栏  ›  技术社区  ›  Abdur Rahman sithum dilanga

JSP文件不在浏览器中加载,但文件名在SpringBoot应用程序的浏览器中显示为字符串

  •  2
  • Abdur Rahman sithum dilanga  · 技术社区  · 7 年前

    但是,如果我使用ModelAndView类,那么它就可以正常工作。如何使用字符串类型方法显示页面?

    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. <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 回复  |  直到 7 年前
        1
  •  2
  •   Alien    7 年前

    @RestController 将响应发送到浏览器主体以便返回JSP页面使用 @Controller

    改变 @控制器

    • @控制器 用于将类标记为Spring MVC控制器。
    • @REST控制器 @控制器 @ResponseBody 注释(参见:[Javadoc][1])

    Difference between spring @Controller and @RestController annotation

        2
  •  1
  •   Swapnil Sanu    7 年前

    这是由于@RestController注释造成的,因为当我们想要以JSON格式返回内容时使用了@RestController注释。