spring mvc(2) spring mvc初体验

  前面讲到随着前端技术的发展,web的开发已经实现了前后分离,并且spring mvc经过多个版本的更新,使用上也变得不一样,并且提供了很多便捷的功能。但是为了便于理解,我们使用比较原始的方式搭建spring mvc环境(只是用于理解spring mvc工作模式,不必实践,现在比较流行的使用spring boot和注解,后面会讲)。

  1.创建一个web项目

  2.引入spring framework相关jar包

  3.配置web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 4     id="WebApp_ID" version="3.1">
 5     <display-name>FirstSpringMVCProj</display-name>
 6     <servlet>
 7         <servlet-name>springmvc</servlet-name>
 8         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 9         <init-param>
10             <param-name>contextConfigLocation</param-name>
11             <!-- 设置SpringMVC配置文件的位置,注意该位置默认是src文件夹下 -->
12             <param-value>classpath:springmvc.xml</param-value>
13         </init-param>
14         <load-on-startup>1</load-on-startup>
15     </servlet>
16     <servlet-mapping>
17         <servlet-name>springmvc</servlet-name>
18         <url-pattern>/</url-pattern>
19     </servlet-mapping>
20     <welcome-file-list>
21         <welcome-file>index.jsp</welcome-file>
22     </welcome-file-list>
23 </web-app>
View Code

  4.配置springmvc.xml配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 3 <beans>
 4     <bean id="simpleUrlHandlerMapping"
 5         class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 6         <property name="mappings">
 7             <props>
 8                 <prop key="/index">indexController</prop>
 9             </props>
10         </property>
11     </bean>
12     <bean id="indexController" class="controller.IndexController"></bean>
13 </beans>
View Code

    5.创建controller

 1 package controller;
 2  
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5  
 6 import org.springframework.web.servlet.ModelAndView;
 7 import org.springframework.web.servlet.mvc.Controller;
 8  
 9 public class IndexController implements Controller {
10     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
11         ModelAndView mav = new ModelAndView("index.jsp");
12         mav.addObject("message", "Hello Spring MVC");
13         return mav;
14     }
15 }
View Code

  6.创建index.jsp

1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2     pageEncoding="UTF-8" isELIgnored="false"%>
3  
4 <h1>${message}</h1>
View Code

  启动项目后,我们通过浏览器访问 /index,就会显示如下页面,也就实现了spring mvc 最初的 controller mode view 分离。

 

 

 

 

 

 
posted @ 2018-07-25 12:33  zwh1988  阅读(168)  评论(0编辑  收藏  举报