为什么@EnableWebMvc会导致查找静态资源失败(o.s.web.servlet.PageNotFound:没有GET映射)

问题描述 投票:0回答:1

我正在使用 Spring Boot 和 Redis 编写用户登录页面。如果我在 webConfig 中添加

@EnableWebMvc
,我将收到以下错误,并且本地主机无法找到静态资源。如果我注释掉
@EnableWebMvc
,代码就会工作并且我的登录页面会正常运行。背后的原因是什么?教程源代码包括
@EnableWebMvc
,代码在教程视频中运行。

错误:

2023-08-26 17:15:31.381 警告 25399 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound :没有 GET 映射 /js/jquery.min.js 2023-08-26 17:15:31.434 警告 25399 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound :否 GET /bootstrap/css/bootstrap.min.css 的映射 2023-08-26 17:15:31.435 警告 25399 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound :没有 GET 映射 /jquery-validation/localization/messages_zh.min.js 2023-08-26 17:15:31.468 警告 25399 --- [nio-8080-exec-5] o.s.web.servlet.PageNotFound :没有 GET 映射 /jquery-validation/jquery.validate.min.js 2023-08-26 17:15:31.468 警告 25399 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound
:没有 GET /bootstrap/js/bootstrap.min.js 的映射 2023-08-26 17:15:31.474 警告 25399 --- [nio-8080-exec-7] o.s.web.servlet.PageNotFound :没有 GET 映射 /layer/layer.js 2023-08-26 17:15:31.579 警告 25399 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound :否 GET /js/common.js 的映射 2023-08-26 17:15:31.580 警告 25399 --- [nio-8080-exec-8] o.s.web.servlet.PageNotFound :否 GET /js/md5.min.js 的映射 2023-08-26 17:15:31.664 WARN 25399 --- [io-8080-exec-10] o.s.web.servlet.PageNotFound :否 GET /login/@%7B/img/bg.jpg%7D 的映射

正确的登录页面图片:

网络配置

package com.xxxx.seckill.config;

import com.xxxx.seckill.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableWebMvc
// enabling EnableWebMvc will cause spring boot to not serve static resources and "o.s.web.servlet.PageNotFound: No mapping for GET /"
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private UserArgumentResolver userArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userArgumentResolver);

    }

}

我的登录.html

<!DOCTYPE HTML>
<html lang = "en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>

    <!-- jquery -->
    <script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
    <!-- bootstrap -->
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap/css/bootstrap.min.css}" />
    <script type="text/javascript" th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
    <!-- jquery-validator -->
    <script type="text/javascript" th:src="@{/jquery-validation/jquery.validate.min.js}"></script>
    <script type="text/javascript" th:src="@{/jquery-validation/localization/messages_zh.min.js}"></script>
    <!-- layer -->
        <!-- pop ups-->
    <script type="text/javascript" th:src="@{/layer/layer.js}"></script>
    <!-- md5.js -->
    <script type="text/javascript" th:src="@{/js/md5.min.js}"></script>
    <!-- common.js -->
    <script type="text/javascript" th:src="@{/js/common.js}"></script>

    <style type="text/css">
        html,body{
            height:100%;
            width:100%;
        }
        body{
            background:url("@{/img/bg.jpg}") no-repeat;
            background-size:100% 100%;
            padding-top:100px;
        }
    </style>

</head>
<body>

<form name="loginForm" id="loginForm" method="post"  style="width:50%; margin:0 auto;">

    <h2 style="text-align:center; margin-bottom: 20px">User Login</h2>

    <div class="form-group">
        <div class="row">
            <label class="form-label col-md-4">Please input your mobile number</label>
            <div class="col-md-5">
                <!-- mobile len requirement 11 digits-->
                <input id="mobile" name = "mobile" class="form-control" type="text" placeholder="mobile-number" required="true"  minlength="11" maxlength="11" />
            </div>
            <div class="col-md-1">
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="row">
            <label class="form-label col-md-4">Please input your password</label>
            <div class="col-md-5">
                <!-- password len requirement 6-16 digits-->
                <input id="password" name="password" class="form-control" type="password"  placeholder="password" required="true" minlength="6" maxlength="16" />
            </div>
        </div>
    </div>

    <div class="row" style="margin-top:40px;">
        <div class="col-md-5">
            <button class="btn btn-primary btn-block" type="reset" onclick="reset()">reset</button>
        </div>
        <div class="col-md-5">
            <button class="btn btn-primary btn-block" type="submit" onclick="login()">login</button>
        </div>
    </div>

</form>
</body>
<script>


    function login(){
        // validate content in the table first, after validation passes, call doLogin function
        $("#loginForm").validate({
            submitHandler:function(form){
                doLogin();
            }
        });
    }
    function doLogin(){
        g_showLoading();

        //get password input from user and do the first MD5 encoding
        var inputPass = $("#password").val();
        var salt = g_passsword_salt;
        var str = "" + salt.charAt(0) + salt.charAt(2) + inputPass + salt.charAt(5) + salt.charAt(4);
        var password = md5(str);

        $.ajax({
            url: "/login/doLogin",
            type: "POST",
            data:{
                mobile:$("#mobile").val(),
                password: password
            },
            success:function(data){
                // data is from RespBean, data fields need to match RespBean fields (code, message, object)
                // close the pop up window
                layer.closeAll();
                if(data.code == 200){
                    layer.msg("login successful");
                    // after log in successfully, the page jumps to good purchase page, it's a simplification from the usual case of user browsing around the mall and then purchase
                    window.location.href="/goods/toList";
                }else{
                    layer.msg("something wrong");
                    layer.msg(data.message) ;// data.msg won't work
                }
            },
            error:function(){
                layer.closeAll();
            }
        });
    }
</script>
</html>

登录控制器

@Controller
@RequestMapping("/login")
@Slf4j 
public class LoginController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/toLogin") //to log in page 跳转登录页
    public String toLogin(){
        return "login";
    }


    @RequestMapping("/doLogin")
    @ResponseBody
    //公用返回对象 response bean, to return response bean, need to @ResponseBody
    public RespBean doLogin(@Valid LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("LoginController doLogin running");
        // 接受传参 receive parameter from users with LoginVo
        log.info("{}", loginVo); //log can be used directly as it is included in Slf4j
        return userService.doLogin(loginVo, request, response);

    }
}

spring-boot authentication spring-mvc redis web-config
1个回答
0
投票

这个参考很有帮助!感谢@dbreaux

为什么 spring-boot 应用程序不需要@EnableWebMvc

我添加以下 addResourceHandlers 方法来与 @EnableWebMvc 结合使用,代码可以正常工作。

package com.xxxx.seckill.config;

import com.xxxx.seckill.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 *  MVC settings
 *  自定义用户参数
 *
 * @author maylai
 * @since 2023-08-12
 */
@Configuration
@EnableWebMvc
// enabling WebMvc will cause spring boot to not serve static resources and "o.s.web.servlet.PageNotFound: No mapping for GET /"
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private UserArgumentResolver userArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userArgumentResolver);

    }

    // 约定大于配置,又有配置文件yml,又有configurer情况下,configurer大于yml, 访问不到static resources
    // @EnableWebMVC must be coupled with the addResourceHandlers below. Without addResourceHandlers, need to comment out @EnableWebMvc
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.