Send ajax request from jsp page, servlet accepts parameters and returns json data

The blogger has been registered with CSDN for a long time and has never written (haha)

I encountered a problem today that stumped me, and after I solved it, I quickly wrote it down

This is a very simple question of updating users

Let's take a look at the jar package required by the project first


The next thing is the jsp page, ajax sends the id

function editCustomer(id) {
			$.ajax({
				type:"get",
				url:"${pageContext.request.contextPath }/editStudioServlet",
				data:{"id":id},
				success:function(data) {
					$("#edit_cust_id").val(${data.cust_id});
					$("#edit_customerName").val(data.cust_name);
					$("#edit_phone").val(data.cust_phone);
					$("#edit_mobile").val(data.cust_mobile);
					alert(data);
					
				}
			});
		}

Then accept the parameters in the servlet and go to the database to query the results

String id = request.getParameter("id");
		//System.out.println(id);
		StudioDao dao = new StudioDaoImpl();
		Customer studio = null;
		try {
			studio = dao.getCustomerById(Integer.parseInt(id));
		} catch (Exception e) {
			e.printStackTrace ();
		}
		Gson gson = new Gson ();
		String json = gson.toJson(studio);
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8");  
		PrintWriter writer = response.getWriter();
		writer.append(json);
Then the Ajax callback function fills in the json data sent from the servlet into the input box to complete.

Last picture


Well, you're done, bloggers will write articles diligently in the future. . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325685006&siteId=291194637