springmvc(2)

1.使用注解开发springmvc,不用配置HandlerMapping和HandlerAdapter,处理请求的controller也不用手动配置为bean

只需在springmvc配置文件中加上下述代码即可:

context:component-scan标签会自动扫描base-package指定的包中@controller注解的java类,而base-package表示com.app.web包下面的controller会被自动注入为bean。

Controller代码:

@Controller注解表示当前java是一个controller,上面的context:component-scan会叫当前类注入到mvc配置文件当中@RequestMapping表示当url链接为hello时执行当前方法:

web.xml配置文件:

与上一次配置不同的是新加入了init-param标签:这个标签需要卸载load-on-startup上面,否则会提示错误:

Invalid content was found starting with element '{"http://xmlns.jcp.org/xml/ns/javaee":init-param}'. One of '{"http://xmlns.jcp.org/xml/ns/javaee":enabled, "http://xmlns.jcp.org/xml/ns/javaee":async-supported, "http://xmlns.jcp.org/xml/ns/javaee":run-as, "http://xmlns.jcp.org/xml/ns/javaee":security-role-ref, "http://xmlns.jcp.org/xml/ns/javaee":multipart-config}' is expected.

init-param里面的contextConfigLocation 代表mvc配置文件去下面这个位置查找,如果不配置的话默认是在web-inf中的【DispatcherServletName】-servlet.xml文件即(dispatcherServlet-servlet.xml),如果加入配置的话就可以自行指定位置以及文件名称了。

关于servlet-mapping的url-pattern问题:如果想拦截所有请求那么请写【/】而不是【/*】,因为/*的路径等级只在精确匹配之下,所以他会拦截大部分的请求,比如当你执行完方法后需要去找hello.jsp的时候也会被他拦截,这是他会在你的dispatcherServlet中找hello.jsp这个方法,但是你肯定没写过这个方法,就会报错。url-patter优先级:https://www.cnblogs.com/yuby/p/10753357.html

原文地址:https://www.cnblogs.com/yuby/p/11000097.html