在servlet中输出Json信息

1. 配置Tomcat,检查preferences中的信息是否已经存在

在servlet中输出Json信息_第1张图片

2. 在lib中添加  json-org.jar 这个包

3. 新建一个class文件,定义一个teacher类

package demo001;

public class teacher {
	/**
	 * 
	 */
	int id;
	String name;
	String course;
	
	public teacher(int id, String name, String course)
	{
		this.id = id;
		this.name = name;
		this.course = course;
	}
	
	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 getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}

}

4. 新建一个servlet文件,添加teacher信息并显示出来

package demo001;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;

public class TeacherQuery extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ArrayList teachers = new ArrayList();
		teachers.add(new teacher(2018001,"shao","Language"));
		teachers.add(new teacher(2018002,"wang","English"));
		teachers.add(new teacher(2018003,"gao","Math"));
		JSONArray jarray = new JSONArray(teachers);			
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(jarray.toString());
	}


}

5. 检查Tomcat的server.xml中的信息,是否为对应的目录:

6. 检查web.xml中的servlet的url是否正确,正确则启动tomcat

7. 在浏览器中输入:http://127.0.0.1:8080/demo001/servlet/TeacherQuery  ,可显示:

你可能感兴趣的:(Java)