【问题标题】:Spring boot does not load jsp filespring boot不加载jsp文件
【发布时间】:2021-03-30 05:12:31
【问题描述】:

使用spring boot starter 2.4.1 version.

resources 文件夹具有以下结构。正如所见,hello.jsp 位于模板文件夹中。这些都包含在 application.properties 中:

  spring.mvc.view.prefix=/templates/
  spring.mvc.view.suffix=.jsp

还有一个简单的控制器:

@Controller
public class HelloController {
    @GetMapping("/hello")
    public String index(){
        return "hello";
    }
}

但是得到 404

控制器方法肯定进入了。

尝试了following answer 中的建议,尝试使用 webapp,但没有帮助:/WEB-INF 没有在目标内创建根本,看来 maven 忽略了 webapp 和 WEB-INF 文件夹。

【问题讨论】:

  • 你怎么知道'控制器方法肯定进入'?
  • 调试、日志记录。
  • 文件是从classpath:/templates而不是templates加载的。这和 JSP 仅适用于 WAR 文件而不是 JAR 文件,并且受到限制。
  • @M.Deinum 你是对的。这就是 spring-boot 为 thymeleaf 设置的内容:docs.spring.io/spring-boot/docs/1.3.0.M1/reference/html/…。但是当我在我的属性文件中设置 classpath:/templates 时(不添加 thymleafe 依赖项)它不起作用。所以我发现的唯一(而且我确信不是有效的)解决方案是将 thymleaf 依赖添加到 pom 中。

标签: java spring spring-boot maven thymeleaf


【解决方案1】:

只需使用无效缓存 (File | Invalidate Caches / Restart) 重新启动 Inellij IDEA 即可解决问题。

实际上它开始使用模板文件夹,因此模板是根目录,并且您在其中放置一些东西,您可以从控制器访问而无需任何prefix 设置。

但是 webapp 又没有什么是可行的,seams maven 完全忽略了 webapp。也许这与 maven 或 spring-boot 版本有关。

并添加 thymeleafe 依赖项,它将与 .html 文件一起使用(这不是我喜欢的东西,但到目前为止找到的唯一可行的解​​决方案)。

【讨论】:

    【解决方案2】:

    尝试更改您的配置和代码,如下所示:

    in application.properties put these configs:
    
    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
    
    
    LoginForm class:
        public class LoginForm {
            private String email;
            private String password;
    
            public LoginForm() {}
            public String getEmail() { return email; }
            public void setEmail(String email) { this.email = email; }
            public String getPassword() { return password; }
            public void setPassword(String password) { this.password = password; }
        }
    
    **LoginForm is just a normal bean with a no-arg Constructor and the getters / setters**
    
    Now, we create a LoginHandler Class to coordinate and handle the whole login process.
    
        @Controller
        @RequestMapping("/login")
        public class LoginHandler {
        private static final String LOGIN_VIEW = "login";
        private static final String LOGOUT_VIEW = "logout";
        }
    
    let’s define some handler methods.
    
        @GetMapping("/login")
        public String showLoginView(Model model) {
        model.addAttribute("loginForm", new LoginForm());
        return LOGIN_VIEW;
        }
    

    【讨论】:

      【解决方案3】:

      好的,我会修复你的代码并在你的 IDE 中运行,

       @RequestMapping("/hello")
      public String index() {
          return "hello";
      }

      【讨论】:

      • 事实并非如此。方法 index() 在我的代码中被正确调用。问题出在 jsp 文件位置/路径或其他问题上。
      • 是的,我累了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2021-04-15
      相关资源
      最近更新 更多