Javaweb data into JSON and JSP get and parse JSON via AJAX (code instance)

Source: Internet
Author: User
Tags tomcat server

JSON is a lightweight unified data interchange format, especially suitable for use in JavaScript, JSON data can be easily converted to JS objects, more and more widely used in JS today, to become an excellent web development engineer, it is imperative to learn it, It can indeed provide you with a real convenience.

Here we have a JSP + servlet demo to get a simple look at JSON usage.

SOURCE Download Address

First, preparatory work

Project Structure Chart:


Jar Package Download:

Free DOWNLOAD link

Second, Person class (Model)

There is nothing special about private properties with their get (), set () methods.

public class Person {
	private int id;
	private String name;
	Private String pwd;

	public int getId () {return
		ID;
	}

	public void setId (int id) {
		this.id = ID;
	}

	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}

	Public String getpwd () {return
		pwd;
	}

	public void SetPwd (String pwd) {
		this.pwd = pwd;
	}
}
iii. servlet Class (Controller)
Inherit HttpServlet, rewrite the doget () and Dopost () method, complete the processing of the specific business logic, and then object the data in the database, then package it as JSON;

Of course, this servlet must be registered with the configuration mapping in Web.xml.

public class Json extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) t
	Hrows servletexception, IOException {doPost (request, response); 
		
		public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
		Response.setcontenttype ("Text/xml;character=utf-8");
		Response.setheader ("Cache-control", "No-cache");
			try {//Create the Person object, save the data, if there is a database, where the data should be removed from the database person P = new person ();
			P.setname ("a");
			P.setid (1);
			P.setpwd ("123456");
			person P1 = new person ();
			P1.setname ("second");
			P1.setid (2);
			P1.setpwd ("666888");
			Load the person object into the collection list<person> List = new arraylist<person> ();
			List.add (P);
			List.add (p1);
				try {///Create the Jsonarray object, Jsonarray is a [] wrapped array (array), where the method is called to load the collection of objects into jsonarray JSON = jsonarray.fromobject (list); Jsonobject is a {} wrapped object (object) where you want to manipulate objects, so create Jsonobject objects jsonobject JB = new Jsonobject ();
				Load the Jsonarray object into the Jb.put ("person", JSON);
				
				Output JSON data, which is a special form of string Response.getwriter (). Write (jb.tostring ());
				 /* Here you can load the data into JSON in another way, except that the foreground accepts the Jsonarray object, which is a [] wrapped array of arrays (array) *jsonarray Jsonarray = new Jsonarray ();
				 *jsonobject JB = new Jsonobject ();
				 *jb.put ("person", JSON);
				 *jsonarray.add (JB);
				 *response.getwriter (). Write (jsonarray.tostring ());
			*/} catch (IOException e) {e.printstacktrace ();
		} catch (Exception e) {e.printstacktrace (); }
	}
}
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version=
"2.5" xmlns= "http://java.sun.com/xml/ns/" 
	Java ee " 
	xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " 
	xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
  <display-name></ display-name>	
  
  <servlet>
  	<servlet-name>Json</servlet-name>
  	<servlet-class >com.jsonTest.servlet.Json</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>Json</servlet-name>
  	<url-pattern>/json</url-pattern>
  </ servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
Four, JSP (View)

Receive background JSON data sent through the server, and then parse JSON using the Eval method of JS to convert the data into a JS object.

For Ajax and server-side communication, see another blog ajax initial knowledge and XMLHttpRequest introduction.

For Eval parsing JSON, see another blog eval parsing the JSON note point.

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <% String Path = Request.getcontextpath ()
	; String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/"
; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  
v. Effect of implementation 

Start Tomcat server, access the project through the browser URL, http://localhost:8080/jsonTest/, you can see the following effect



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.