首页 > 其他分享 >SpringMVC - 初识

SpringMVC - 初识

时间:2024-08-11 21:27:57浏览次数:7  
标签:xml return SpringMVC hello public 初识 servlet class

1. 简介

Spring MVC是一个创建Web应用程序的框架,它是遵循Model-View-Controller的设计模式。

Spring MVC通过DispatcherServlet来接收请求,然后对应对具体的controllers, models和views.

2. 一个HelloWorld事例

1. 添加maven依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.3.37</version>
</dependency>

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

2. 在Web.xml中添加DispatcherServlet

<!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 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-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</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>

3. 在resources目录下面添加springmvc.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
        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">
    <mvc:annotation-driven />
    <context:component-scan base-package="com.example"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

4. 添加controller

@Controller
@RequestMapping("/hello")
public class HelloController {
    @GetMapping("/world")
    public String world(Model model){
        model.addAttribute("message", "hello world, everyone!");
        return "hello";
    }
}

5. 添加hello.jsp文件

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

6. 整个目录结构如下:

7. 启动,访问

http://localhost:8080/hello/world

3. 纯代码方式启动SpringMVC

1. 创建注册DispatcherServlet的类,Spring给我们提供了一个抽象的AbstractDispatcherServletInitializer,我们继承它就好了

public class ServletInitConfig extends AbstractDispatcherServletInitializer {
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        return context;
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

 2. 添加SpringMvcConfig.java

@Configuration
@ComponentScan("com.example")
public class SpringMvcConfig {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

 3. 创建controller

@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("message", "hello world 2!");
        return "hello";
    }
}

 4. 创建hello.jsp

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

 5. 代码结构如下,去除了前面的web.xml和springmvc.xml, 改用代码来配置

6. 访问:http://localhost:8080/hello 

 

7. 原理

在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器,servlet3.0赋予了web项目免去所有配置文件(web.xml)的能力。

可以自定义一个实现ServletContainerInitializer接口,这个类必须在jar包的META-INF/services/javax.servlet.ServletContainerInitializer文件里面进行声明,这个文件的内容就是自定义类的全类名。注意看下面spring-web模块里面的配置

 SpringServletContainerInitializer类定义如下:

@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    public SpringServletContainerInitializer() {
    }

    public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
    }
}

 注意这个类上面的@HandlesTypes注解,servlet容器会扫描项目中的所有类,如果符合@HandlesTypes注解value值指定的类型,就会放在一个数组中,最终会传递给onStartup方法的第一个参数。

我们再来看一下AbstractDispatcherServletInitializer类, 它就实现了WebApplicationInitializer接口

public abstract class AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer 

public abstract class AbstractContextLoaderInitializer implements WebApplicationInitialize

标签:xml,return,SpringMVC,hello,public,初识,servlet,class
From: https://blog.csdn.net/mjb709/article/details/141112012

相关文章

  • springMVC 请求流程解析
    @SuppressWarnings("deprecation")protectedvoiddoDispatch(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ //实际处理时用的请求,如果不是上传请求,则直接使用接收到的request,否则封装成上传的request HttpServletRequestprocessedRequ......
  • 初识c语言
    什么是c语言c语言是一门计算机编程语言,可广泛用于底层开发。c语言是一种能以简易方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。第一个c语言程序入门第一个c语言代码如下:那么其运行的结果就是打印helloworld,运行结果如下:......
  • 初识Spring
    文章目录一.Spring是什么?1.为什么要学?2.学什么?3.怎么学?二.Spring相关概念1.初识Spring1.1.Spring家族1.2.了解Spring发展史2.Spring系统架构2.1.系统架构图2.2.课程学习路线3.Spring核心概念3.1.目前项目中的问题3.2.IOC、IOC容器、Bean、DI3.3.核心......
  • 0001初识MySQL
    ##内容参考网课##笔记整理一,数据库基础知识1.数据库概念英文名称:Database,即存储数据的仓库;专业解释为存储在计算机磁盘上的有组织,可供享的大量数据的集合 类型关系数据库与非关系数据库两类,前者包含MySQL,Oracle,SQL,Server,SQLite等,后者包含Redis,MongoDB等数据库管理系......
  • 1.1javaSE初识
    JDK:JDK是JavaDevelopmentKit的缩写,意为Java语言的软件开发工具包(SDK)。它是Java编程的核心工具,为程序开发者提供了一个完整的开发环境。JRE:Java运行环境,是运行Java程序所必须的环境的集合,包含了JVM(Java虚拟机)和Java核心类库。Java开发工具:包括编译器(javac)、解释器(java)、调试......
  • 新建一个SpringMVC项目
    新建一个SpringMVC项目一、思路需求分析,主要考虑用例图、活动图建数据库新建maven项目设置项目的web框架pom.xml中导入依赖包,数据库、连接池、mybatis,mybatis-spring、spring、junit编写spring主配置文件applicationContext.xml,用于整合框架编写web.xml文件,DispatcherSer......
  • Java入门学习——Day01初识Java
    一、为什么学习Java1.1Java历史1.1.1背景介绍        Java语言最初由SunMicrosystems的詹姆斯·高斯林(JamesGosling)等人在1991年开始开发,当时SunMicrosystems希望开发一种能够在各种消费电子设备上运行的小型程序语言,最初命名为Oak。        1995年5月......
  • 初识LangChain的快速入门指南
    LangChain概述LangChain是一个基于大语言模型用于构建端到端语言模型应用的框架,它提供了一系列工具、套件和接口,让开发者使用语言模型来实现各种复杂的任务,如文本到图像的生成、文档问答、聊天机器人等。LangChain简化了LLM应用程序生命周期的各个阶段:开发阶段:使用Lan......
  • 算法与数据结构——初识
    算法初识算法定义:算法(algorithm)是在有限时间内解决特定问题的一组指令或操作步骤,它具有以下特性。问题是明确的,包含清晰的输入和输出定义。具有可行性,能够在有限步骤、时间和内存空间完成。各步骤都有确定的定义,在相同的输入和运行条件下,输出始终相同。数据结构定义:数据......
  • Vue初识,vue的插值语法,vue指令之文本指令,vue指令之事件指令, vue指令之属性指令
    ⅠVue初识【一】前端的发展史#1HTML(5)、CSS(3)、JavaScript(ES5、ES6、ES13):编写一个个的页面->给后端(PHP、Python、Go、Java)->后端嵌入模板语法->后端渲染完数据->返回数据给前端->在浏览器中查看#2Ajax的出现->后台发送异步请求,Render+Ajax混合#3单......