背景

初学java,在学习spring时,一步一步安装视频教程进行配置,编码,在最后运行时,却无法访问controller中的请求,提示404。首页可正常访问,因controller中直接指向了一个静态jsp文件,经测试,直接修改url可以正常访问该页面,但经过controller访问却提示404。

HTTP状态 404 - 未找到
类型 状态报告

描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。

Apache Tomcat/9.0.36

实现代码

1、pom.xml中已经正确配置了所需的dependency。
2、web.xml配置如下

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3、UserController代码:

@Controller
public class UserController {

    @RequestMapping("/quick")
    public String save(){
        System.out.println("Controller save running ...");
        return "success.jsp";
    }
}

4、spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven/>
    <context:component-scan base-package="info.hnbc.controller"/>
</beans>

分析

在反复测试后,发现根本就没有进入到Controller中,初步估计是根本就没有正确扫描到我们的controller,也就是在ioc容器进行解析我们的UserController时出错。各种折腾后发现在打包过程中,没有jar包,这也就导致ioc容器无法正常加载,从而导致UserController类没有加载打包给tomcat。具体原因还在研究,先介绍解决方法,后续再进行更新。

解决方案

打开Project Structure,选择Artifacts选项卡,在右侧,展开WEB-INF,新建一个名为lib的文件夹,
spring-mvc-study-1.png

之后将对应的库添加到lib下,重新运行即可解决。

标签: spring mvc, HTTP状态 404, controller

添加新评论