解决SpringBoot项目通过Controller的return没法跳转页面的问题

本文详细记录了解决SpringBoot项目中Controller跳转页面时出现的模板解析错误问题,通过调整pom.xml中的资源过滤设置,成功实现了页面的正常跳转。

Error resolving template [index], template might not exist or might not be accessible by any of the configured Template Resolvers

这个是我的报错。

我在SpringBoot项目中的Controller中通过return跳转页面的时候无法跳转,项目报上面的异常。首先我把Controller类中的注解@RestController修改为了@Contrller,但是没有什么作用,接着我在Controller类中的方法上面添加了注解@Responsebody,这个时候发现页面还是没有跳转成功,但是页面直接打印出来我返回的内容。随后我检查了自己的项目目录,关键是templates的位置,对比了我的配置文件application.yml中关于thymeleaf的配置。

仔细对照,并没有什么不对的地方。然后我查看了添加的依赖,我的依赖是

<dependency>       

    <groupId>org.springframework.boot</groupId>      

    <artifactId>spring-boot-starter-thymeleaf</artifactId>    

</dependency>

依赖也没有问题。最后我注意到我的pom.xml中的build中有一段配置

这段配置是为了项目能够扫描到xml或者priperties而配置的,其实并没有什么额外的作用,但是也就是这段配置导致找不到我的html页面,将他们注释掉就好了,或者在里面添加上html文件类型就好,通过Controller中的return就可以正常跳转页面了。

Controller类中的跳转方法:

@RequestMapping(value = "/index")
@ResponseBody
public ModelAndView index(Model model){
    model.addAttribute("boot_name","jack");
    model.addAttribute("boot_age",20);
    model.addAttribute("boot_info","jack,success");
    return new ModelAndView("index");
}

添加html类型如下:

<!--保证配置文件能被扫描到-->
<resources>
  <resource>
    <directory>src/main/java</directory>
    <includes>
      <include>**/*.yml</include>
      <include>**/*.properties</include>
      <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.yml</include>
      <include>**/*.properties</include>
      <include>**/*.xml</include>
      <include>**/*.html</include>
    </includes>
  </resource>
</resources>
在 Spring Boot 应用中,若希望 Controller 执行后不跳转页面,通常是指通过异步请求(如 AJAX)与后端交互,而不是触发传统的表单提交行为。这种情况下,前端页面不会刷新或导航到新页面,而是通过 JavaScript 接收响应并局部更新 UI。 ### 使用 `@ResponseBody` 返回 JSON 数据 Spring Boot 的 Controller 方法可以通过添加 `@ResponseBody` 注解,将返回值直接写入 HTTP 响应体中,而不是作为视图名称进行跳转。这种方式常用于构建 RESTful API 或前后端分离的场景。 ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class LoginController { @PostMapping("/login") public @ResponseBody User login(@RequestBody LoginForm form) { // 验证用户名和密码逻辑 if ("admin".equals(form.getUsername()) && "123456".equals(form.getPassword())) { return new User("admin", "登录成功"); } else { return new User(null, "用户名或密码错误"); } } static class User { private String username; private String message; public User(String username, String message) { this.username = username; this.message = message; } // Getter and Setter } static class LoginForm { private String username; private String password; // Getter and Setter } } ``` 上述代码中,`@RestController` 是 `@Controller` 与 `@ResponseBody` 的组合注解[^1],适用于所有方法都需要返回数据而非视图名称的场景。该方法接收 JSON 格式的请求体,并返回 JSON 数据,供前端 JavaScript 处理响应结果。 ### 使用 Thymeleaf 模板时保持当前页面不变 如果使用的是 Thymeleaf 等模板引擎,并且希望在表单提交后不跳转页面,可以结合 AJAX 请求实现异步交互。例如,在 HTML 页面中使用 `fetch` 发送 POST 请求,并处理返回的 JSON 数据: ```html <form id="loginForm"> <input type="text" name="username" placeholder="用户名" /> <input type="password" name="password" placeholder="密码" /> <button type="submit">登录</button> </form> <div id="message"></div> <script> document.getElementById('loginForm').addEventListener('submit', function(event) { event.preventDefault(); // 阻止默认提交行为 const formData = new FormData(this); fetch('/login', { method: 'POST', body: JSON.stringify(Object.fromEntries(formData)), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { document.getElementById('message').innerText = data.message; }) .catch(error => { console.error('请求失败:', error); }); }); </script> ``` 此示例中,通过 `fetch` 提交登录信息,并解析后端返回的 JSON 数据,将提示信息动态显示在页面上,从而避免页面刷新或跳转。 ### 配置 CORS 支持以允许跨域请求 当前端与后端运行在不同端口或域名下时,需配置跨域资源共享(CORS),确保浏览器允许异步请求访问后端接口: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") // 允许跨域的路径 .allowedOrigins("*") // 允许的源 .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法 .allowedHeaders("*"); // 允许的头部 } } ``` 以上配置允许指定路径下的接口接受来自任意来源的请求,适用于前后端分离架构中的开发环境[^1]。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

one_smail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值