SpringMVC

Posted chn.tiancx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC相关的知识,希望对你有一定的参考价值。

SpringMVC

说明下【本文是在网上听课做的笔记,代码是自己敲的,有些文字是复制的老师发的】

SpringMVC概述

使用SpringMVC替换Servlet

Servlet的问题:

1、需要判断调用哪个方法。(逻辑需要自己编写)

2、需要获得request的数据,并且需要手动封装,还要进行类型转换。

3、跳转和转发数据的代码太繁琐。

4、通过ajax请求的对象,需要通过fastjson进行转换,并使用相应对象的输出流写出。

以上问题SpringMVC都给出了解决方案。

1、添加依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.18.RELEASE</version>
</dependency>

2、在web.xml中配置前端控制器

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--
     前端控制器
  -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC-Servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--
      /表示拦截了除了jsp之外所有的请求
    -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

3、编写SpringMVC的配置文件(结构和Spring配置文件一致)

<?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"
       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">
    <!--
          映射器
      -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <!--
           适配器
       -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!--
         视图解析器
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--
            配置Controller
        -->
<!--    <bean id="/user" class="com.woniu.controller.UserController"></bean>-->
        <bean id="/user" class="cn.cqie.controller.UserController"/>
</beans>

4、添加Controller

package cn.cqie.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Description:
 * Author: tiancx
 * Date: Created in 2021/11/23 21:30
 */
public class UserController implements Controller 
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception 
        System.out.println("UserController.handleRequest");

        return null;
    

5、通过浏览器访问Controller

SpringMVC的工作机制

DispatcherServlet

<?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"
       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">
    <!--
        映射器
        BeanNameUrlHandlerMapping
        在浏览器中发送/user
        通过/user在Spring容器中找到id对应的实例

        SimpleUrlHandlerMapping
        声明一个映射关系
        Properties
    -->
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/user">userController</prop>
            </props>
        </property>
    </bean>
    <!--
        适配器
        SimpleControllerHandlerAdapter
        可以执行实现了Controller接口的控制器

        HttpRequestHandlerAdapter
        可以执行实现了HttpRequestHandler接口的控制器
    -->
    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" ></bean>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" ></bean>
    <!--
        视图解析器
        prefix 从webapp根目录指定
        suffix 是后缀
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--
        配置Controller
    -->
    <bean id="userController" class="cn.cqie.controller.UserController"></bean>
</beans>

Controller的实现

使用注解配置Controller

package cn.cqie.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Description:
 * Author: tiancx
 * Date: Created in 2021/11/23 21:30
 */
@Controller
public class UserController2  

    @RequestMapping("userSave")
    public ModelAndView save()
        System.out.println("UserController2.save");
        return new ModelAndView("index");
    

<?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"
       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">
    <context:component-scan base-package="cn.cqie"/>
    <mvc:annotation-driven></mvc:annotation-driven> <!--这个可以替换掉下面的两个 bean,甚至更多 -->
<!--    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
<!--    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
    <!--
         视图解析器
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--
            配置Controller
        -->
    <!--    <bean id="/user" class="com.woniu.controller.UserController"></bean>-->
    <bean id="userController" class="cn.cqie.controller.UserController"/>
</beans>

ModelAndView类

package cn.cqie.controller;

import cn.cqie.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Author: tiancx
 * Date: Created in 2021/11/23 21:30
 */
@Controller
public class UserController2  
//    @RequestMapping("testList")  就是在浏览器输入 testList  和以前的servlet一样
    @RequestMapping("testList")
    public ModelAndView list()
        System.out.println("UserController2.save");
        List<User> list =new ArrayList<>();
        list.add(new User("yx",26));
        list.add(new User("wls",20));
        list.add(new User("tcx",20));
        //                                          /list.jsp
        ModelAndView ma = new ModelAndView("list");

        //request.setAttribute();
        ma.addObject("msg","66666");

        return ma;
    

    @RequestMapping("testList2")
    public ModelAndView list2()
        System.out.println("UserController2.save");
        List<User> list =new ArrayList<>();
        list.add(new User("yx",26));
        list.add(new User("wls",20));
        list.add(new User("tcx",20));
        ModelAndView ma = new ModelAndView("list2");
        ma.addObject("msg",list);
        return ma;
    

    @RequestMapping("testList3")
    public ModelAndView list3()
        System.out.println("UserController2.save");
        List<User> list =new ArrayList<>();
        list.add(new User("yx",26));
        list.add(new User("wls",20));
        list.add(new User("tcx",20));
        ModelAndView ma = new ModelAndView("list2");
        //request.setAttribute(); 名字默认为类型与泛型的组合 userList
        ma.addObject(list);
        return ma;
    


    @RequestMapping("testList4")
    public String list4(Model model)
        System.out.println("UserController2.save");
        List<User> list =new ArrayList<>();
        list.add(new User("yx",26));
        list.add(new User("wls",20));
        list.add(new User("tcx",20));

        model.addAttribute(list);
        return "list2"; // /list.jsp
    


    @RequestMapping("testList5")
    public String list5(Model model)
            //重定向
        return "redirect:list.jsp";
    

相关的jsp页面

list.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/11/24
  Time: 21:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    $msg
</body>
</html>

list2.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/11/24
  Time: 21:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <ul>
        <c:forEach items="$userList" var="user">
            <li>$user.name</li>
        </c:forEach>
    </ul>
</body>
</html>

jstl需要导入的依赖

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

视图解析器概述

将Controller的返回值进行解析,到浏览器。

在SpringMVC中也有很多视图解析器

这时通过视图解析器解析handler返回的值(逻辑视图,转发数据)

InternalResourceViewResolver会将逻辑视图与prefix和suffix组合成物理视图名,
如果逻辑视图返回值中包含redirect:,则进行重定向操作,如果是forward:或者没有前缀,则转发操作。

编写一个视图

package cn.cqie.controller.a_view;

import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Description:
 * Author: tiancx
 * Date: Created in 2021/11/25 15:02
 */
public class MyView implements View 
    @Override
    public String getContentType() 
        return null;
    

    @Override
    public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception 
        //map就是model中添加的数据
        for (Map.Entry<Str

以上是关于SpringMVC的主要内容,如果未能解决你的问题,请参考以下文章

springmvc的特点

学习笔记——SpringMVC简介;SpringMVC处理请求原理简图;SpringMVC搭建框架

SpringMVC

springMVC学习笔记初识springmvc

SpringMVC

springMVC1 springmvc的基础知识