【问题标题】:Cannot return HTML file from SpringBoot either as string or ModelAndView无法从 SpringBoot 以字符串或 ModelAndView 的形式返回 HTML 文件
【发布时间】:2021-10-21 23:29:41
【问题描述】:

我有一个 SpringBoot 应用程序,并且想在 API 调用上返回一个 html 页面(带有使用 thymeleaf 的令牌)。问题是 SpringBoot 给出 404 说它找不到端点(如果我不尝试返回 html 页面,它可以)。

我想要的是能够以某种方式返回 HTML 页面,用 thymeleaf 替换 ${token} 值。

项目结构(只有控制器和资源很重要)

主应用程序

@EnableEurekaClient
@EnableJpaRepositories({ "com.ps.oms.client.repository", "com.ps.oms.user.repository",
        "com.ps.oms.admin.BrokerDisable.repository" })
@EnableSwagger2
@SpringBootApplication
public class UserApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(UserApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }

}

控制器

@Controller
@RequestMapping("/api/v1")
@CrossOrigin(origins = "*", allowedHeaders = "*")
@Slf4j
public class AccountController {
    
    @GetMapping("/reset-password")
    public String showResetPasswordForm(@Param(value = "token") String token, Model model) {
        
        model.addAttribute("token", token);
        return "reset_password_form"; //this never works
        //return "redirect:/reset_password_form.html"; //this works if html file in static folder but cannot use thymeleaf
    }
}

HTML 文件

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- removed css -->

<title>Reset Password</title>
</head>

<body>
    <div class="logoblock">
        <p class="logoname">Order Management System</p>
    </div>
    <form class="reset-form">

        <label class="headlabel">Reset Your Password</label>
        <p th:text="${token}">Hi!</p>

        <div class="form-group">
            <input id="newPsw" class="psw-field" type="password" name="newPassword"
                placeholder="Enter New Password"> <span class="input-icon"><i
                class="fa fa-lock"></i></span>
        </div>

        <div class="form-group">
            <input id="confPsw" class="psw-field" type="password" name="confirmPassword"
                placeholder="Confirm Password"> <span class="input-icon"><i
                class="fa fa-lock"></i></span>
        </div>

        <button type="submit" onclick="savePass(event)" class="reset-btn">Reset</button>
    </form>
    

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script th:inline="javascript">

$(document).ready(function () {
    $('form').submit(function(event) {
        savePass(event);
    });
});

function savePass(event){
    event.preventDefault();
    
    var pswData = {
            newPassword: $("#newPsw").val(),
            confirmPassword:$("#confPsw").val(),
        }
    
    $.ajax({
        url: '/api/v1/reset-password',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        success: function(data){alert(data.message);},
        error: function(data){alert(data.responseJSON.message);},
        data: JSON.stringify(pswData)
    });
}

</script>
</body>
</html>

CORS 配置(我不知道这是否有任何作用)

@SuppressWarnings("deprecation")
@Configuration
public class CorsConfiguration {
    @Bean
    public WebMvcConfigurerAdapter corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/v1/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS");
                }
        };
    }
}

安全配置

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
    }
}

我在 POM.xml 中有以下可能与之相关的依赖项

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>


        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

【问题讨论】:

    标签: spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    在 web.xml 文件中添加您的 html 文件名。

    <servlet-mapping>
        <servlet-name>webapp</servlet-name>
        <url-pattern>/</url-pattern>  
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>/index.hml</url-pattern>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-11
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      相关资源
      最近更新 更多