B站狂神说Java---记录SpringMVC学习笔记

Posted 小智RE0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了B站狂神说Java---记录SpringMVC学习笔记相关的知识,希望对你有一定的参考价值。

B站学习传送门==>【狂神说Java】SpringMVC最新教程IDEA版通俗易懂

感谢狂神



M即model模型是指模型表示业务规则。
V即View视图是指用户看到并与之交互的界面。
C即controller控制器是指控制器;接受用户的输入并调用模型和视图去完成用户的需求.

1.回顾servlet

创建新的maven,在pom.xml文件中进行相关配置.

删除src目录,将当前项目作为父级根项目

<!--导入相关依赖配置-->
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>
<!--为防止资源导出失败;在build中需要配置resources-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

检查maven的地址;

创建新的模块;作为子目录项目;

添加框架支持

写个DemoServlet类

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author by CSDN@小智RE0
 * @date 2021-10-06 19:24
 */
//复习servlet
public class Demo01Servlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mark = req.getParameter("mark");
        //根据返回的参数处理;
        if(mark.equals("my")){
            req.getSession().setAttribute("message","返回的是My");
        }else if(mark.equals("you")){
            req.getSession().setAttribute("message","返回的是You");
        }

        //转发页面;
        req.getRequestDispatcher("/index.jsp").forward(req,resp);
    }
}

在web.xml配置servlet

<?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_4_0.xsd"
         version="4.0">
    
    <!--配置servlet-->
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>Demo01Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/demo</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 小智
  Date: 2021/10/6
  Time: 18:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>复习servlet</title>
  </head>
  <body>

  ${message}
  <form action="demo" method="post">
    点击按钮
    <input type="submit" name="mark" value="my"><br/>
    <input type="submit" name="mark" value="you"><br/>
  </form>
  </body>
</html>

启动后,点击按钮my


2.SpringMVC概述

官方文档地址::4.3.24版本文档

可进入

https://docs.spring.io/spring-framework/docs/4.3.24.RELEASE/spring-framework-reference

点击html

可找到这里mvc相关的.

https://docs.spring.io/spring-framework/docs/4.3.24.RELEASE/spring-framework-reference/html/mvc.html

当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者.

SpringMVC来自于SpringFramework,基于Java实现的MVC轻量级Web框架。
Spring的web框架核心是DispatcherServlet
DispatcherServlet可以管理不同的部分

先快速搭建一下;

配置web.xml

<?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_4_0.xsd"
         version="4.0">

    <!--配置注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--启动级别-1-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--/ 匹配所有的请求;(不包括.jsp)-->
    <!--/* 匹配所有的请求;(包括.jsp)-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

resources目录下创建springmvc-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--处理映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/demos/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="/demo" class="com.xiaozhi.controller.DemoController"/>
</beans>

写个控制层

package com.xiaozhi.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author by CSDN@小智RE0
 * @date 2021-10-06 20:28
 */
public class DemoController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();
        //封装对象,放在ModelAndView中。Model
        mv.addObject("message","SpringMVC显示");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("demo");
        return mv;
    }
}

demo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>试试MVC</title>
</head>
<body>
${message}
</body>
</html>

配置tomcat;

大概的布局为;

访问 http://localhost:8080/study02_fasttry/demo

开始运行时出现404错误;检查了jar包后,没有缺少的;
然后就去给项目手动添加了相关的所有jar包;

然后再启动后访问;


3. SpringMVC执行原理

刚才在fwhttp://localhost:8080/study02_fasttry/demo 时,可分为3部分;
http://localhost:8080 服务器域名;
study02_fasttry 在tomcat部署的web站点;
demo 控制器

DispatcherServlet 为前置控制器,是springmvc的控制核心.客户端发出请求后,由它接收请求,拦截请求.

4.深入理解

试试再写一次配置步骤;

需要注意的是,在配置springmvc时, 用//* 有区别;
/ 仅匹配所有的请求,不会去匹配jsp页面;
/* 匹配所有的请求以及jsp页面

配置web.xml

<?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_4_0.xsd"
         version="4.0">

    <!--配置DispatchServlet,请求分发,前端控制-->
    <servlet>
        <servlet-name>deepspringmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--需要绑定springmvc的参数文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--配置文件的地址-->
            <param-value>classpath:springmvc-deepspringmvcservlet.xml</param-value>
        </init-param>

        <!--配置启动的级别,和服务器一块启动-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>deepspringmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

resources目录下写springmvc-deepspringmvcservlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.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" id="internalResourceViewResolver">
        <!--前缀后缀,注意拼接时的对应目录-->
        <property name="prefix" value="/WEB-INF/demos/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

<!--Handler-->
    <bean id="/demo2" class="com.xiaozhi.controller.DeepStudyMvc"/>
</beans>

简易控制层

package com.xiaozhi.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author by CSDN@小智RE0
 * @date 2021-10-06 22:45
 */

//简易控制层;
public class DeepStudyMvc implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //新建视图对象;
        ModelAndView modelAndView = new ModelAndView();

        //添加要传输的数据;
        modelAndView.addObject("message","再次学习");

        //设定要去的页面;
        modelAndView.setViewName("demo2");
        return modelAndView;
    }
}

demo2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>深入理解MVC</title>
</head>
B站狂神说Java笔记-java流程控制

B站狂神说Java笔记-数组

B站狂神说Java笔记-java基础语法

B站狂神说Java笔记-java方法

B站狂神说Java笔记-多线程

B站狂神说Java笔记-面向对象编程