Spring MVC 传递参数的几种方式

一 ajax带简单参数请求

controller

import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        return "testParam";
    }

    @RequestMapping(value = "test")
    @ResponseBody
    public Map<String, Object> test(String name, Integer age) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("name", name);
        result.put("age", age);
        return result;
    }

}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="${pageContext.request.contextPath}/script/plugins/inspinia/js/jquery-2.1.1.js"></script>
</head>
<body>

<script type="text/javascript">
    $.ajax({
        url: 'test.json',
        type: 'post',
        data: {
            name: '二狗',
            age: 3
        },
        async: true,
        cache: false,
        success: function (data) {
            console.log(JSON.stringify(data));
        }
    });
</script>

</body>

</html>

页面


20180824092236.png

二 ajax带数组参数请求

controller

import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        return "testParam";
    }

    /**
     * @param name
     * @param food 页面的food:[1,2,3]会已 food[]:1,food[]:2,food[]:3形式发送过来,所以这里要给food参数起个food[]别名,这样才能接收到
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "test")
    @ResponseBody
    public Map<String, Object> test(String name, @RequestParam(name = "food[]") String[] food) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("name", name);
        result.put("food", food);
        return result;
    }

}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="${pageContext.request.contextPath}/script/plugins/inspinia/js/jquery-2.1.1.js"></script>
</head>
<body>

<script type="text/javascript">
    $.ajax({
        url: 'test.json',
        type: 'post',
        data: {
            name: '二狗',
            food: ['狗粮','骨头','营养膏']
        },
        async: true,
        cache: false,
        success: function (data) {
            console.log(JSON.stringify(data));
        }
    });
</script>

</body>

</html>

页面


20180824093032.png

三 ajax带对象请求

实体类

package com.pandabus.custom.controller;

public class Dog {
    private String name;
    private String[] food;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String[] getFood() {
        return food;
    }

    public void setFood(String[] food) {
        this.food = food;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

controller

import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        return "testParam";
    }

    /***
     *
     * @param dog 需要添加@RequestBody注解,这样SpringMvc会把收到的JSON反序列化成实体
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "test")
    @ResponseBody
    public Map<String, Object> test(@RequestBody Dog dog) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("dog", dog);
        return result;
    }

}

JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="${pageContext.request.contextPath}/script/plugins/inspinia/js/jquery-2.1.1.js"></script>
</head>
<body>

<script type="text/javascript">
    var dog = {
        name: '二狗',
        food: ['狗粮', '骨头', '营养膏'],
        age: 3
    };

    $.ajax({
        url: 'test.json',
        type: 'post',
        contentType: 'application/json',//需要指定contentType
        data: JSON.stringify(dog),//传递对象的json
        async: true,
        cache: false,
        success: function (data) {
            console.log(JSON.stringify(data));
        }
    });
</script>

</body>

</html>

页面


20180824093911.png

四 ajax表单上传文件

controller

import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        return "testParam";
    }

    /***
     *
     * @param file 必须指定@RequestParam
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "test")
    @ResponseBody
    public Map<String, Object> test(@RequestParam(name = "file") CommonsMultipartFile file) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("content", readFile(file));
        return result;
    }

    private List<String> readFile(CommonsMultipartFile file) throws IOException {
        List<String> result = new ArrayList<>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
            return result;
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

    }
}

JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="${pageContext.request.contextPath}/script/plugins/inspinia/js/jquery-2.1.1.js"></script>
    <script src="${pageContext.request.contextPath}/script/js/jquery.form.js"></script> <!--引入jquery.form-->
</head>
<body>
<!-- form 指定 enctype -->
<form class="form-horizontal" id="uploadTxtForm" enctype="multipart/form-data">
    <input type="file" class="form-control" name="file" id="file">
    <button type="button" id="btn_upload">上传</button>
</form>

<script type="text/javascript">
    $("#btn_upload").click(function () {
        var option = {
            url: "test.json",
            type: "POST",
            async: true,
            success: function (data) {
                console.log(JSON.stringify(data));
            }
        };
        $("#uploadTxtForm").ajaxSubmit(option); //ajax 提交表单
    });
</script>

</body>

</html>

页面


20180824101930.png

五 ajax同时提交文件和参数

controller

import com.pandabus.framework.base.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/testParam/")
public class TestParamController extends BaseController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        return "testParam";
    }

    /***
     *
     * @param file 必须指定@RequestParam
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "test")
    @ResponseBody
    public Map<String, Object> test(@RequestParam(name = "file") CommonsMultipartFile file, String storyName) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("content", readFile(file));
        result.put("storyName", storyName);
        return result;
    }

    private List<String> readFile(CommonsMultipartFile file) throws IOException {
        List<String> result = new ArrayList<>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
            return result;
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

    }
}

JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="${pageContext.request.contextPath}/script/plugins/inspinia/js/jquery-2.1.1.js"></script>
    <script src="${pageContext.request.contextPath}/script/js/jquery.form.js"></script> <!--引入jquery.form-->
</head>
<body>
<!-- form 指定 enctype -->
<form class="form-horizontal" id="uploadTxtForm" enctype="multipart/form-data">
    <input type="file" class="form-control" name="file">
    <input type="text" class="form-control" name="storyName"><br>
    <button type="button" id="btn_upload">提交</button>
</form>

<script type="text/javascript">
    $("#btn_upload").click(function () {
        var option = {
            url: "test.json",
            type: "POST",
            async: true,
            success: function (data) {
                console.log(JSON.stringify(data));
            }
        };
        $("#uploadTxtForm").ajaxSubmit(option); //ajax 提交表单
    });
</script>

</body>

</html>

页面


20180824102920.png

六 Java代码同时上传代码和附件

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

public final class Test {


    public static void main(String[] args) throws IOException {
        HttpPost httpPost = new HttpPost("http://xxxx:8080/yyyy//deviceConfig/uploadLogs.json");
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse resp = null;
        String respondBody = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            httpPost.setConfig(requestConfig);

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody("file", new File("/var/root/Desktop/aaa.txt"));//附件
            multipartEntityBuilder.addTextBody("logOperationId", "18");//普通参数
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            resp = client.execute(httpPost);
            respondBody = EntityUtils.toString(resp.getEntity());
            System.out.println(respondBody);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } finally {
            resp.close();
        }
    }

}

@ResponseBody
    @RequestMapping(value = "uploadLogs")
    public Map<String, Object> uploadLogs(@RequestParam("file") CommonsMultipartFile file, Integer logOperationId) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //TODO 操作参数
        return result;
    }

Java代码上传file和text

public static void main(String[] args) throws IOException {
        HttpPost httpPost = new HttpPost("http://localhost:8080/long_river/xxx/yyy.json");
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse resp = null;
        String respondBody = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            httpPost.setConfig(requestConfig);

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody("files", new File("/var/root/Desktop/testMap.html"));
            multipartEntityBuilder.addBinaryBody("files", new File("/var/root/Desktop/menu.html"));
            multipartEntityBuilder.addTextBody("deviceIds", "18");
            multipartEntityBuilder.addTextBody("deviceIds", "19");
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            resp = client.execute(httpPost);
            respondBody = EntityUtils.toString(resp.getEntity());
            System.out.println(respondBody);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } finally {
            resp.close();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容

  • 春有百花秋有月,夏有凉风冬有雪, 抛开闲事由它去,静享人间好时节。
    水到渠成1阅读 231评论 7 11
  • 几天没写了,因为一些事情烦的焦头烂额。 打死我也没想到的事情发生了,来的那么突然,不知道该怎么办,该如何去解决。我...
    哈哈哈吖吖a阅读 214评论 4 0