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();
Note note = new Note();
note.setId("01");
note.setName("java变量");
//将note对象转成json字符串(静态方法)
JSONObject json = JSONObject.fromObject(note);
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.实现的效果