SpringMVC 接收json和form格式参数 并测试(后端httpCilent和前端AJAX)

本文详细介绍了SpringMVC框架下如何使用Ajax进行前后端交互,包括接收JSON对象、处理复杂数据类型如List和Map,以及通过不同方式提交数据的方法。同时,展示了如何利用HttpClient和jQuery进行POST和GET请求,实现数据的发送与接收。
摘要由CSDN通过智能技术生成

 

controller:

@RestController
@Slf4j
@RequestMapping("apiContract")
public class ApiContractController {
	@Autowired
	private ContractService contractService;
	
	
	 // 接受 复杂的js字符串 对象即json对象的字符串,用@RequestBody标签
	@PostMapping("/saveContract")
	public R saveContract(@RequestBody ContractVO contract){

		System.out.println(contract);
    }
	/**
	 * 接受form表单提交 即json对象,用 @RequestParam,为了便于操作,可以map转entity
	 */
	@RequestMapping("uploadExcelPersonCase")
	public R uploadExcelPersonCase(@RequestParam MultipartFile file,Map map){
		if(file == null){
			return R.error("文件为空");
		}
		CheckRequestParamUtil.checkIfParamError(map, "contractCode","amountFromExcel");
		InvoiceApplyVO VO = (InvoiceApplyVO) MapBeanUtil.map2Object(map,InvoiceApplyVO.class);//map转entity
		R r = contractService.uploadExcelPersonCase(file,VO);
		return r;
	}
    

controller中用到---ContractVO: 

 

package com.navitek.ylt.vo;

import lombok.Data;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: syl
 * @Date: 2019/7/4 0004 15:34
 * @Description:
 */
@Data
public class ContractVO {

    //合同编码  【手工敲判重}
    private String contractCode;
 
   

/*==============================费率相关======================================*/
    //厂家总成本
    private BigDecimal factoryCost;
    //园区服务费
    private BigDecimal parkServiceFee;
    //总包毛利
    private BigDecimal totalPackageMargin;
    //分包毛利
    private BigDecimal subcontractMargin;

    //乙方id
    private String partybId;

    //分包的机构编码
    private List<String> partybSubId;

    private List<ServiceVO> serviceList;//此处是一个object集合

}

 controller中用到---servceVO:

@Data
public class ServiceVO {
    private String serviceId;
    private BigDecimal truePrice;
}

controller相关---MapBeanUtil:

 

package com.navitek.utils;


        import java.lang.reflect.Field;
        import java.lang.reflect.Modifier;
        import java.util.HashMap;
        import java.util.Map;

/**
 * map转bean,bean转map
 */
public class MapBeanUtil {

    /**
     * 实体对象转成Map
     *
     * @param obj 实体对象
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * Map转成实体对象
     *
     * @param map   实体对象包含属性
     * @param clazz 实体对象类型
     * @return
     */
    public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
        if (map == null) {
            return null;
        }
        Object obj = null;
        try {
            obj = clazz.newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}

 

 HttpClient测试:

package com.navitek.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.*;


/**
 * 功能描述: HttpclientUtil 远程调用 json  和  form 格式
 *
 * @param:
 * @return:
 * @author: syl
 * @date: 2019/1/28 0028 下午 3:32
 */
@Slf4j
public class HttpclientUtil {
    /**
     * get请求
     *
     * @return
     */
    public static String doGet(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                log.info("get 返回信息:" + strResult);
                return strResult;
            }
        } catch (IOException e) {
            log.error("get 出错:" + e);
        }
        return null;
    }

    /**
     * post请求(用于key-value格式的参数) js对象
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params) {
        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                return sb.toString();
            } else {    //
                log.info("出错==状态码:" + code);
                return null;
            }
        } catch (Exception e) {
            log.info("post请求(用于key-value格式的参数) js对象" + e);
            return null;
        }
    }

    /**
     * post请求(用于请求json格式的参数) js对象的字符串
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPostJsonStr(String url, Object param) throws Exception {
        String params = JSON.toJSONString(param);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            } else {
                log.error("请求返回:" + state + "(" + url + ")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 功能描述:HttpUrlConnection请求
     *
     * @param:
     * @return:
     * @author: syl
     * @date: 2019/2/15 0015 上午 9:51
     */
    public static String doGetHttp(String strUrl) throws IOException {
        // String strUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=106.15.15.14"; //这是我临时建的web项目,去访问它的index.jsp界面
        URL url = new URL(strUrl);
        HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
        InputStreamReader input = new InputStreamReader(httpcon.getInputStream(), "utf-8");
        BufferedReader br = new BufferedReader(input);
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) { //读取每行数据
            sb.append(line);
            sb.append("\r\n");
        }
        String sbString = sb.toString();
        log.info("result... " + sbString);
        return sbString;
    }

    public static void main(String[] args) throws Exception {
        String base = "http://localhost:8080";
        String method = "/apiContract/saveContract";
        Map<String, Object> p = new HashMap<>();
        p.put("contractCode", "111");
        log.info(p.toString());
         HttpclientUtil.doPostJsonStr(base+method,p);
        String method1 = "/apiContract/test";
        HttpclientUtil.doPost(base + method1, p);

    }
}

html +Jquery    AJax测试:

------ post js 对象提交

$.ajax({
            //提交数据的类型 POST GET
            type:"POST",
            //提交的网址
            url:"apiContract/saveContract",
            //提交的数据   该参数为属性值类型的参数
         //(和url?Name="sanmao"&Password="sanmapword"一样)后台若为SpringMVC接受,注明@RequestParam
            data:{contractCode:"10000",partyaId:"1111",list:[{a:"1"},{b:"c"}]},
            //返回数据的格式
            datatype: "html",//"xml", "html", "script", "json", "jsonp", "text".
            //在请求之前调用的函数
            beforeSend:function(){console.log("来啊快活啊")},
            //成功返回之后调用的函数             
            success:function(data){
           		console.log(data);           
            }   ,
            //调用执行后调用的函数
            complete: function(XMLHttpRequest, textStatus){
               console.log(XMLHttpRequest.responseText);
               console.log(textStatus);
                //HideLoading();
            },
            //调用出错执行的函数
            error: function(e){
               console.log(e); console.log("大哥出错了 ");//请求出错处理
            }         
         });





         ------ js 对象转 字符串 

         $.ajax({
            //提交数据的类型 POST GET
            type:"POST",
            //提交的网址
            url:"apiContract/saveContract",
            //提交的数据   该参数为属性值类型的参数
         //(和url?Name="sanmao"&Password="sanmapword"一样)后台若为SpringMVC接受,注明@RequestBody
            data:JSON.stringify({contractCode:"10000",partyaId:"1111",partybSubId:["aa","bbb"],serviceList:[{serviceId:1,a:2}]}),contentType: "application/json; charset=utf-8",
            //返回数据的格式
            datatype: "html",//"xml", "html", "script", "json", "jsonp", "text".
            //在请求之前调用的函数
            beforeSend:function(){console.log("来啊快活啊")},
            //成功返回之后调用的函数             
            success:function(data){
               console.log(data);           
            }   ,
            //调用执行后调用的函数
            complete: function(XMLHttpRequest, textStatus){
               console.log(XMLHttpRequest.responseText);
               console.log(textStatus);
                //HideLoading();
            },
            //调用出错执行的函数
            error: function(e){
               console.log(e); console.log("大哥出错了 ");//请求出错处理
            }         
         });

用html,在html引入Jquery就行。然后打开chrome,在console中测试即可。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

somdip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值