day63
JSON
Jackson方式
package com.saas.test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.saas.entity.Student; import com.saas.entity.Birth; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TestJacksonJson { public static void main(String[] args) { Student student = new Student(); student.setSid(1); student.setName("张三"); student.setScore(90.5); Birth birth = new Birth(); birth.setYear(1990); birth.setMonth(1); birth.setDay(1); student.setBirth(birth); System.out.println(student); System.out.println("==========================================="); ObjectMapper mapper = new ObjectMapper(); try { String jsonStu = mapper.writeValueAsString(student); System.out.println(jsonStu); System.out.println("==========================================="); Student student2 = mapper.readValue(jsonStu, Student.class); System.out.println(student2); System.out.println("==========================================="); List<Student> list = new ArrayList<>(); list.add(student); list.add(student2); String jsonList = mapper.writeValueAsString(list); System.out.println(jsonList); System.out.println("==========================================="); List<Student> list2 = mapper.readValue(jsonList, mapper.getTypeFactory().constructCollectionType(List.class, Student.class)); System.out.println(list2); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }运行结果如下:
Student{sid=1, name='张三', score=90.5, birth=Birth{year=1990, month=1, day=1}} =========================================== {"sid":1,"name":"张三","score":90.5,"birth":{"year":1990,"month":1,"day":1}} =========================================== Student{sid=1, name='张三', score=90.5, birth=Birth{year=1990, month=1, day=1}} =========================================== [{"sid":1,"name":"张三","score":90.5,"birth":{"year":1990,"month":1,"day":1}},{"sid":1,"name":"张三","score":90.5,"birth":{"year":1990,"month":1,"day":1}}] =========================================== [Student{sid=1, name='张三', score=90.5, birth=Birth{year=1990, month=1, day=1}}, Student{sid=1, name='张三', score=90.5, birth=Birth{year=1990, month=1, day=1}}]
AJAX和JSON综合案例
简介
完成一个访百度的搜索效果,用户键盘输入内容后,下面有联想词语列表,在列表上悬浮有与其他条目不一样的效果样式,离开又恢复到之前的状态,用户点击条目后,让该条目显示在搜索框中,并且将下面的下拉框清空。
静态页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index html</title> <style> #imgDiv { width: 100%; height: 100%; margin-top: 160px; margin-left: 600px; } #par { width: 800px; height: 480px; position: absolute; left: 30%; margin-top: 60px; } #keyword { width: 560px; height: 40px; margin-top: 20px; border: 2px solid green; font-size: 20px; } #search { width: 200px; height: 44px; margin-top: 20px; font-size: 20px; } .tdHover{ background-color: pink; font-size: 22px; } </style> </head> <body> <div id="imgDiv"> <img id="img" src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png" alt=""/> </div> <div id="par"> <input type="text" id="keyword" οnkeyup="getContent()"> <button id="search">百度一下,你就知道</button> <table id="table"> <tbody id="tbody"> <!--<tr> <td>java</td> </tr> <tr> <td>javascript</td> </tr> <tr> <td>jsp</td> </tr> <tr> <td>jstl</td> </tr>--> </tbody> </table> </div> <script> var xhr; function createXHR(){ if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } function getContent() { //alert(123) createXHR(); var keyword = document.getElementById("keyword").value; xhr.open("GET","search?keyword="+keyword,true); xhr.send(); xhr.onreadystatechange = callBack; } function callBack(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var content = xhr.responseText; // eval函数可以将字符串转换为JSON对象 content = eval(content); createTD(content); setListener(content); } } } function setListener(c){ var size = c.length; for (var i = 0; i < size; i++){ var selectTD = document.getElementById("id" + i); selectTD.addEventListener("mouseover", function (){ this.setAttribute("class", "tdHover"); }); selectTD.addEventListener("mouseout", function (){ this.removeAttribute("class"); }); selectTD.addEventListener("click", function (){ var keyword = this.innerText; document.getElementById("keyword").value = keyword; clearTD(); }); } } function createTD(c){ clearTD(); var tbody = document.getElementById("tbody"); for(var i = 0; i < c.length; i++){ var tr = document.createElement("tr"); var td = document.createElement("td"); var node = document.createTextNode(c[i]); td.appendChild(node); td.setAttribute("id","id" + i); tr.appendChild(td); tbody.appendChild(tr); } } function clearTD(){ var tbody = document.getElementById("tbody"); tbody.innerText = ""; } </script> </body> </html>
后台Servlet
package com.saas.servlet; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @WebServlet(urlPatterns = "/search") public class SearchServlet extends HttpServlet { private static List<String> datas = new ArrayList<>(); static { datas.add("java"); datas.add("python"); datas.add("c++"); datas.add("c#"); datas.add("php"); datas.add("javascript"); datas.add("html"); datas.add("css"); datas.add("mysql"); datas.add("sqlserver"); datas.add("mongodb"); datas.add("redis"); datas.add("hadoop"); datas.add("jstl"); datas.add("js"); datas.add("jsp"); datas.add("sql"); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String keyword = req.getParameter("keyword"); if (keyword != null && !keyword.trim().equals("")) { List<String> result = new ArrayList<>(); for (String data : datas) { if (data.contains(keyword)) { result.add(data); } } Collections.sort(result); ObjectMapper om = new ObjectMapper(); String s = om.writeValueAsString(result); resp.getWriter().write(s); } } }