精华内容
下载资源
问答
  • servlet发送字符串
    千次阅读
    2019-05-01 23:29:35

    Servlet

    //引入相关包
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import net.sf.json.JSONObject;

    aaa=“string”;
    JSONObject json = new JSONObject();
    json.put(“bbb”,aaa);
    response.getWriter().write(json.toString());//将json格式数据发送到前端

    jsp

    var test1=JSON.parse(xmlHttp.responseText);
    // var test2=test1.aaa;
    var test2=test1["aaa"];
    
    更多相关内容
  • Servlet处理JSON字符串传输问题

    千次阅读 2018-07-08 11:02:00
    过程中遇到了一些问题,其中就出现了Json字符串传输问题。 1、request.getParameter()方法问题 刚开始前端通过get请求传输数据,后端采用request.getParameter()方法接收数据。但后来有了局部刷新需求,前端...

    前些时候做学校的实践周项目,因为功能比较简单,没有采用框架直接用Servlet实现。过程中遇到了一些问题,其中就出现了Json字符串传输问题。

    1、request.getParameter()方法问题

    刚开始前端通过get请求传输数据,后端采用request.getParameter()方法接收数据。但后来有了局部刷新需求,前端改用Ajax发送json请求后,request.getParameter()接收不到数据。然后同学告诉我是因为json数据是通过request body(请求体)传送的,而request.getParameter()只能获取request head(请求头)中的数据,所以原来的方法无效。

    2、Java解析json问题

    2.1 实现方法

    放弃request.getParameter()方法,采用流的方式读取request body中的json串。然后将json字符串转为JSONObject对象,最后将JSONPObject对象转为Java对象。

    这里需要导入json支持包,一共有6个包,必不可少。

    f6c9ea2256ec6a32833b9ba907fe748cd49.jpg

    实现方法如下:

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader( 
                                     (ServletInputStream)request.getInputStream(), "utf-8"));  
        StringBuffer sb = new StringBuffer("");  
        String temp;  
        while ((temp = br.readLine()) != null) {  
            sb.append(temp);  
        }  
        br.close(); 
        //获取到的json字符串 
        String acceptjson = sb.toString();  
        //将json字符串转为jsonobject对象
    	JSONObject json = JSONObject.fromObject(acceptjson);
        //将jsonobject对象转为java对象
        Client client = (Client)JSONObject.toBean(json,Client.class);
        System.out.println(client);
    } catch (Exception e) {  
        e.printStackTrace();    
    }

    2.2 遇到的问题

    导入包的版本不对。这是一个教导人使用Maven的很好的例子,如果使用Maven就不会有这些问题了。错误的包可能不含有相关方法,在程序运行的时候会报空错误。当时是换了好几个不同版本的包才把报错解决掉,所以最好还是使用Maven进行管理。

    展开全文
  • //将传入的xml字符串转换为map集合 Map,String> params = new HashMap,String>(); params = this.parseXmlToMap(xmlData); //验签 String posSign = genMac(xmlData); //得到请求报文的密文 String ...

    客户端代码:

    @Action(value = "/sendxmlTest", results = { 
    			@Result(name = SUCCESS, location = "condo/accountOpenApplly.jsp"),
    			@Result(name = INPUT, location = "base/error.jsp") })
    	public String sendxmlTest(){
    		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
    						"<request>\n" + 
    						"  <head>\n" + 
    						"    <transType>0101</transType>\n" + 
    						"    <terminalVer>1.0.0</terminalVer>\n" + 
    						"    <dateTime>20170407103000</dateTime>\n" + 
    						"  </head>\n" + 
    						"  <body>\n" + 
    						"    <contactNo>Test00001</contactNo>\n" + 
    						"  </body>\n" + 
    						"<mac>902de37505fce863f4489a87c7e3fa6c</mac>"+
    						"</request>";
    
    		String url = "http://127.0.0.1:8080/zxemm/contactServlet.htm";
    		try {
    			String resultXml = SubmitUtils.buildRequest(url, xml);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	return SUCCESS;
    		
    	}

    服务端代码:

    package com.jiuyi.net.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    
    import com.jiuyi.jyplat.entity.condo.ContactInfo;
    import com.jiuyi.jyplat.service.SpringContextUtil;
    import com.jiuyi.jyplat.service.condo.IContactInfoService;
    import com.jiuyi.jyplat.util.ConfigManager;
    import com.jiuyi.jyplat.util.DateUtils;
    import com.jiuyi.jyplat.util.Utils;
    import com.jiuyi.net.message.httpClient.XMLUtil;
    import com.jiuyi.net.message.pos.contact.QurContactRsp;
    import com.jiuyi.net.message.pos.contact.QurContactRspMsg;
    import com.jiuyi.net.message.pos.contact.RequestHead;
    import com.jiuyi.net.utils.PosMacUtils;
    
    /**
     * 
     * <p><b>Title: </b>ContactServlet.java
     * <p><b>Description: </b>合同信息查询servlet
     * @author 
     * @version V1.0
     * <p>
     * 2017-4-6  创建类  <br>
     *
     */
    public class ContactServlet extends HttpServlet{
    
    	private static final long serialVersionUID = 1L;
    	
    	Logger log = Logger.getLogger(ContactServlet.class);
    	
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doPost(request, response);
    	}
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		log.info("收到查询合同信息的请求...");
    		QurContactRspMsg rspMsg = new QurContactRspMsg();
    		QurContactRsp rsp = new QurContactRsp();
    		RequestHead head = new RequestHead();
    		head.setTransType("0101");
    		head.setTerminalVer("V1.0");
    		head.setDateTime(DateUtils.getToday(DateUtils.TIME_STR_FORMAT));
    		PrintWriter out = response.getWriter();
    		ServletInputStream sis = null;  
    		String xmlData="";
    		Map<String,String> macMap = new HashMap<String,String>();
    		String posKey = (String) ConfigManager.getInstance().getConfigItem("pos_key", ""); //获取配置文件中的加密key
    		try {
    			//编码格式改成UTF-8
    			response.setCharacterEncoding("UTF-8");
    			request.setCharacterEncoding("UTF-8");
    			response.setContentType("textml; charset=UTF-8");
    			response.setHeader("Content-type", "text/html;charset=UTF-8");
    			
    			sis=request.getInputStream();
    			// 取HTTP请求流长度  
                int size = request.getContentLength();  
                // 用于缓存每次读取的数据  
                byte[] buffer = new byte[size];  
                // 用于存放结果的数组  
                byte[] xmldataByte = new byte[size];  
                int count = 0;  
                int rbyte = 0;  
                // 循环读取  
                while (count < size) {   
                    // 每次实际读取长度存于rbyte中  
                    rbyte = sis.read(buffer);   
                    for(int i=0;i<rbyte;i++) {  
                        xmldataByte[count + i] = buffer[i];  
                    }  
                    count += rbyte;  
                }  
                  
                xmlData = new String(xmldataByte, "UTF-8");  
                log.info("查询合同信息接口接收的xmlData为:"+xmlData);
                
                //将传入的xml字符串转换为map集合
    			Map<String,String> params = new HashMap<String,String>();
                params = this.parseXmlToMap(xmlData);
    
                //验签
    			String posSign = genMac(xmlData); //得到请求报文的密文
    			String mySign = PosMacUtils.buildRequestMysign(params,posKey);
    			if(Utils.isNullData(posSign,mySign) || !posSign.equals(mySign)){
    				log.error("调用保存pos机交易流水接口验签失败!");
    				head.setResponseCode("0001");
    				head.setResponseDesc("验签失败");
    				rspMsg.setHead(head);
    				String xmlRsp = XMLUtil.objToxml(rspMsg);
    				xmlRsp = XMLUtil.formatXml(xmlRsp);
    				
    				macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    				String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    				rspMsg.setMac(mac);
    				String resultXml = XMLUtil.objToxml(rspMsg);
    				resultXml = XMLUtil.formatXml(resultXml);
    				log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    				out.print(resultXml);
    				out.flush();
    				out.close();
    				return;
    			}
    			
    			
    			
    			//获取请求参数中的合同号
    			String contactNo = params.get("contactNo");
    			String transType = params.get("transType");
    			if(Utils.isNullData(contactNo,transType)){
    				log.error("调用查询合同信息接口请求参数不完整,请检查!");
    				head.setResponseCode("0011");
    				head.setResponseDesc("请求参数不完整");
    				rspMsg.setHead(head);
    				String xmlRsp = XMLUtil.objToxml(rspMsg);
    				xmlRsp = XMLUtil.formatXml(xmlRsp);
    				
    				macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    				String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    				rspMsg.setMac(mac);
    				String resultXml = XMLUtil.objToxml(rspMsg);
    				resultXml = XMLUtil.formatXml(resultXml);
    				log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    				out.print(resultXml);
    				out.flush();
    				out.close();
    				return;
    			}
    			IContactInfoService contactInfoService = (IContactInfoService)SpringContextUtil.getBean("contactInfoService");
    			ContactInfo c = contactInfoService.findByContactNo(contactNo);
    			if(null==c){
    				head.setResponseCode("0001");
    				head.setResponseDesc("查询合同信息不存在");
    				rspMsg.setHead(head);
    				String xmlRsp = XMLUtil.objToxml(rspMsg);
    				xmlRsp = XMLUtil.formatXml(xmlRsp);
    				
    				macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    				String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    				rspMsg.setMac(mac);
    				String resultXml = XMLUtil.objToxml(rspMsg);
    				resultXml = XMLUtil.formatXml(resultXml);
    				log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    				out.print(resultXml);
    				out.flush();
    				out.close();
    				return;
    			}
    			if(null!=c && "1111".equals(c.getStatus())){//合同已撤销
    				head.setResponseCode("0004");
    				head.setResponseDesc("退款中(合同已撤销)");
    				rspMsg.setHead(head);
    				String xmlRsp = XMLUtil.objToxml(rspMsg);
    				xmlRsp = XMLUtil.formatXml(xmlRsp);
    				
    				macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    				String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    				rspMsg.setMac(mac);
    				String resultXml = XMLUtil.objToxml(rspMsg);
    				resultXml = XMLUtil.formatXml(resultXml);
    				log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    				out.print(resultXml);
    				out.flush();
    				out.close();
    				return;
    			}
    			if(null!=c && "2222".equals(c.getStatus())){//无效合同
    				head.setResponseCode("0010");
    				head.setResponseDesc("无效合同");
    				rspMsg.setHead(head);
    				String xmlRsp = XMLUtil.objToxml(rspMsg);
    				xmlRsp = XMLUtil.formatXml(xmlRsp);
    				
    				macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    				String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    				rspMsg.setMac(mac);
    				String resultXml = XMLUtil.objToxml(rspMsg);
    				resultXml = XMLUtil.formatXml(resultXml);
    				log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    				out.print(resultXml);
    				out.flush();
    				out.close();
    				return;
    			}
    			rsp.setBackCardName(c.getBackCardName());
    			rsp.setBankCode(c.getBackCardNo());
    			rsp.setCompanyName(c.getCompanyName());
    			rsp.setContactAmt(null==c.getContactAmt()?0.0:Double.parseDouble(c.getContactAmt()));
    			rsp.setContactNo(c.getContactNo());
    			rsp.setCreateDate(c.getCreateDate());
    			rsp.setHouseAddr(c.getHouseAddr());
    			rsp.setHouseArea(null==c.getHouseArea()?0.0:Double.parseDouble(c.getHouseArea()));
    			rsp.setHouseNo(c.getHouseNo());
    			rsp.setOperNo(c.getOperNo());
    			rsp.setPayCont(null==c.getPayCont()?0.0:Double.parseDouble(c.getPayCont()));
    			rsp.setPaymentCode(c.getPaymentCode());
    			rsp.setProjectName(c.getProjectName());
    			rsp.setProjectNo(c.getProjectNo());
    			rsp.setRoomNo(c.getRoomNo());
    			rsp.setSuperviseAmt(null==c.getSuperviseAmt()?0.0:Double.parseDouble(c.getSuperviseAmt()));
    			rsp.setUnitNo(c.getUnitNo());
    			head.setResponseCode("0000");
    			head.setResponseDesc("交易成功");
    			rspMsg.setHead(head);
    			rspMsg.setBody(rsp);
    			String xmlRsp = XMLUtil.objToxml(rspMsg);
    			xmlRsp = XMLUtil.formatXml(xmlRsp);
    			
    			macMap = this.parseXmlToMap(xmlRsp); //将xml报文转换成map集合用于生成密文
    			String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    			rspMsg.setMac(mac);
    			String resultXml = XMLUtil.objToxml(rspMsg);
    			resultXml = XMLUtil.formatXml(resultXml);
    			log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    			out.print(resultXml);
    			out.flush();
    			out.close();
    			return;
    			
    		} catch (Exception e) {
    			log.error("调用保存pos机交易流水接口出现异常!"+e.toString(), e);
    			String returnXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    			returnXml+="<response><head><dateTime>"+DateUtils.getToday(DateUtils.TIME_STR_FORMAT)+"</dateTime>";
    			returnXml+=" <responseCode>9999</responseCode><responseDesc>系统异常</responseDesc><terminalVer>V1.0</terminalVer><transType>0101</transType></head></response>";
    			macMap = this.parseXmlToMap(returnXml); //将xml报文转换成map集合用于生成密文
    			String mac = PosMacUtils.buildRequestMysign(macMap, posKey);
    			String resultXml ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    			resultXml += "<response><head><dateTime>"+DateUtils.getToday(DateUtils.TIME_STR_FORMAT)+"</dateTime>";
    			resultXml+=" <responseCode>9999</responseCode><responseDesc>系统异常</responseDesc><terminalVer>V1.0</terminalVer><transType>0101</transType></head><mac>"+mac+"</mac></response>";
    			log.info("调用保存pos机交易流水接口返回报文为:"+resultXml);
    			out.print(resultXml);
    			out.flush();
    			out.close();
    			return;
    		}
    		
    	}
    	
    	
    	/**
    	 * 
    	 * <p><b>Description: </b>得到发送过来的密文
    	 * <p>2017-4-7 下午12:34:45
    	 * @author 
    	 * @param xml
    	 * @return
    	 */
    	public static String genMac(String xml){
    		try {
    			Document doc = null;  
    			// 将字符串转为XML  
    			doc = DocumentHelper.parseText(xml);   
    			// 获取根节点  
    			Element rootElt = doc.getRootElement();   
          
    			String mac =  rootElt.elementTextTrim("mac");
    			return mac;
    		} catch (DocumentException e) {
    			e.printStackTrace();
    		}   
    		return null;
    	}
    	
    	/**
    	 * 
    	 * <p><b>Description: </b>解析查询合同信息接口的请求报文
    	 * <p>2017-4-7 上午10:27:02
    	 * @author 
    	 * @param xml
    	 * @return
    	 */
    	public static Map parseXmlToMap(String xml) {  
    	      Map map = new HashMap();  
    	      Document doc = null;  
    	      try {  
    	          // 将字符串转为XML  
    	          doc = DocumentHelper.parseText(xml);   
    	          // 获取根节点  
    	          Element rootElt = doc.getRootElement();   
    	          // 获取根节点下的子节点head  
    	          Iterator iter = rootElt.elementIterator("head");   
    	          // 遍历head节点  
    	          while (iter.hasNext()) {  
    	  
    	              Element recordEle = (Element) iter.next();  
    	              // 拿到head节点下的子节点transType值  
    	              String transType = recordEle.elementTextTrim("transType");   
    	              map.put("transType", transType);  
    	              // 拿到head节点下的子节点terminalVer值  
    	              String terminalVer = recordEle.elementTextTrim("terminalVer");   
    	              map.put("terminalVer", terminalVer);  
    	              // 拿到head节点下的子节点dateTime值  
    	              String dateTime = recordEle.elementTextTrim("dateTime");   
    	              map.put("dateTime", dateTime);  
    	              
    	              // 拿到head节点下的子节点responseCode值  
    	              String responseCode = recordEle.elementTextTrim("responseCode");   
    	              map.put("responseCode", responseCode);  
    	              // 拿到head节点下的子节点responseDesc值  
    	              String responseDesc = recordEle.elementTextTrim("responseDesc");   
    	              map.put("responseDesc", responseDesc);  
    	          }  
    	  
    	          //获取根节点下的子节点body  
    	          Iterator iterss = rootElt.elementIterator("body");   
    	          // 遍历body节点  
    	          while (iterss.hasNext()) {  
    	              Element recordEless = (Element) iterss.next();  
    	              // 拿到body节点下的子节点contactNo值  
    	              String contactNo = recordEless.elementTextTrim("contactNo");   
    	              map.put("contactNo", contactNo); 
    	              
    	              String contactAmt = recordEless.elementTextTrim("contactAmt");   
    	              map.put("contactAmt", contactAmt); 
    	              
    	              String superviseAmt = recordEless.elementTextTrim("superviseAmt");   
    	              map.put("superviseAmt", superviseAmt); 
    	              
    	              String houseNo = recordEless.elementTextTrim("houseNo");   
    	              map.put("houseNo", houseNo); 
    	              
    	              String houseArea = recordEless.elementTextTrim("houseArea");   
    	              map.put("houseArea", houseArea); 
    	              
    	              String houseAddr = recordEless.elementTextTrim("houseAddr");   
    	              map.put("houseAddr", houseAddr); 
    	              
    	              String backCardName = recordEless.elementTextTrim("backCardName");   
    	              map.put("backCardName", backCardName); 
    	              
    	              String roomNo = recordEless.elementTextTrim("roomNo");   
    	              map.put("roomNo", roomNo); 
    	              
    	              String bankCode = recordEless.elementTextTrim("bankCode");   
    	              map.put("bankCode", bankCode); 
    	              
    	              String unitNo = recordEless.elementTextTrim("unitNo");   
    	              map.put("unitNo", unitNo); 
    	              
    	              String projectName = recordEless.elementTextTrim("projectName");   
    	              map.put("projectName", projectName); 
    	              
    	              String projectNo = recordEless.elementTextTrim("projectNo");   
    	              map.put("projectNo", projectNo); 
    	              
    	              String companyName = recordEless.elementTextTrim("companyName");   
    	              map.put("companyName", companyName); 
    	              
    	              String createDate = recordEless.elementTextTrim("createDate");   
    	              map.put("createDate", createDate); 
    	              
    	              String paymentCode = recordEless.elementTextTrim("paymentCode");   
    	              map.put("paymentCode", paymentCode); 
    	              
    	              String payCont = recordEless.elementTextTrim("payCont");   
    	              map.put("payCont", payCont); 
    	              
    	              String operNo = recordEless.elementTextTrim("operNo");   
    	              map.put("operNo", operNo); 
    	              
    	          }  
    	      } catch (DocumentException e) {  
    	          e.printStackTrace();  
    	      } catch (Exception e) {  
    	          e.printStackTrace();  
    	      }  
    	      return map;  
    	  }  
    }
    
    发送xml格式字符串请求报文的代码

    package com.jiuyi.net.utils;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    
    public class SubmitUtils {
    	
    	/**
         * 建立请求,以模拟远程HTTP的POST请求
         * @param urlStr 请求地址
         * @param xmlInfo 请求的xml内容
         * @return 返回请求内容 xml字符串
         * @throws Exception
         */
        public static String buildRequest(String urlStr,String xmlInfo) throws Exception {
        	String strResult = "";
        	HttpURLConnection httpConn = null;
        	BufferedReader bufReader = null;
        	InputStreamReader input = null;
        	
    		try {
    			URL url = new URL(urlStr);
    			httpConn = (HttpURLConnection) url.openConnection();
    			httpConn.setFollowRedirects(true);
    			httpConn.setDoOutput(true); // 需要向服务器写数据
    			httpConn.setDoInput(true); //
    			httpConn.setUseCaches(false); // 获得服务器最新的信息
    			httpConn.setAllowUserInteraction(false);
    			httpConn.setRequestMethod("POST");
    			httpConn.addRequestProperty("accept", "text/xml;text/html");
    			httpConn.addRequestProperty("Content-Type",  "text/xml;charset=utf-8");
    			httpConn.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
    			httpConn.setRequestProperty("Referer","http://passport.examda.com/?login&tpl=mn&u=http%3A//www.examda.com/");
    			httpConn.setRequestProperty("Accept-Language", "zh-cn");
    			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    			httpConn.setRequestProperty("Accept-Encoding","gzip, deflate");
    			httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Foxy/1; .NET CLR 2.0.50727;MEGAUPLOAD 1.0)");
    			httpConn.setRequestProperty("Host", "passport.examda.com");
    			httpConn.setRequestProperty("Content-Length", xmlInfo.length()+ "");
    			
    			OutputStream out = httpConn.getOutputStream();
    			out.write(xmlInfo.getBytes("UTF-8"));
    			out.flush();
    			out.close();
    			
    			input = new InputStreamReader(httpConn.getInputStream(), "UTF-8");
    			bufReader = new BufferedReader(input);
    			String line = "";
    			StringBuilder contentBuf = new StringBuilder();
    			
    			while ((line = bufReader.readLine()) != null) { 
    				contentBuf.append(line);
    			}
    			strResult = contentBuf.toString();
    			
    		} catch (MalformedURLException e) {
    			e.printStackTrace();
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally{
    			if (bufReader!=null){
    				bufReader.close();
    			}
    			if (input != null) {
    				input.close();
    			}
    			if (httpConn != null) {
    				httpConn.disconnect();
    			}
    		}
    		return strResult;
        }
    
    
    }
    

    展开全文
  • /** * @author: 主要是测试数据发送kafka数据 * @date: 2020-08-06 20:20:00 * @description 直接发送JSON发送到kafka的指定队列里面 */ @RestController @RequestMapping(value = "/kafka") public class Kafka...

    1、请求接口数据的接受Controller类对象进行接收处理

    
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.kafka.core.KafkaTemplate;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author:   主要是测试数据发送kafka数据
     * @date:     2020-08-06  20:20:00
     * @description   直接发送JSON发送到kafka的指定队列里面
     */
    
    @RestController
    @RequestMapping(value = "/kafka")
    public class KafkaController {
    
        @Autowired
        KafkaTemplate kafkaTemplate;
    
    
        private static final String NEWS_INFO_TOPIC = "bus_to_platform";
        private static final String COLLECTION_TO_BUS = "collec_to_bus";
    
        @RequestMapping(value = "/newsInfo/test", method = RequestMethod.POST)
    展开全文
  • 但是在前后端分离趋于一种流行趋势,再加上Android和iOS开发技术日渐成熟,大部分团队都会选择在服务器端仅提供一套通用的webservice数据接口,而web页面、Android和iOS统一都通过这套数据接口来向服务器发送请求和...
  • 我们当然可以自己手动解析,但是那样太麻烦,要做字符串截取;如果是用 JSON ,那解析就十分的方便了: 像上图那种就是 json 格式了,键值对,中间用冒号 : 隔开。 像上图那种一看就可以创建一个对象,来接收 json...
  • 实例:A和B两台服务器之间传输log文件或者其他文件, ...1、发送log文件和字符串参数的servlet mport java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.i...
  • 关于前端传空字符串

    万次阅读 2018-10-10 16:27:29
    则可以equals空字符串: 这个地方的确是之前一直忽略了,以后让前端传空,不要传"",get请求拼接url就=就行,后面啥都不写,post请求传js可以直接写成null,浏览器照样会把这个参数解析为空。联...
  • * 从流对象解析出字符串内容 * @param inputStream * @return str */ private String getStrContent(ServletInputStream inputStream) { if (inputStream == null) { return ""; } String str = ...
  • 防止sql注入,输入字符串过滤

    千次阅读 2020-10-16 16:37:24
    import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import ...
  • 接收字符串 两种格式 get, post需要设置发送参数 public static void interfaceUtil(String path,String data) { try { URL url = new URL(path); //打开和url之间的连接 HttpURLConnection con...
  • response输出字符串和输出对象

    千次阅读 2019-11-27 17:17:30
    1、创建测试类(ResController.java) ... import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.Map;...import javax.servlet.http.HttpS...
  • Servlet 表单数据

    2021-01-03 05:38:32
    Servlet 表单数据 ...GET 方法是默认的从浏览器向 Web 服务器传递信息的方法,它会产生一个很长的字符串,出现在浏览器的地址栏中。如果您要向服务器传递的是密码或其他的敏感信息,请不要使用 GET 方法。GET
  • //Java对象转换成JSON字符串 response . getWriter ( ) . write ( JSONObject . toJSONString ( user ) ) ; } } JSP代码 < % @ page language = "java" contentType = "text/html; charset=utf-8" ...
  • Servlet解析JSON数据和发送JSON数据

    万次阅读 多人点赞 2017-03-16 13:11:12
    package com.qst.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;...import javax.servlet.http.HttpServletRe
  • servlet向jsp传值的两种方式

    千次阅读 2022-03-09 09:19:35
    servlet:。。。。。。。。。。。 response.setContentType("text/html;charset=utf-8"); if (Jsjgly == null){ //如果=null说明用户输入的信息在数据库匹配不成功 //通过请求作用域对象HttpServletRequest接口...
  • FreeMarker教程---Freemarker操作字符串

    千次阅读 2014-09-24 11:22:02
     scalars保存的值有两种类型:字符串(用引号括起,可以是单引号或双引号)和数字(不要用引号将数字括起,这会作为字符串处理)  对scalars的访问从root开始,各部分用“.”分隔,如animals.mouse.price ...
  • ajax中json对象和json字符串使用区分

    千次阅读 2019-08-06 08:28:42
    如果是对象的话用JSON.stringify(data)转换成json字符串,反之用JSON.parse()转换成对象。 post与get post提交的是json对象 非字符串时 contentType 不要设为json 如果是get,则contentType设为json get...
  • JSON就是一种数据交换格式,JSON在与JS进行数据交互的时候,可以简单的将JSON理解为字符串,将JS对象转换为JSON字符串,方便数据传输,在要使用JS对象的时候再将JSON字符串转换成JS对象 2、JSON对象和JS对象的关系...
  • jsp中发送Ajax请求及Servlet中响应

    千次阅读 2021-06-14 18:02:36
    jsp页面发送Ajax请求,和html中其实一样,jsp代码如下: <%-- Created by IntelliJ IDEA. User: 17605 Date: 2021/6/6 Time: 19:10 To change this template use File | Settings | File Templates. --%>...
  • 实现将在服务器获取客户端传来的JSON字符串,并把JSON字符串转成JSON对象并取得其中属性值 方式1:解析JSON字符串使用json.jar来实现,需要新增jar如下 首先在web中配置spring 编码过滤器,防止乱码 &lt;...
  • Java字符编码设置总结

    千次阅读 2021-02-13 00:04:59
    1、eclipse workspace中的字符编码:windows->Preferences->general->Workspace以后新建立工程其属性对话框中的Text file encoding即为UTF-8,这个也是安装完Eclipse之后应该立刻做的第一件事,但是这种...
  •  (1) 把java对象列表转换为json对象数组,并转为字符串  JSONArray array = JSONArray.fromObject(list);  String jsonstr = array.toString();    (2) 把java对象转换成json对象,并转化为字符串  ...
  • Servlet-----HttpServletResponse类(响应字符数据、响应字节数据以及重定向)的介绍、代码实现
  • JavaWeb——Servlet Tomcat工作机制动画演示(点击动图可全屏观看) 什么是Servlet Servlet(Server Applet),全称Java Servlet,未有中文译文。是用Java编写的服务器端程序。其主要功能在于交互...
  • 其实 JSP/Servlet 的中文encoding 并没有想像的那么复杂,虽然定位和解决问题没有定规,各种运行环境也各不尽然,但后面的原理是一样的。了解字符集的知识是解决字符问题的基础。不过,随着中文字符集的变化,不仅仅...
  • Servlet基础详解

    万次阅读 多人点赞 2022-02-14 17:02:51
    Servlet的基本概念及使用规范
  • 文章目录Writing Service MethodsConstructing Responses实践环境新建项目服务器响应字符串数据流测试服务器响应 JSON 数据流测试服务器响应图片流测试服务器响应 PDF 文件流测试参考 Writing Service Methods ...
  • ServletServlet 详解(使用+原理)

    千次阅读 多人点赞 2022-04-21 16:31:50
    Servlet 介绍1.1 什么是 Servlet1.2 Servlet 的主要工作2. Servlet 程序创建步骤2.1 创建项目2.2 引入依赖2.3 创建目录2.4 编写代码2.5 打包程序2.6 部署程序2.7 验证程序3. 使用 Smart Tomcat 进行部署3.1 安装 ...
  • } } StudentListServlet 将查询到的数据发送给jsp显示在页面上 package com.wy.web; import com.wy.pojo.Student; import com.wy.util.JdbcUtil; import javax.servlet.ServletException; import javax.servlet....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 86,750
精华内容 34,700
关键字:

servlet发送字符串