Java --- SpringMVC(1)

SpringMVC是Spring的一部分,是一种基于Java的轻量级Web框架,它实现了MVC设计模式,简化了Web开发。本文介绍了MVC的概念,SpringMVC的优势,以及如何创建一个SpringMVC项目,包括配置DispatcherServlet、URL映射和Bean的分配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是MVC

MVC : 模型、视图、控制器 , 是一种软件设计规范,说明不是设计模式;

本质:将业务逻辑 , 数据 , 显示 分离的方式来编写代码; 前后端分离;

Model:数据模型,提供要展示的数据,一般我们都会把这两个分离开来 , 数据Dao,服务层Service。

View :负责进行数据的渲染和展示;客户端想要看到的东西

Controller:接收用户请求,交给Model处理,从Model更新后的数据或者结果,返回给前端。调度员

面向接口编程;

最典型的案例就是:JSP:View + Servlet:Controller + JavaBean:Model;

Model1
在早期的Web开发中,就是用的Model1模式
只有两层:视图层和模型层;
在这里插入图片描述优点:架构简单,适合小型项目开发;

缺点:JSP职责不单一 , 承受它不该承受的压力,不便于维护;

Model2
将项目分为三个模块:M:模型 V:视图 C :控制器在这里插入图片描述
职责分析:

controller:

  • 取得表单的数据
  • 调用业务的逻辑方法
  • 转向指定的页面

Model:

  • Dao:操作数据库
  • Service:业务逻辑
  • 保存数据的更新状态

View:

  • 显示页面

Model2优化了Model1时代的缺点,让所有层职责更加分明;降低了维护难度

SpringMVC

什么是SpringMVC

SpringMVC 是 Spring的一部分,是基于Java实现的MVC的轻量级Web框架

我们为什么要学习SpringMVC

  • 趋势,使用的人多。
  • 简单,易学,轻量级
  • 高效,基于请求和响应的MVC框架;
  • 约定优于配置;
  • 功能强大:RestFul、数据验证、格式化{json}、主题,本地化、异常处理…

官网上说Spring的web模块提供了大量独特的功能,包括:

清晰的角色划分:控制器(controller)、验证器(validator)、 命令对象(command object)、表单对象(form object)、模型对象(model object)、 Servlet分发器(DispatcherServlet)、 处理器映射(handler mapping)、视图解析器(view resolver)等等。 每一个角色都可以由一个专门的对象(类)来实现。< Bean>

强大而直接的配置方式:将框架类和应用程序类都能作为JavaBean配置,而且支持跨多个context 的引用。

可适配、非侵入:可以根据不同的应用场景,选择合适的控制器子类 (simple型、command型、form型、wizard型、multi-action型或者自定义),而不是从单一控制器 (比如Action/ActionForm)继承。

可重用的业务代码:可以使用现有的业务对象作为命令或表单对象,而不需要去扩展某个特定框架的基类。

可定制的绑定(binding) 和验证(validation):比如将类型不匹配作为应用级的验证错误, 这可以保存错误的值。再比如本地化的日期和数字绑定等等。在其他某些框架中,你只能使用字符串表单对象, 需要手动解析它并转换到业务对象。

可定制的handler mapping和view resolution:Spring提供从最简单的URL映射, 到复杂的、专用的定制策略。与某些web MVC框架强制开发人员使用单一特定技术相比,Spring显得更加灵活。

灵活的model转换:在Springweb框架中,使用基于Map的 键/值对来达到轻易地与各种视图技术的集成。

可定制的本地化和主题(theme)解析:支持在JSP中可选择地使用Spring标签库、支持JSTL、支持Velocity(不需要额外的中间层)等等。

简单而强大的JSP标签库(Spring Tag Library):支持包括诸如数据绑定和主题(theme) 之类的许多功能。它提供在标记方面的最大灵活性。

JSP表单标签库:在Spring2.0中引入的表单标签库,使得在JSP中编写 表单更加容易。

Spring Bean的生命周期可以被限制在当前的HTTP Request或者HTTP Session。 准确的说,这并非Spring MVC框架本身特性,而应归属于Sping MVC使用的WebApplicationContext容器。

正因为SpringMVC较Struct2好 , 简单 , 便捷 , 易学 , 天生和Spring无缝集成(使用SpringIoC和Aop) , 使用约定优于配置 . 能够进行简单的junit测试 . 支持Restful风格 .异常处理 , 本地化 , 国际化 , 数据验证 , 类型转换 , 拦截器 等等…所以我们要学习 .

SpringMVC框架围绕着DispatcherServlet(Servlet请求分发器)设计;

The DispatcherServlet

在这里插入图片描述
在这里插入图片描述

创建SpringMVC项目

  1. 首先我们需要利用Maven创建一个web项目
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
  2. 创建好项目之后,我们需要在pop.xml中导入jar包,并且解决资源导出问题

导包

<!-- Spring MVC 及 Spring系列包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.24.RELEASE</version>
    </dependency>

    <!--Servlet核心-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <!-- JSTL -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

解决资源导出问题,在build加入如下代码

    <!--解决资源导出问题-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  1. 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
  <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:</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
  
</web-app>
  1. 配置springmvc-servlet.xml,并在WEB-INF中创建一个名叫jsp的目录,回到上一步,在classpath:中填入我们创建的这个xml的名字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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package=""/>
    <mvc:annotation-driven/>

    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>
  1. 在main目录下面创建包 com.westos.controller,并且创建HelloController 的java class,在springmvc-servlet.xml中的 <context:component-scan base-package=""/>加入这个包,并编写HelloController代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/h1")
 public String hello(Model model){
     model.addAttribute("msg","HelloSpringMVC");
     return "hello";
 }
}

  1. 在WEB-INF中的jsp目录中创建hello.jsp 用来接收msg的数据

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

  1. 配置Tomcat并进行测试,测试结果如图所示
    在这里插入图片描述
    这种方式,是使用注解,还有两种方式,URL对应bean 和 为URL分配一个bean
URL对应bean

还是上面的项目,我们重新创建一个类 HelloController2

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

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

@Controller
public class HelloController2 {
    @RequestMapping("/h2")
    public ModelAndView hello(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","URL对应bean");
        mv.setViewName("hello");
        return mv;
    }
}

之后在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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--<context:component-scan base-package="com.westos.controller"/>-->
    <!--<mvc:annotation-driven/>-->

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean id="/h2" class="com.westos.controller.HelloController2"/>

    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

注意:如果要使用这种方式,必须将之间配置的

    <!--<context:component-scan base-package="com.westos.controller"/>-->
    <!--<mvc:annotation-driven/>-->

注释掉,不然会报错。

结果图为:
在这里插入图片描述

为URL分配一个Bean

和上述步骤一样,我们首先要创建一个类HelloController3

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

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

public class HelloContorller3 implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","为URL分配一个Bean");
        mv.setViewName("hello");
        return mv;
    }
}

之后要重新配置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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--<context:component-scan base-package="com.westos.controller"/>-->
    <!--<mvc:annotation-driven/>-->

    <!--<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->
    <!--<bean id="/h2" class="com.westos.controller.HelloController2"/>-->

    <bean id="helloController3" class="com.westos.controller.HelloContorller3"/>
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/h3">helloController3</prop>
            </props>
        </property>
    </bean>

    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

结果图为:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值