精华内容
下载资源
问答
  • 我正在尝试读取jQuery发送的数据,因此可以在servlet中使用它jQuery的var test = [{pv: 1000, bv: 2000, mp: 3000, cp: 5000},{pv: 2500, bv: 3500, mp: 2000, cp: 4444}];$.ajax({type: 'post',url: 'ma...

    我是java的新手,我为这个问题苦苦挣扎了2天,最后决定在这里提问。

    我正在尝试读取jQuery发送的数据,因此可以在servlet中使用它

    jQuery的

    var test = [

    {pv: 1000, bv: 2000, mp: 3000, cp: 5000},

    {pv: 2500, bv: 3500, mp: 2000, cp: 4444}

    ];

    $.ajax({

    type: 'post',

    url: 'masterpaket',

    dataType: 'JSON',

    data: 'loadProds=1&'+test, //NB: request.getParameter("loadProds") only return 1, i need to read value of var test

    success: function(data) {

    },

    error: function(data) {

    alert('fail');

    }

    });

    Servlet

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    if (request.getParameter("loadProds") != null) {

    //how do i can get the value of pv, bv, mp ,cp

    }

    }

    我非常感谢您可以提供的任何帮助。

    展开全文
  • Java EE form表单发送JsonServlet接收Json并发送Json 1.需要的jar包 commons-beanutils-1.8.3.jar commons-collections-3.2.1-1.0.0.jar commons-lang-2.5.jar commons-logging-1.1.1.jar ezmorph-1.0.6.jar ...

    Java EE form表单发送Json、Servlet接收Json并发送Json


    1.需要的jar包


    commons-beanutils-1.8.3.jar
    commons-collections-3.2.1-1.0.0.jar
    commons-lang-2.5.jar
    commons-logging-1.1.1.jar
    ezmorph-1.0.6.jar
    json-lib-2.4-jdk15.jar

    2.ajax使form传送json


    <form onsubmit="return false" action="#" method="post" id="form1">
    	<input type="text" name="name1">
    	<input type="text" name="name2"><br/>
    	
    	<input type="radio" value="" name="gender">
    	<input type="radio" value="" name="gender"><br/>
    	
    	<input type="checkbox" value="0" name="game0">game0
    	<input type="checkbox" value="1" name="game0">game1
    	<input type="checkbox" value="2" name="game0">game2<br/>
    	
    
        <input type="button" value="submit" onclick="login()">
    </form>
    
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript">
        function login() {
        	console.log("123")
            $.ajax({
            //几个参数需要注意一下
                type: "POST",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/24-request/JsonServlet" ,//url
                contentType:"application/json",	
                data:JSON.stringify($('form').serializeObject()),
                success: function (result) {
                    console.log(result);//打印服务端返回的数据(调试用)
                    if (result.resultCode == 200) {
                        alert("SUCCESS");
                    }
                    ;
                },
                error : function() {
                    alert("异常!");
                }
            });
        }
        $.fn.serializeObject = function() {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [ o[this.name] ];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    </script>
    

    3.Servlet接收Json、发送Json


    此部分参考博客

    package com.closer.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import javax.servlet.http.HttpServletRequest;
    import net.sf.json.JSONObject;
     
    public class JsonReader {
    	public static JSONObject receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
     
    		// 读取请求内容
    		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
    		String line = null;
    		StringBuilder sb = new StringBuilder();
    		while ((line = br.readLine()) != null) {
    			sb.append(line);
    		}
    		//将json字符串转换为json对象
    		JSONObject json=JSONObject.fromObject(sb.toString());
    		return json;
    	}
    }
    
    

    事先创建好User类,用于将传过来的Json赋值给User类对象

    package com.closer.request;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.closer.util.JsonReader;
    
    import net.sf.json.JSONObject;
    
    @WebServlet("/JsonServlet")
    public class JsonServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        public JsonServlet() {
            super();
        }
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		response.getWriter().append("Served at: ").append(request.getContextPath());
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		response.setContentType("application/json;charset=utf-8");
    		 
    		/** 设置响应头允许ajax跨域访问 **/
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		/* 星号表示所有的异域请求都可以接受, */
    		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    		System.out.println(response.toString());
    		JSONObject json=JsonReader.receivePost(request);
    		System.out.println(json);
    		
    		User user = (User)JSONObject.toBean(json, User.class);
    		System.out.println(user.toString());
    		
    		JSONObject jsonObject=new JSONObject();
    		response.setStatus(200);
    		jsonObject.put("user", JSONObject.fromObject(user));
    		jsonObject.put("message", "用户登录成功!");
    		response.getWriter().write(jsonObject.toString());
    		response.getWriter().flush();
    	}
    
    }
    
    

    # 参考

    1. Servlet解析JSON数据和发送JSON数据
    2. form表单提交json格式数据
    3. Ajax提交表单数据的几种方式
    展开全文
  • Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
  • servlet 接收json数据并响应

    千次阅读 2018-07-28 11:11:16
    客户端发送json数据给servlet服务端 /*HttpClient.java*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io....

    客户端发送json数据给servlet服务端

    /*HttpClient.java*/
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import net.sf.json.JSONObject;
    public class HttpClient {
    	public HttpClient(){
    	}
        public static String doPost(String httpUrl, String param) {
            HttpURLConnection connection = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedReader br = null;
            String result = null;
            try {
                URL url = new URL(httpUrl);
                // 通过远程url连接对象打开连接
                connection = (HttpURLConnection) url.openConnection();
                // 设置连接请求方式
                connection.setRequestMethod("POST");
                // 设置连接主机服务器超时时间:15000毫秒
                connection.setConnectTimeout(15000);
                // 设置读取主机服务器返回数据超时时间:60000毫秒
                connection.setReadTimeout(60000);
                // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
                connection.setDoOutput(true);
                // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
                connection.setDoInput(true);
                // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
                connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // 通过连接对象获取一个输出流
                os = connection.getOutputStream();
                // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
                os.write(param.getBytes());
                // 通过连接对象获取一个输入流,向远程读取
                if (connection.getResponseCode() == 200) {
    
                    is = connection.getInputStream();
                    // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    // 循环遍历一行一行读取数据
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("\r\n");
                    }
                    result = sbf.toString();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 断开与远程地址url的连接
                connection.disconnect();
            }
            return result;
        }
        public static String test(String url){
        	String result=null;
        	JSONObject json = new JSONObject();
        	json.put("comm", "comm");
        	json.put("stu", "stu");
        	System.out.println("请求的json数据:\n"+json.toString());
        	result=HttpClient.doPost(url, json.toString());
    		System.out.println("响应返回的json数据:\n"+result);
            return result;
        } 
    }
    
    
    
    

    服务端接收请求并相应回去

    /*HttpServer.java*/
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import data.ResponseData;
    import data.Student;
    import net.sf.json.JSONObject;
    import service.Service;
    import service.ServiceImpl;
    @WebServlet("/HttpServer")
    public class HttpServer extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        public HttpServer() {
            super();
        }
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doPost(request, response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		response.setHeader("content-type","text/html;charset=UTF-8");
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		/* 星号表示所有的异域请求都可以接受, */
    		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    		PrintWriter out=response.getWriter();
    		// 读取请求内容
    		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
    		String line = null;
    		StringBuilder sb = new StringBuilder();
    		while ((line = br.readLine()) != null) {
    			sb.append(line);
    		}
    		//将json字符串转换为json对象
    		JSONObject json=JSONObject.fromObject(sb.toString());
    		//将数据转化为java对象,注:之前客户端是封装了两个数据(stu,comm),所以处理时
            //需要对其转换
    		Student stu=(Student) JSONObject.toBean((JSONObject) json.get("stu"), Student.class);
    		System.out.println(stu.toString());
    		Comm comm=(Comm) JSONObject.toBean((JSONObject) json.get("comm"), Comm.class);
    		
    		//数据处理,数据库连接方面,用来响应消息
    		Service service=new ServiceImpl();
    		ResponseData responseData=service.getStuInfo(stu);
    		//ResponseData responseData=Data.getStuInfo(stu);
    		
    	    JSONObject newJson=new JSONObject();
    	    newJson.put("comm", json.get("comm"));
    	    newJson.put("data", responseData);
    	    out.write(newJson.toString());
    	    System.out.println(newJson.toString());
    	}
    }
    
    
    
    

    展开全文
  • //当cursor读取到最后一条record的时候 if(resultSet.getRow() == allCount) { //打印剩余的空白cell //for(int k = j;k ;k++) { // strTable.append("<tr>"); // for (int i = 1;i ();i++) { // strTable....

    前端

    $("#btn").on("click",function(){  
        sqlStatement = document.getElementById("sqlStatement").value;
        $.ajax({
            type: "GET",
            url : "DemoServlet",
            dataType:"text",
            async: false,
            data:{sql: sqlStatement, pCount:pageCount},
            success: function(resultData){
                jObject = JSON.parse(resultData);
                document.getElementById("result").innerHTML = jObject.table;
            },
            error:function(xhr, status, errMsg){
                alert("Data transmission failed!");
            }
        });
    });

    后台:返回有个table给前台

    import java.io.IOException;
    import java.io.PrintWriter;
    
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.sql.Connection;
    import java.sql.ResultSet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONObject;
    
    @SuppressWarnings("serial")
    public class DemoServlet extends HttpServlet{
        public static int EACHPAGENUM = 20;
        public String sql = null;
        public String newSQL = null;
        public String pageCount = null;
        public Connection connection = null;  
        public Statement statement = null;  
        public ResultSet resultSet = null;
        public ConnectDB2 connectDB2 = null;
        public PrintWriter out = null;
        public StringBuffer strTable = null;;
        public JSONObject jObject = null;
        public int pageNum = 0;
        public int allCount = 0;
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            response.setHeader("Access-Control-Allow-Origin", "*");
            
            // Get SQL form ajax
            sql = request.getParameter("sql");
            newSQL = sql.replace("\"", "'");
            pageCount = request.getParameter("pCount");
            System.out.println("pCount = " + pageCount);
            System.out.println(newSQL);
            
            //Set up connection to DB2
            connectDB2 = new ConnectDB2();  
            connection = connectDB2.getConnection();
            PrintWriter out = response.getWriter();
             
            try {
                statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                resultSet = statement.executeQuery(newSQL);
                
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                
                //Get col name
                //out.println("<table border='1' width='100%'><tr>");
                strTable = new StringBuffer();
                strTable.append("<table border='1' width='100%' height='240px'><tr>");
                for (int i = 1;i <= resultSetMetaData.getColumnCount();i++) {
                //    out.println("<th>" + resultSetMetaData.getColumnName(i) + "</th>");
                    strTable.append( "<th>" + resultSetMetaData.getColumnName(i) + "</th>");
                }
                strTable.append("</tr>");
                //System.out.println("strTable = " + strTable);
                
                pageNum = 0;
                resultSet.last();
                allCount = resultSet.getRow();
                if(resultSet.getRow() % 20 == 0) {
                    pageNum = resultSet.getRow() / 20;
                }else {
                    pageNum = resultSet.getRow() / 20 + 1;
                }
            
                System.out.println("pageNum = " + pageNum);
                if(Integer.parseInt(pageCount) <= pageNum) {
                    resultSet.absolute(EACHPAGENUM * (Integer.parseInt(pageCount)-1) + 1);
                    for(int j = 0;j < 20;j++){      
                        strTable.append("<tr>");
                        for (int i = 1;i <= resultSetMetaData.getColumnCount();i++) {    
                            //    out.println("<td>" + resultSet.getString(i) + "</td>");
                            strTable.append("<td>" + resultSet.getString(i) + "</td>");                        
                        }
                        strTable.append("</tr>");                    
                        //当cursor读取到最后一条record的时候
                        if(resultSet.getRow() == allCount) {
                            //打印剩余的空白cell
                            //for(int k = j;k < 20 - j;k++) {
                            //    strTable.append("<tr>");
                            //    for (int i = 1;i <= resultSetMetaData.getColumnCount();i++) {
                            //        strTable.append("<td></td>");
                            //    }
                            //    strTable.append("<tr>");
                            //}
                            break; //跳出循环20次的这层循环
                        }
                        resultSet.next();
                    }
                }
                strTable.append("</table>");
                System.out.println(strTable); 
                
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println(e);
            }
     
            jObject = new JSONObject();
            jObject.put("table", strTable.toString());
            jObject.put("pageNum", pageNum);
            out.write(jObject.toString());
            out.flush();
            out.close();
        }
    }
    
    


    展开全文
  • 新建一个servlet,使用doPost()方法,在其中手动写一个json字符串,并将传输文件类型设置为json,传输字符编码设置为utf-8,将浏览器解析方式设置为utf-8 protected void doPost ( HttpServletRequest ...
  • 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
  • 用Ext写一个登陆界面,登陆完后进入一个...用Servlet发送请求,Json数据也是JS通过Servlet请求从数据库中读取显示在Grid表格中。例子比较简单,但方法很明朗。 代码没有经过处理,可能有些乱,但思路还是比较清晰的。
  • jqurey_servlet_json流程

    2016-03-12 09:53:08
    公司需求需要web前端,我很荣幸的从...charset=utf-8'否则请求的数据会按map(键值对)的形式在请求头中,而这样的方法将数据放在了request的payload的地方,并且是全json的形式,在servlet中需要用流的形式进行读
  • 一、Spring JDBC 读取数据库示例 Spring JDBC 示例 想要理解带有 jdbc 模板类的 Spring JDBC 框架的相关概念,让我们编写一个简单的示例,来实现下述 Student 表的所有 CRUD 操作。 CREATE TABLE Student ( ...
  • 前些时候做学校的实践周项目,因为功能比较简单,没有采用框架直接用Servlet实现。过程中遇到了一些问题,其中就出现了Json字符串传输问题。 1、request.getParameter()方法问题 刚开始前端通过get请求传输数据,...
  • 前后端对接后端部分。post方式接受前端传递的json数据,在postman亲测可用,未完待续!如有错误尽请指正!
  • 由于两个使用的包不一样,安卓中使用JSON和服务器中使用JSON,用法不一样 服务器端: student.java中必须要使用getXxx方法和setXXX方法,必须要重写toString,而且是规定的格式 public class Student { ...
  • 经过几天的研究实现定时读取数据库报警信息,报警,请大家参考。

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 27,287
精华内容 10,914
关键字:

servlet读取json