? SpringMVC框架的核心思想是MVC思想,即模型(Model)--视图(View)--控制器(Controller)。它主要通过分离模型,视图及控制器在应用程序中的角色将业务逻辑从页面解耦。通常,模型负责封装应用程序数据在视图层展示,视图仅仅只是展示这些数据,不包含任何业务逻辑。控制器负责接收来自用户的请求,并调用后台服务(service 或者 dao)来处理业务逻辑。处理后,后台业务层可能会返回了一些数据在视图层展示。控制器收集这些数据及准备模型在视图层展示。MVC 模式的核心思想是将业务逻辑从界面中分离出来,允许它们单独改变而不会相互影响。
? Spring MVC 是 Spring 家族中的一个 web 成员, 它是一种基于 Java 的实现了 Web MVC 设计思想的请求驱动类型的轻量级 Web 框架,即使用了 MVC 架构模式的思想,将 web 层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring MVC 也是要简化我们日常Web 开发的。
? Spring MVC 是服务到工作者思想的实现。前端控制器是DispatcherServlet;应用控制器拆为处理器映射器(Handler Mapping)进行处理器管理和视图解析器(View Resolver)进行视图管理;支持本地化/国际化(Locale)解析及文件上传等;提供了非常灵活的数据验证、格式化和数据绑定机制;提供了强大的约定大于配置(惯例优先原则)的契约式编程支持。
1.让我们能非常简单的设计出干净的 Web 层;
2.进行更简洁的 Web 层的开发;
3.天生与 Spring 框架集成(如 IoC 容器、AOP 等);
4.提供强大的约定大于配置的契约式编程支持;
5.能简单的进行 Web 层的单元测试;
6.支持灵活的 URL 到页面控制器的映射;
7.非常容易与其他视图技术集成,如 Velocity、FreeMarker 等等,因为模型数据不放在特定的 API 里,而是放在一个 Model 里(Map 数据结构实现,因此很容易被其他框架使用);
8.非常灵活的数据验证、格式化和数据绑定机制,能使用任何对象进行数据绑定,不必实现特定框架的 API;
9.支持灵活的本地化等解析;
10.更加简单的异常处理;
11.对静态资源的支持;
12.支持 Restful 风格。
1.坐标依赖添加(jar包)
<!-- spring web -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.2.RELEASE</version>
  </dependency>
  <!-- spring mvc -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
  </dependency>
  <!-- web servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
  </dependency>
  <!-- 添加json 依赖jar包 -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.0</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.0</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.0</version>
  </dependency>
</dependencies>
<build>
  <finalName>spring01</finalName>
  <plugins>
    <plugin>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>maven-jetty-plugin</artifactId>
      <version>6.1.25</version>
      <configuration>
        <scanIntervalSeconds>10</scanIntervalSeconds>
        <contextPath>/springmvc01</contextPath>
      </configuration>
    </plugin>
  </plugins>
</build>2.配置web.xml(前端控制器)
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <!-- 表示容器启动时 加载上下文配置  这里指定spring 相关配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:*.xml</param-value>
  </context-param>
  <!-- 启用spring容器环境上下文监听 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 编码过滤 utf-8 -->
  <filter>
    <description>char encoding filter</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- servlet请求分发器 -->
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:servlet-context.xml</param-value>
    </init-param>
    <!-- 表示启动容器时初始化该Servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <!-- 这是拦截请求, /代表拦截所有请求,拦截所有.do请求 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>3.配置servlet-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">
    <!-- 扫描com.back.controller 下包 -->
    <context:component-scan base-package="com.back.controller" />
    <!-- mvc 请求映射 处理器与适配器配置-->
    <mvc:annotation-driven/>
    <!--配置视图解析器  默认的视图解析器- -->
    <bean id="defaultViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="contentType" value="text/html" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>4.页面控制器的编写
@Controller
public class HelloController {
    @RequestMapping("hello") // /hello
    public String hello(){
        return "hello";
    }
    @RequestMapping("index") // /index
    public String index(){
        return "index";
    }
}5.添加视图页面(在 WEB-INF 下新建 jsp 文件夹 ,并在文件加下新建 hello.jsp)
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/11/6
  Time: 15:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    
<title>hello</title>
</head>
<body>
<h3>Hello, SpringMVC!!</h3>
</body>
</html>6.启动jetty服务器,浏览器访问

