无法将模型对象添加到 "/" 中的 jsp 视图中,但相同的方法在调用 /index 时有效



这是我正在开发的网站的链接

35.200.161.123/沙赫巴兹汗/索引

35.200.161.123/ShahbazKhan/(有关问题,请参阅最新新闻部分(

它们都是由相同的控制器方法处理并返回相同的页面。 问题是对/index 的调用正常工作,而当我访问我的网站时,就像 35.200.161.123/ShahbazKhan/一样,"帖子"对象没有传递给 jsp。 这是索引控制器的代码

@Autowired
private PostService postService;
@RequestMapping(value={"/","index"})
public ModelAndView index(HttpServletRequest req){
HttpSession session = req.getSession();
List<Post> posts = postService.findLatest3();
ModelAndView mv = new ModelAndView("index");
mv.addObject("posts", posts);
mv.addObject(session);
return mv;
}

我缺少一些配置??该项目是使用 Spring Boot 构建的

图像 1

问题所在

项目目录结构

应用程序属性文件

spring.datasource.url = jdbc:mysql://xx.xx.xx.xx/shahbazkhan
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password= xxxxxxxxxx
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update 

spring.resources.static-locations=classpath:/static
spring.mvc.view.prefix: /
spring.mvc.view.suffix: .jsp

Web服务器的默认行为(即将35.200.161.123/ShahbazKhan/等所有请求传递给35.200.161.123/ShahbazKhan/index(不再适用。所有请求都将传递到控制器,并与您提供的视图解析程序属性进行比较。应用程序服务器检查请求的资源在 WEB-INF 文件夹中是否可用,并在处理后返回资源。

如果未找到资源,则 Web 服务器默认提供静态页面。

目前,您的所有视图都在webapps文件夹下公开可用,因此在调用projectsite/时,不会调用索引控制器,并且没有jsp对象即可按原样提供"index.html"。

您必须将所有 Spring、Hibernate 和其他 Java 资源放在 WEB-INF 文件夹中,因为每当传递请求时都会查找此文件夹。参考: https://vitalflux.com/web-application-folder-structure-spring-mvc-web-projects/, https://blogs.quovantis.com/spring-project-best-practices

然后,您必须告诉应用程序服务器在所有请求前面加上/WEB-INF/。您必须通过将spring.mvc.view.prefix: /更改为spring.mvc.view.prefix: /WEB-INF/来在视图解析程序中提供该属性

最新更新