1.导入json_jar.jar包
2.编写一个实体类Note
public class Note implements Serializable{
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.编写一个servlet
public class LoadNoteServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
List<Note> list = new ArrayList<Note>();
Note note = new Note();
note.setId("01");
note.setName("java变量");
Note note1 = new Note();
note1.setId("02");
note1.setName("ajax应用");
list.add(note);
list.add(note1);
//将note对象集合转成json数组(静态方法)
JSONArray json = JSONArray.fromObject(list);
out.println(json);
String json_str = json.toString();
out.print(json_str);
out.flush();
out.close();
}
}
4.在web.xml中配置servlet
<servlet>
<servlet-name>LoadNoteServlet</servlet-name>
<servlet-class>servlet.LoadNoteServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LoadNoteServlet</servlet-name>
<url-pattern>/load.do</url-pattern>
</servlet-mapping>
5.实现的效果