1.导入需要的jar包
a) spring-beans
b) spring-context
c) spring-core
d) spring-expression
e) spring-web
f) spring-webmvc
g) commons-logging(日志包)
2.在web.xml中配置DispatcherServlet服务(通过springMVC-servlet.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>SpringMVC</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list>
<servlet> <!-- springMVC默认路径是:/WEB-INF/servletName-servlet.xml 可以通过init-param来更改:paeam-name:contextConfigLocation,param-value:classpath:(编码后xml所在的具体位置) --> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> |
3.在springMVC-servlet.xml配置Beans,HandlerMapping(可以不配置默认是:BeanNameUrlHandlerMapping),Controller,InternalResourceViewResolver(加个前缀prefix,后缀suffix)(找文档)
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- BeanNameUrlHandlerMapping:通过name找 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 配置Controller --> <bean name="/my.do" class="com.zhiyou100.kfs.controller.MyController"></bean>
<!-- 配置视图解析器:ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> </beans> |
4.创建Controller,返回ModelAndView对象(还可以是String,java对象(json))
package com.zhiyou100.kfs.controller;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController;
public class MyController extends AbstractController{
@Override protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception { ModelAndView mv=new ModelAndView(); mv.setViewName("login"); mv.addObject("name", "login<br/>hello!"); return mv; }
} |
5.在视图解析层(InternalResourceViewResolver)通过ModelAndView找视图(jsp、excel、pdf、php...)
6.根据视图解析层提供的位置创建jsp
7.web工程包结构: