spring mvc 之初体验

时间:2020-12-02 15:16:17

Spring MVC最简单的配置

  配置一个Spring MVC只需要三步:

  1. 在web.xml中配置Servlet;
  2. 创建Spring MVC的xml配置文件;
  3. 创建Controller和View
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"> <!-- spring mvc配置开始 -->
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring mvc配置结束 --> <welcome-file-list>
<welcome-file>index</welcome-file>
</welcome-file-list>
</web-app>

所配置的Servlet是DispatcherServlet类型,它就是Spring MVC的入口,Spring MVC的本质就是一个Servlet。在配置DispatcherServlet的时候可以设置contextConfigLocation参数来指定Spring MVC配置文件的位置,如果不指定就默认使用WEB-INF/[ServletName]-servlet.xml文件。

servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/>
<context:component-scan base-package="com.excelib" />
</beans>

<mvc:annotation-driven/>是Spring MVC提供的一键式的配置方法,配置此标签后Spring MVC会自动做一些注册组件之类的事情。

context:component-scan base-package="com.excelib" />扫描通过注释配置的类,还可以通过context:include-filter子标签来设置只扫描@Controller就可以了,别的交给Spring容器管理

 <context:component-scan base-package="com.excelib" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
 @Controller
public class GoController {
private final Log logger = LogFactory.getLog(GoController.class);
//处理HEAD类型的”/”请求,HEAD类型的请求可以用来检测服务器的状态,因为它不返回body所以比GET请求更省网络资源
@RequestMapping(value={"/"},method= {RequestMethod.HEAD})
public String head() {
return "go.jsp";
}
//处理GET类型的"/index"和”/”请求
@RequestMapping(value={"/index","/"},method= {RequestMethod.GET})
public String index(Model model) throws Exception {
logger.info("======processed by index=======");
//返回msg参数
model.addAttribute("msg", "Go Go Go!");
return "go.jsp";
}
}

若果没有配置ViewResolver,Spring MVC将默认使用org.springframework.web.servlet.view.InternalResourceViewResolver作为ViewResolver。