效果图如下:
package test;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class fucktest extends HttpServlet {/*** Constructor of the object.*/public fucktest() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");//输出的为文本格式response.setCharacterEncoding("UTF-8");//中文乱码解决//json字符串String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子肥乃哦\"}";PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println(" <HEAD><TITLE>A Servlet Hello world</TITLE></HEAD>");out.println(" <BODY>");out.print(" This is ");out.print(this.getClass());out.println(", using the GET method");out.print("<br/>");//换行显示out.println("<br/>以下是json的测试数据<br/>");out.println(jsonStr);//此处打印json字符串out.println(" </BODY>");out.println("</HTML>");out.flush();out.close();}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");//response.setContentType("application/json; charset=utf-8");response.setCharacterEncoding("UTF-8");String jsonStr = "{\"name\":\"fly\",\"type\":\"虫子\"}";PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println(" <BODY>");out.print(" This is ");out.print(this.getClass());out.println(", using the POST method测试数据");out.println("\r\n");out.println("以下是json的测试数据");out.println(jsonStr);out.println(" </BODY>");out.println("</HTML>");out.flush();out.close();}/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here}}