(017) 자바 백 스테이지 개발 클 라 이언 트 는 HTTP 를 통 해 인터페이스 JSon 데 이 터 를 가 져 옵 니 다.
                                            
 24927 단어  자바 개발 의 길
                    
       ,     javaWeb       。          !     JsonTest  ,    tomcat,           JsonTest   index.jsp  。
단계 1: 새 테스트 용 Model 류 새 뉴스 테스트 류 News 는 주로 데이터 모델 테스트 디 스 플레이, JSon 변환 테스트 등에 사 용 됩 니 다. 코드 는 다음 과 같 습 니 다.
import java.util.Date;  
public class News {  
    private int nId; //   ID  
    private String title; //       
    private String content; //       
    private String date; //         
    private String url; //      
    private Date nDate; //     ,Date    
    public News(int nId, String title, String content, String date, String url) {  
        this.nId = nId;  
        this.title = title;  
        this.content = content;  
        this.date = date;  
        this.url = url;  
    }  
    public News() {  
    }  
    public News(int nId, String title, String content, Date nDate, String url) {  
        this.nId = nId;  
        this.title = title;  
        this.content = content;  
        this.nDate = nDate;  
        this.url = url;  
    }  
    public String getUrl() {  
        return url;  
    }  
    public void setUrl(String url) {  
        this.url = url;  
    }  
    public Date getnDate() {  
        return nDate;  
    }  
    public void setnDate(Date nDate) {  
        this.nDate = nDate;  
    }  
    public int getnId() {  
        return nId;  
    }  
    public void setnId(int nId) {  
        this.nId = nId;  
    }  
    public String getTitle() {  
        return title;  
    }  
    public void setTitle(String title) {  
        this.title = title;  
    }  
    public String getContent() {  
        return content;  
    }  
    public void setContent(String content) {  
        this.content = content;  
    }  
    public String getDate() {  
        return date;  
    }  
    public void setDate(String date) {  
        this.date = date;  
    }  
}  새 페이지 테스트 클래스 NewTotal 은 주로 JSon 페이지 표시 에 사 용 됩 니 다. 코드 는 다음 과 같 습 니 다.
import java.util.List;  
public class NewTotal {  
    private int total; //      
    private List rows; //      
    public NewTotal() {  
    }  
    public NewTotal(int total, List rows) {  
        this.total = total;  
        this.rows = rows;  
    }  
    public int getTotal() {  
        return total;  
    }  
    public void setTotal(int total) {  
        this.total = total;  
    }  
    public List getRows() {  
        return rows;  
    }  
    public void setRows(List rows) {  
        this.rows = rows;  
    }   
}      STEP 2: 테스트 용 Action 과 JSP 인터페이스 에 새 JSonServlet 을 추가 하고 HttpServlet 에서 계승 합 니 다. 구체 적 인 코드 는 코드 에 설명 되 어 있 습 니 다.
Servlet 생 성:http://blog.csdn.net/gaohuanjie/article/details/36377425
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.ArrayList;  
import java.util.List;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import com.google.gson.Gson;  
import com.test.model.NewTotal;  
import com.test.model.News;  
public class JsonServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        //        ,          ,       JDBC          
        News new1 = new News(110, "    ", "       7   ", "2016-5-16 10:22:20",  
                "http://world.huanqiu.com/exclusive/2016-05/8974294.html");  
        News new2 = new News(111, "Apple       ", "         ,       ", "2016-5-16 10:22:20",  
                "http://mobile.163.com/16/0523/09/BNO7SG2B001168BQ.html");  
        News new3 = new News(113, "Google I/O    ", "Google         ,    Android7.0?", "2016-5-16 10:22:20",  
                "http://www.ithome.com/html/android/227647.htm");  
        News new4 = new News(114, "      400 ", "      400 ,          ", "2016-5-16 10:22:20",  
                "http://news.mydrivers.com/1/484/484072.htm");  
        News new5 = new News(115, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new6 = new News(116, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new7 = new News(117, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new8 = new News(118, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new9 = new News(119, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new10 = new News(120, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new11 = new News(121, "     !!!!!!", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new12 = new News(122, "     !!!!!!", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new13 = new News(123, "     !!!!!!", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new14 = new News(124, "     !!!!!!", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new15 = new News(125, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new16 = new News(126, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new17 = new News(127, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new18 = new News(128, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new19 = new News(129, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        News new20 = new News(130, "      400 ", "      400 ,          ", "2016-5-16 10:22:20", "www.baidu.com");  
        String page = req.getParameter("page");  
        //           
        List newslist = new ArrayList();  
        if (page == null || page.equals("0")) {  
            newslist.add(new1);  
            newslist.add(new2);  
            newslist.add(new3);  
            newslist.add(new4);  
            newslist.add(new5);  
            newslist.add(new6);  
            newslist.add(new7);  
            newslist.add(new8);  
            newslist.add(new9);  
            newslist.add(new10);  
        }  
        else {  
            newslist.add(new11);  
            newslist.add(new12);  
            newslist.add(new13);  
            newslist.add(new14);  
            newslist.add(new15);  
            newslist.add(new16);  
            newslist.add(new17);  
            newslist.add(new18);  
            newslist.add(new19);  
            newslist.add(new20);  
        }  
        //              
        NewTotal nt = new NewTotal(newslist.size(), newslist);  
        //   GSON jar       toJson  ,     JSON     
        Gson gson = new Gson();  
        String json = gson.toJson(nt);  
        //        
        System.out.println(json);  
        resp.setContentType("text/plain");  
        resp.setCharacterEncoding("gb2312");  
        PrintWriter out = new PrintWriter(resp.getOutputStream());  
        out.print(json);  
        out.flush();  
        //   Json      JsonTest   
    }  
    @Override  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        this.doGet(req, resp);  
    }  
}    수정 항목 index. jsp 페이지 는 다음 과 같 습 니 다.
"java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
  
<html>  
  <head>  
    <base href="">  
    <title>Test Jsontitle>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8>  
    pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
      
  head>  
  <body>  
     <form action="getJson" method="get">  
        <input type="submit" value="      JSON  "/>  
     form>  
  body>  
html>  프로젝트 에 웹. xml 를 설정 하고 JSonServlet 맵 을 등록 합 니 다. 설정 은 다음 과 같 습 니 다.
  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>JsonTestdisplay-name>  
  <welcome-file-list>  
    <welcome-file>index.jspwelcome-file>  
  welcome-file-list>  
  <servlet>  
      <servlet-name>JsonServletservlet-name>  
      <servlet-class>com.test.json.JsonServletservlet-class>  
  servlet> 
  <servlet-mapping>  
      <servlet-name>JsonServletservlet-name>  
      <url-pattern>/getJsonurl-pattern>  
  servlet-mapping>  
web-app>  STEP 3: Tomcat 용기 에 항목 을 추가 하고 서버 실행 서버 를 실행 하 며 주소 표시 줄 에 주 소 를 입력 합 니 다.http://localhost:8080/JsonTest/getJson?page=0,
⚠️여기 난리 날 수도 있어 요.해결 방법: 웹 페이지 인 코딩 만 전환 하면 됩 니 다. 인 코딩 을 utf - 8 로 설정 합 니 다.클 라 이언 트 인 코딩 은 utf 8 로 설정 되 어 상호작용 과정 에서 인 코딩 이 일치 하도록 합 니 다.오케이!
효과 그림:

간단 한 http 요청 이 되 돌 아 왔 습 니 다!
예 참조:http://blog.csdn.net/jaikydota163/article/details/51458880