SpringMVC学习

本文详细介绍了SpringMVC框架的基础使用,包括配置XML和注解方式,数据响应(返回ModelAndView、字符串、对象),以及数据接收(参数映射、对象和路径变量)。
摘要由CSDN通过智能技术生成

1.认识springMVC框架

  • MVC是一种设计思想,将一个应用分成3个基本部分,分别代表着Web应用程序中的3种职责
  • Model(模型):用于存储数据和完成业务逻辑处理
  • View(视图):用于显示数据和向控制器提交数据请求
  • Controller(控制器):根据视图请求调用Model完成业务处理,将处理后的结果交由View进行展示

图片来源:稀土掘金

Spring MVC的特点:

  • 轻量级,简单易学
  • 高效 , 基于请求响应的MVC框架
  • 松耦合,各个模块分离
  • 与Spring兼容性好,无缝结合
  • 约定优于配置
  • 功能强大:RESTful、数据验证、格式化、本地化、主题等
  • 简洁灵活

2.初用SpringMVC框架

方法1:xml方式:

先导入这里用maven的pom文件做演示,对应的jar也是类似:

<!--SpringMVC必要-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.8</version>
      </dependency>
<!--    Servlet相关的功能和特性 Web工程需要依赖属于 servlet-api.jar和jsp-api.jar-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

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

在web.xml中配置DispatcherServlet

解释:SpringMVC是基于Servlet的框架,DispatcherServlet是整个SpringMVC框架的核心

DispatcherServlet主要职责是接收所有用户请求,并将其分派给相应的Controller来处理

<!-- 配置DispatcherServlet -->
<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>
org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
<!-- 配置DispatcherServlet接受所有URL请求 -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 <!-- 编码过滤器,解决中文乱码问题 -->
    <filter>
        <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

注:url-pattern是”/”,千万不能写成”/*”

在resources下面建一个spring-mvc.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: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.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 将控制器扫描到容器中 -->
    <context:component-scan base-package="controller"/>

    <!-- 开启SpringMVC框架的注解驱动 -->
    <mvc:annotation-driven/>

    <!--    在容器钟帮我们注册一个bean DefaultServleHttpRequstHandler
            作用:中间组件,解决静态资源不能加载
    -->
    <!--    <mvc:default-servlet-handler></mvc:default-servlet-handler>-->

    <!--    在容器中注册一个bean 作用:在这个路径下下面找静态资源
            解决静态资源
    -->
    <mvc:resources location="/statics/" mapping="/statics/**" />
    <mvc:resources location="/uploadfiles/" mapping="/uploadfiles/**" />

    <!-- 上传文件解析器-->
    <!-- 配置 MultipartResolver -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 最大允许上传大小20MB -->
        <property name="maxUploadSize" value="20971520" />
    </bean>


</beans>

上面可以直接放进去,根据自己需求就保留需要的

修改web.xml,配置在tomcat启动的时候自动加载spring-mvc.xml”配置

 <!-- 加载类路径下的spring-mvc.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:spring-mvc.xml,
            </param-value>
        </init-param>

将上面这个添加到如下:

在web->WEB-INF下面建一个view文件夹用来放jsp文件(文件放WEB-INF是为了安全,不然直接访问xxx.jsp就能访问到)

hello.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
hello
</body>
</html>

在java代码处新建一个controller文件夹,再建一个HelloController

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

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}

注意:这里return之所以可以返回“hello”是因为在spring-mvc.xml里面我们已经添加了一个视图解析器:

⑦ 运行:idea中左上角打开文件->项目结构

然后配置一个Tomcat 运行起来,在浏览器中输入:

到这就已经配置好了SpringMVC ,并且能运行

方法2:注解方式:代替xml的②③④(也就是web.xml和spring-mvc.xml不用了

直接在java那创建一个config文件夹,然后建2个类:SpringMvcConfig和ServletContainersInitConfig

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
//当tomacat启动后先web.xml 前端控制器/
//当tomacat启动后  找当前类
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //加载配置类
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

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

    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}
import converter.DateConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("controller")
@EnableWebMvc  // Content type ‘application/json’ not supported当一直报改错
               //没有对应的 HttpMessageConverter 来处理 Content-Type 为 application/json 且 类型为自定义的类型(Person)。
               //解决方案:@EnableWebMvc 注解 放配置里面或者新建一个类
               //@Configuration
                //public class MvcConfig extends WebMvcConfigurationSupport {
                //}
public class SpringMvcConfig  {
    //视图解析器
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
    //在springmvc配置类中配置自定义类型转换器
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new DateConverter());
            }
        };
    }
}

 大家可以看到其实需要配置的和xml一样的,不过是注解方式

3.SpringMVC数据响应

①返回ModelAndView对象

在HelloController中:

    @RequestMapping("/hello2")
    public ModelAndView hello2(){
        //Model:模型,用于封装数据
        //View:视图,用于展示数据
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username","yb");//将数据放model里面
        modelAndView.setViewName("hello");
        return modelAndView;//返回这个视图以及数据username
    }

②Model:用法像session

    @RequestMapping("/hello3")
    public String hello4(Model model){
        model.addAttribute("username","yb");
        return "hello";
    } 

③返回字符串(@ResponseBody注解告知SpringMVC框架,方法返回的字符串)

 @RequestMapping("/hello4")
@ResponseBody
public String hello4(){
    return "hahahh哈哈哈";
}

④返回对象

导入一个json依赖:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
   </dependency>
@RequestMapping("/hello4")
  @ResponseBody
    public Phone data3() {
        Phone phone = new Phone();
        phone.setPhoneId(1L);
        phone.setBrandId(1L);
        phone.setModelNumber("mate60");
        phone.setCapacity(256);
        return phone;
    } 

4.SpringMVC数据接收

①获取基本类型参数

    @RequestMapping("/param1")
    @ResponseBody
     public void param1(int Id,String Number){//参数名一样自动映射
        System.out.println(Id);
         System.out.println(Number); 
    }

@RequestMapping("/param2")
     @ResponseBody

//参数名不一样 通过@RequestParam注解显示的绑定
    public void param2(int Id2,@RequestParam("Number") String Number2){ 
         System.out.println(Id2);
        System.out.println(Number2);
    }

 ②获取一个对象:@RequestBody表示会从请求体里面去拿,要是前端用的form表单,就不需要这个注解(这种用得最多,请注意,拿到的数据和自己后端User字段一致,这样会自动映射)

    @PostMapping("/getUserListPage")
    public R getUserListPage(@RequestBody User user){
        return userService.getUserListPage(user);
    }

③获取请求路径里面的:

	@RequestMapping("/param10/{date}")
    @ResponseBody
 public void param10(@PathVariable("date") Date date){
        System.out.println(date);
 }

总结:以上内容都是最基础使用的,更多内容还需自行学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值