大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專(zhuān)注Java教育14年 全國(guó)咨詢(xún)/投訴熱線:400-8080-105
動(dòng)力節(jié)點(diǎn)LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁(yè) hot資訊 幾種SpringMVC參數(shù)傳遞的方式

幾種SpringMVC參數(shù)傳遞的方式

更新時(shí)間:2022-03-25 10:05:05 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽2360次

SpringMVC參數(shù)傳遞的方式有幾種?小編來(lái)告訴大家。

1.簡(jiǎn)單的ajax參數(shù)請(qǐng)求

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>

頁(yè)面

2.ajax帶數(shù)組參數(shù)請(qǐng)求

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 頁(yè)面的food:[1,2,3]會(huì)已 food[]:1,food[]:2,food[]:3形式發(fā)送過(guò)來(lái),所以這里要給food參數(shù)起個(gè)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: ['狗糧','骨頭','營(yíng)養(yǎng)膏']
        },
        async: true,
        cache: false,
        success: function (data) {
            console.log(JSON.stringify(data));
        }
    });
</script>
</body>
</html>

頁(yè)面

3.ajax帶對(duì)象請(qǐng)求

實(shí)體類(lèi)

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會(huì)把收到的JSON反序列化成實(shí)體
     * @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: ['狗糧', '骨頭', '營(yíng)養(yǎng)膏'],
        age: 3
    };
    $.ajax({
        url: 'test.json',
        type: 'post',
        contentType: 'application/json',//需要指定contentType
        data: JSON.stringify(dog),//傳遞對(duì)象的json
        async: true,
        cache: false,
        success: function (data) {
            console.log(JSON.stringify(data));
        }
    });
</script>
</body>
</html>

頁(yè)面

4.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>

頁(yè)面

5.ajax同時(shí)提交文件和參數(shù)

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>

頁(yè)面

6.Java代碼同時(shí)上傳代碼和附件

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");//普通參數(shù)
            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 操作參數(shù)
        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();
        }
    }

以上就是關(guān)于“幾種SpringMVC參數(shù)傳遞的方式”的介紹,大家如果想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下動(dòng)力節(jié)點(diǎn)的SpringMVC教程,里面的課程內(nèi)容細(xì)致全面,由淺到深,適合沒(méi)有基礎(chǔ)的小伙伴學(xué)習(xí),希望對(duì)大家能夠有所幫助。

提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)

  • 全國(guó)校區(qū) 2025-06-26 搶座中
免費(fèi)課程推薦 >>
技術(shù)文檔推薦 >>
主站蜘蛛池模板: 美日韩免费视频 | 日本国产成人精品视频 | 亚洲一级毛片视频 | 狠狠综合久久综合网站 | 亚洲精品一二区 | 99国产大尺度福利视频 | 奇米影音四色 | 久久小视频 | 久久天堂成人影院 | 劲爆欧美色欧美 | 日韩欧美精品一区二区三区 | 精品精品国产高清a毛片 | 99热这里只有精品在线播放 | 久久精品国产福利国产秒 | 日韩欧美成人免费中文字幕 | 天天射天天射天天干 | 福利视频免费观看 | 国产成人久久久精品毛片 | 久草在线视频免费资源观看 | 成人欧美视频在线观看 | 国产精品区一区二区免费 | 欧美一区日韩一区中文字幕页 | 亚洲成人在线视频观看 | 777奇米影视网 | 亚洲va国产日韩欧美精品色婷婷 | 四虎国产精品免费入口 | 精品国产一区二区三区久 | 99九色 | 久热中文字幕在线 | 香蕉视频一级 | 呦系列视频一区二区三区 | 国产成人禁片在线观看 | 国产精品短篇二区 | 亚洲欧美日韩国产综合高清 | 日本特级aⅴ一级毛片 | 精品国产免费一区二区 | 精品无码久久久久久国产 | 欧美视频一区二区三区在线观看 | 久久精品一区二区三区中文字幕 | 成年人免费在线视频 | 欧美成人一区二免费视频 |