第一:加载web.xml之后,读哪个配置文件问题?即是applicationContext.xml还是xxx-servlet.xml?
解答:①在web.xml中配置DispatcherServlet时,看下面代码红色
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
</servlet>
在没有<init-param>时,会自动寻找xxx-servlet.xml(即默认为xxx-servlet.xml,
默认路径为/WEN-INF/xxx-servlet.xml(xxx=定义的servlet-name 即<servlet-name>dispatch</servlet-name>),)
即是:dispatch-servlet.xml
②:如果有<init-param>,就会寻找<init-param>中配置的文件,不会再找xxx-servlet.xml
第二:如果配置了<init-param>,那么applicationContext.xml文件在哪里?
解答:下面第一种方式,在/WebContent/WEB-INF/目录下
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
</servlet>
第二种方式,在/src/目录下:
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
第三:url的访问路径是什么?下面是两个简单例子
举例1:url:http://localhost:8080/demo1/welcome/hello
- @Controller
- @RequestMapping("/welcome")
- public class HelloWorldController {
- @RequestMapping(value="/hello" ,method=RequestMethod.GET)
- public String printWelcome(ModelMap model){
- model.addAttribute("message" ,"Spring 3 MVC Hello World");
- return "hello"; }
- }
举例2:url:http://localhost:8080/demo1/home
- @Controller
- public class HomeController {
- @RequestMapping("home")
- public String home(){
- return "home"; }
- }
上面两个小例子运行最少需要的其他代码如下:
1,web.xml
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2,dispatch-servlet.xml
<!-- 在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的Java文件,
如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean -->
<context:component-scan base-package="com" />
<!-- viewResolver将把逻辑视图名解析为具体的view,通过这种策略模式,很容易更换其他视图模式
如:InternalResourceViewResolver将逻辑视图名解析为jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
3,在/WEB-INF/下放两个jsp
home.jsp
<body>hello spring!</body>
hello.jsp
<body> <h1>Message: ${message}</h1> </body>