SpringMVC参数接收与数据返回详解

一,参数的接收

参数接收的几种方式:

1.使用servlet API接收参数

在方法参数中添加HttpServletRequest类型的参数,然后就可以像servlet的方法一样来接收参数

java 复制代码
@RequestMapping("p1")
    public String param1(HttpServletRequest request){
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        return "hello";
    }

2.在方法中定义同名参数

java 复制代码
@RequestMapping("param2")
    public String method2(int id,String name){
        System.out.println(id+name);
        return "param";
    }

如果url地址中的参数名与方法的参数名不一致时,可以使用RequestParam注解进行重新关联

java 复制代码
@RequestMapping("param3")
    public String method3(@RequestParam("p") String password){
        System.out.println(password);
        return "param";
    }

url地址中的参数名p,而方法中的参数名是password,这时我们可以使用RequestParam注解对参数进行重新关联

当我们在方法中接收一个整数类型的参数时,如果url中没有传递该参数则会抛异常。如果这个参数不是必须要传递的,我们可以给该参数设置默认值。

java 复制代码
@RequestMapping("p2")
    public String param2(String name,@RequestParam(defaultValue = "0") int age){
        System.out.println(name);
        System.out.println(age);
        return "hello";
    }

设置完默认值后,如果url中没有携带id参数,则该参数默认值为0,不会抛出异常

3.使用POJO类接收参数

什么是POJO?

"Plain Old Java Object""简单java对象"。POJO的内在含义是指那些没有从任何类继承、也没有实现任何接口,更没有被其它框架侵入的java对象。

java 复制代码
@RequestMapping("student")
    public String test(Student student){
        System.out.println(student);
        return "param";
    }

spring会自动的从请求中把参数名与Student类中属性名相同的数据,进行赋值

4.使用PathVariable接收参数

java 复制代码
//restful请求传参方式,可以传递多个参数,每个参数都用/分隔,但是不建议传递多个
    //最好只传一个
    @RequestMapping("p4/{id}")
    public String param4(@PathVariable("id") int id){
        System.out.println(id);
        return "hello";
    }

使用PathVariable进行参数传递,首先要在地址中添加占位符,然后使用PathVariable跟方法入参进行绑定

二,返回数据的几种方式

1.使用servlet API传递数据:

首先需要在方法中增加HttpServletRequest类型的参数,然后使用request对象传递数据,使用方式与之前学习servlet时的用法一致

java 复制代码
@RequestMapping("resp2")
    public String method2(HttpServletRequest request){
        request.setAttribute("msg","test");
        Student student=new Student();
        student.setName("张三");
        request.setAttribute("student",student);
        return "resp2";
    }

2.使用Map集合传递参数

首先需要在方法中增加java.util.Map类型的参数,然后使用map对象通过put方法,把数据写入到map中,进行数据传递

java 复制代码
@RequestMapping("resp3")
    public String method3(Map<String,Object> map){
        map.put("msg","map传参");
        Student student=new Student();
        student.setName("张三");
        map.put("student",student);
        return "resp2";
    }

3.使用Model传递数据:

首先需要在方法中增加Model类型的参数,然后使用model对象通过addAttribute方法,把数据写入到addAttribute对象中,进行数据传递

java 复制代码
 @RequestMapping("r2")
    public String res2(Model model){
        //springMVC推荐使Model进行
       model.addAttribute("msg","model 传参");
        return "resp";
    }

4.使用ModelAndView传递数据:

首先在方法中创建ModelAndView对象,使用addObject方法传递数据,使用setViewName设置要跳转的页面,注意方法的返回值也是ModelAndView类型

java 复制代码
@RequestMapping("resp5")
    public ModelAndView method(){
        ModelAndView mv=new ModelAndView();
        //使用addObject方法传递参数
        mv.addObject("msg","ModelAndView传参");
        //使用setViewName方法设置跳转页面
        mv.setViewName("resp2");
        return mv;
    }

