web.xml中Servlet配置如下:
[html]
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.4" 3 xmlns="http://java.sun.com/xml/ns/j2ee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 7 8 9 <servlet> 10 <servlet-name>getDataServlet</servlet-name>; 11 <servlet-class>testTree.TestTree</servlet-class>; 12 </servlet> 13 14 <servlet-mapping> 15 <servlet-name>getDataServlet</servlet-name>; 16 <url-pattern>/getData</url-pattern>; 17 </servlet-mapping> 18 19 </web-app>
JSP页面:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.4" 3 xmlns="http://java.sun.com/xml/ns/j2ee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 7 8 9 <servlet> 10 <servlet-name>getDataServlet</servlet-name>; 11 <servlet-class>testTree.TestTree</servlet-class>; 12 </servlet> 13 14 <servlet-mapping> 15 <servlet-name>getDataServlet</servlet-name>; 16 <url-pattern>/getData</url-pattern>; 17 </servlet-mapping> 18 19 </web-app>
Action代码:
1 [java] view plain copy 2 3 public class TestTree extends HttpServlet { 4 5 @Override 6 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 7 // System.out.println("--------doGet--------"); 8 this.doPost(request, response); 9 } 10 11 @Override 12 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 // System.out.println("--------doPost--------"); 14 String id = request.getParameter("id"); 15 String name = request.getParameter("name"); 16 String level = request.getParameter("level"); 17 String otherParam = request.getParameter("otherParam"); 18 System.out.println(id + "|" + name + "|" + level + "|" + otherParam); 19 20 JSONObject json = new JSONObject(); 21 List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>(); 22 23 for(int i = 0; i < 5; i++){ 24 HashMap<String,Object> hm = new HashMap<String,Object>(); //最外层,父节点 25 hm.put("id", id + i);//id属性 ,数据传递 26 hm.put("name", id + i); //name属性,显示节点名称 27 hm.put("pId", id); 28 29 list.add(hm); 30 } 31 32 JSONArray arr = new JSONArray(list); 33 json.put("success", true); 34 json.put("arr", arr); 35 36 System.out.println("--------json------" + json.toString()); 37 response.getWriter().write(arr.toString()); 38 // response.getWriter().write(json.toString()); 39 // response.getWriter().write("[{pId:‘2‘,name:‘20‘,id:‘20‘}]"); 40 } 41 42 }
时间: 2024-10-11 13:03:39