java学习中写不出代码怎么办 (springmvc接口无法访问)

springmvc自定义配置404页面,springmvc资源拒绝访问

今天在配置ssm的时候老是报404错误,控制台又没有错误信息,网上搜了很多资料,终于解决了。把我遇到的问题总结后有了以下内容!

1、检查请求的URL是否会被springmvc拦截

web.xml配置文件中,检查访问路径URL是否被springmvc拦截,对应关系如下图。

<可以先只看图中标注的代码,其余代码的关系会在后面几步依次确认是否正确>

2、检查Controller层是否使用@Controller注解

检查是否在Controll层使用@Controller注解来将其标注为组件;

只有使用了@Controller标注的Controller层才能被Springmvc识别.

3、检查springmvc.xml是否配置正确

springmvc自定义配置404页面,springmvc资源拒绝访问

3.1、检查是否配置了<context:component-scan/>及路径是否配置正确

1、<context:component-scan/>是用来指明让springmvc容器去哪里扫描@Controller注解,

只有springmvc找到了@Controller注解,springmvc才能进入Controller.

2、配置方式为:<context:component-scan base-package="com.taotao.controller" />

3、Base-package后面如果写成”com.taotao.controller.*”是错误的(不带*,定位到包即可).

4、Base-package后面的路径指的是Controller层所在的包,如图,注意路径一定要写对.

3.2、检查是否配置了<mvc:annotation-driven/>(上图中,第10行的配置)

解释:<mvc:annotation-driven/>相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean,配置一些messageconverter。

简单来说即解决了@Controller注解的使用前提配置。

配置方式如上图中第10行:<mvc:annotation-driven />

ps:<mvc:annotation-driven/>和<context:component-scan/>貌似不分先后顺序

4、检查是否web.xml文件中是否正确配置Springmvc

4.1、如果没有配置<init-param></init-param>

那么spring容器会自动去WEB-INF目录下扫描一个叫SpringMVC-servlet.xml的配置文件来加载springmvc容器.

4.2、如果如下图配置了<init-param></init-param>

重点检查一下是否classpath后面的路径书写的有错误.

注意:

1.只有成功读取到springmvc的xml配置文件,才能让spring容器加载springmvc容器,然后才能识别@Controller注解并执行标注的Contoller层

2.<param-name></param-name>之间的contextConfigLocation是固定的

springmvc自定义配置404页面,springmvc资源拒绝访问

PS:

web.xml加载spring容器的xml配置文件时,<param-name></param-name>之间的contextConfigLocation也是固定的.

springmvc自定义配置404页面,springmvc资源拒绝访问

5、检查是否成功加载spring容器

如果spring容器都未成功加载,那么肯定无法成功加载springmvc容器。

5.1、检查在web.xml中是否对spring容器正确配置

[html] view plain copy print?

  1. <!-- spring监听程序 -->

  2. <listener>

  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  4. </listener>

  5. <!-- 初始化spring的xml配置文件,注意路径 -->

  6. <context-param>

  7. <param-name>contextConfigLocation</param-name>

  8. <param-value>classpath:config/spring/applicationContext-*.xml</param-value>

  9. </context-param>

<!-- spring监听程序 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 初始化spring的xml配置文件,注意路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring/applicationContext-*.xml</param-value> </context-param>

代码截图及对应关系如下(如果看不清楚的话,可以保存到本地,然后用本地照片浏览器查看)

springmvc自定义配置404页面,springmvc资源拒绝访问

注意:再次强调,<param-name>标签中的contextConfigLocation是固定的,书写错误会报错。

如果有书写错误的地方,或者是有问题的地方请及时评论或者是私信,以免误导个别萌新。

感谢你长得那么美还来看小编的文章,喜欢就点关注吧!