以上四种返回数据的方式都可以使用,效率上也几乎无差别,没有具体的好与坏,想要使用哪种看自己的个人喜好

三,文件上传

  • Spring MVC 为文件上传提供了直接的支持,这种支持是通 过即插即用的 MultipartResolver 实现的。Spring 用 Jakarta CommonsFileUpload 技术实现了一个 MultipartResolver 实现类:CommonsMultipartResovler
  • Spring MVC 上下文中默认没有装配 MultipartResovler,因 此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 MultipartResolver

配置CommonsMultipartResolver

首先配置编码,必须跟jsp文件中的编码保持一致

maxUploadSize用来配置最大支持的文件大小,默认是不限制,单位是byte

XML 复制代码
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="5242880"/>
    </bean>

导入上传文件需要的jar包

XML 复制代码
<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

编写上传的jsp页面

注意enctype属性,如果不加是无法上传文件的

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>file</title>
</head>
<body>

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <br/>
    <input type="submit" value="上传">
</form>
</body>
</html>

编写用于上传的controller方法

注意参数类型,一定要用RequestParam注解标注,否则报错

java 复制代码
@RequestMapping("upload")
    public String upload(@RequestParam("file")MultipartFile file) throws Exception{
        //获取文件原名
        System.out.println(file.getOriginalFilename());
        String path="D:\\Java\\"+file.getOriginalFilename();
        file.transferTo(new File(path));
        return "hello";
    }

四,处理JSON数据

什么是JSON数据格式

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

JSON建构于两种结构:

  • "名称/值"对的集合(A collection of name/value pairs)。相当于Java中的Map
  • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

JSON数据格式

javascript 复制代码
{
"name": "张三",
"age": 20,
"email": "5689876@qq.com",
"phone": "15122334455",
}

这就是一段最简单的JSON格式的数据

SpringMVC返回JSON

1.配置jar包
XML 复制代码
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.11.2</version>
        </dependency>
2.配置文件中添加<mvc:annotation-driven/>标签
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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:comtext="http://www.springframework.org/schema/context"
       xmlns:avc="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <avc:annotation-driven/>
    <comtext:component-scan base-package="com.haina.springmvc"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="5242880"/>
    </bean>
</beans>
3.添加方法
java 复制代码
package com.haina.springmvc;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JSONController {

    //ResponseBody注解的作用是让该方法不再跳转页面,而是返回JSON格式的数据
    @RequestMapping("j1")
    @ResponseBody
    public Map<String,Object> j1(){
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("code",1001);
        map.put("msg","success");
        return map;
    }

    @RequestMapping("j2")
    @ResponseBody
    public Student j2(){
        Student st=new Student();
        st.setNo(1234);
        st.setName("张三");
        st.setAge(20);
        st.setMajor("计算机");
        return st;
    }

    @RequestMapping("j3")
    @ResponseBody
    public List<Student> j3(){
        List<Student> list=new ArrayList<Student>();
        for (int i=0;i<10;i++){
            Student st=new Student();
            st.setNo(1234+i);
            st.setName("张三"+i);
            st.setAge(20+i);
            st.setMajor("计算机"+i);
            list.add(st);

        }
        return list;
    }

}
相关推荐
幽络源小助理3 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
wfsm7 小时前
spring事件使用
java·后端·spring
ChinaRainbowSea12 小时前
补充:问题:CORS ,前后端访问跨域问题
java·spring boot·后端·spring
hqxstudying14 小时前
java依赖注入方法
java·spring·log4j·ioc·依赖
春生野草14 小时前
关于SpringMVC的整理
spring
Bug退退退12315 小时前
RabbitMQ 高级特性之重试机制
java·分布式·spring·rabbitmq
hello早上好16 小时前
CGLIB代理核心原理
java·spring
先睡1 天前
Redis的缓存击穿和缓存雪崩
redis·spring·缓存
Bug退退退1231 天前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq