tomcat服务器用Servlet类查找磁盘文件上的Json信息,如果匹配则在浏览器上显示出该条内容的全部信息

2017-09-13 20:37:42来源:cnblogs.com作者:Advancing-Swift人点击

分享
package com.swift;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;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 com.google.gson.Gson;/** * Servlet implementation class FindServlet */@WebServlet("/find")public class FindServlet extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public FindServlet() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/student.json"),"utf-8"));        List<Student> list=new ArrayList<Student>();        String str;        while((str=br.readLine())!=null) {            Gson gson=new Gson();            Student stu=gson.fromJson(str, Student.class);            list.add(stu);        }        br.close();        String name=request.getParameter("name");        for(Student stu:list) {            if(stu.getName().equals(name)) {                Gson gson=new Gson();                String json=gson.toJson(stu);                response.getWriter().println(json);            }        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台