为使 spring 能找到定义为 controller 的 bean,需要在 spring-context 配置文件中增加如下定义
<!-- 扫描com.back.controller 下包 -->
<context:component-scan base-package="com.back.controller" />在类前面定义,则将 url 和类绑定
在方法前面定义,则将 url 和类的方法绑定
@Controller
@RequestMapping("index")
public class IndexController {
    @RequestMapping("test01")
    public ModelAndView test01(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("name","zhangsan");
        mv.setViewName("index");
        return mv;
    }1.基本数据类型、字符串数据绑定
@Controller
@RequestMapping("index")
public class IndexController {
    @RequestMapping("test01")
    public ModelAndView test01(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("name","zhangsan");
        mv.setViewName("index");
        return mv;
    }
    @RequestMapping("test02")
    public String Model(Model model){
        model.addAttribute("name","lisi");
        return "index";
    }
    @RequestMapping("test03")
    public String test03(Map map){
        map.put("name","wangwu");
        return "index";
    }
    @RequestMapping("test04")
    public String test04(HttpServletRequest request){
        request.setAttribute("name","zhaoliu");
        return "index";
    }
    @RequestMapping("test05")
    public String test05(HttpSession session){
        session.setAttribute("name","zhengqi");
        return "index";
    }
    @RequestMapping("test06")
    public String test06(HttpServletRequest request){
        request.getSession().setAttribute("name","wangba");
        return "index";
    }
}2.数组类型
@RequestMapping("test05")
    public String test05(Integer[] ids,Model model) {
        for (int i = 0; i < ids.length; i++) {
            System.out.print(ids[i]);
        }
        return "params";
    }3.vo类型
public class User {
    private Integer id;
    private String username;
    private String password;
    private Phone phone;
//    private List<Phone> phones = new ArrayList<>();
    private Set<Phone> phones = new HashSet<>();
    private Map<String,Phone> map = new HashMap<>();
    public User() {
        phones.add(new Phone());
        phones.add(new Phone());
        phones.add(new Phone());
    }
    public Phone getPhone() {
        return phone;
    }
    public void setPhone(Phone phone) {
        this.phone = phone;
    }
    public Map<String, Phone> getMap() {
        return map;
    }
    public void setMap(Map<String, Phone> map) {
        this.map = map;
    }
    public Set<Phone> getPhones() {
        return phones;
    }
    public void setPhones(Set<Phone> phones) {
        this.phones = phones;
    }
    /* public List<Phone> getPhones() {
        return phones;
    }
    public void setPhones(List<Phone> phones) {
        this.phones = phones;
    }*/
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", password=‘" + password + ‘\‘‘ +
                ", phones=" + phones +
                ‘}‘;
    }
}4.list类型
public class Phone {
    private String num;
    public String getNum() {
        return num;
    }
    public void setNum(String num) {
        this.num = num;
    }
    @Override
    public String toString() {
        return "Phone num [ " + num + "]";
    }
}5.set类型
<%--
  Created by IntelliJ IDEA.
  User: back
  Date: 2018/11/6
  Time: 19:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h>Hello World!!!</h>
参数:${a}===============${b}
    <hr>
    <%--<form action="test08" method="post">
        <input name="phones[0].num" value="123456" />
        <input name="phones[1].num" value="457689" />
        <input name="phones[2].num" value="333999">
        <button type="submit"> 提交</button>
    </form>--%>
    <%--<form action="test09" method="post">
        <input name="map[‘1‘].num" value="123456" />
        <input name="map[‘2‘].num" value="457689" />
        <input name="map[‘3‘].num" value="333999">
        <button type="submit"> 提交</button>
    </form>--%>
    <form action="test10" method="post">
        <input name="username" value="123456" />
        <input name="password" value="4576" />
        <input name="phone.num" value="4576" />
        <button type="submit"> 提交</button>
    </form>
</body>
</html>@Controller
@RequestMapping("user")
@SessionAttributes({"lisi"})
public class UserController {
    @RequestMapping("test01")
    public ModelAndView test01(String username){
        ModelAndView mv = new ModelAndView();
        mv.addObject("username",username);
        mv.setViewName("user");
        return mv;
    }
    @RequestMapping("test02")
    public String test02(){
        return "redirect:user.jsp";
    }
    @RequestMapping("test03")
    @ResponseBody
    public User getUser(Integer id){
        User user = new User();
        user.setId(id);
        user.setPassword("123456");
        user.setUsername("zhangsan");
        return user;
    }
    @RequestMapping("test04")
    @ResponseBody
    public List<User> getListUser(Integer id){
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            User user = new User();
            user.setId(id);
            user.setPassword("123456");
            user.setUsername("zhangsan");
            userList.add(user);
        }
        return userList;
    }
}6.Map类型
<%--
  Created by IntelliJ IDEA.
  User: back
  Date: 2018/11/7
  Time: 14:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Hello SpringMVC!!!</h1>
    ${sessionScope.username} ||| ${sessionScope.password}
</body>
</html>
7.自定义复合类型
@Controller
@RequestMapping("params")
public class ParamsController {
    @RequestMapping("test01")
    public String test01(HttpServletRequest request){
        String a = request.getParameter("a");
        System.out.println(a);
        request.setAttribute("a",a);
        return "params";
    }
    @RequestMapping("test02")
    public String test02(String a, Model model){
        System.out.print(a);
        model.addAttribute("a",a);
        return "params";
    }
    @RequestMapping("test03")
    public String test03(String a,Integer b,Model model){
        System.out.print(a);
        System.out.print(b);
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        return "params";
    }
    @RequestMapping("test04")
    public String test04(@RequestParam(defaultValue = "good") String a,
                         @RequestParam(defaultValue = "88") Integer b, Model model){
        System.out.print(a+"======="+b);
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        return "params";
    }
    @RequestMapping("test05")
    public String test05(Integer[] ids,Model model) {
        for (int i = 0; i < ids.length; i++) {
            System.out.print(ids[i]);
        }
        return "params";
    }
    @RequestMapping("test06")
    public String test06(User user){
        System.out.print(user);
        return "params";
    }
    @RequestMapping("test07")
    public String test07(User user){
        System.out.print(user);
        return "params";
    }
    @RequestMapping("test08")
    public String test08(User user){
        System.out.print(user);
        return "params";
    }
    @RequestMapping("test09")
    public String test09(User user){
        Set<Map.Entry<String,Phone>> set = user.getMap().entrySet();
        for(Map.Entry<String,Phone> entry:set){
            System.out.print(entry.getKey()+"========"+entry.getValue().getNum());
        }
        return "params";
    }
    @RequestMapping("test10")
    public String test10(User user){
        System.out.println(user.getUsername()+"==="+user.getPassword()+"==="+user.getPhone().getNum());
        return "params";
    }
    public ModelAndView queryUser(HttpServletRequest request, HttpServletResponse response){
        String userName= request.getParameter("userName");
        ModelAndView mv=new ModelAndView();
        mv.addObject("userName", userName);
        mv.setViewName("request");
        return mv;
    }
}原文:https://www.cnblogs.com/y-u-p/p/10416111.html