使用Servlet根據瀏覽器request的get方法獲取值,將磁碟中與之對應的json數據刪除的方法

来源:http://www.cnblogs.com/qingyundian/archive/2017/09/13/7517683.html
-Advertisement-
Play Games

package com.swift; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja... ...


package com.swift;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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 DeleteServlet
 */
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        File file=new File("d:/student.json");
        //獲取全部學生對象
        List<Student> list=getAllStudent(file);
        System.out.println(list.toString());
        //獲取要刪除學生姓名
        String name=request.getParameter("name");
        System.out.println(name);
        //從list對象列表中刪除匹配姓名的學生對象
        deleteStudentByName(response, list, name);
        System.out.println(list.toString());
        //將刪除後的對象列表寫入磁碟文件
        StringBuffer sb=new StringBuffer();//將剩下的json信息保存到sb中,不然文件中只能得到最後一個json數據
        Gson gson=new Gson();
        for(Student stu:list) {
            String json=gson.toJson(stu);
            sb.append(json);
            sb.append("\r\n");
        }
        writeToFile(file, sb.toString());
    }

    private void deleteStudentByName(HttpServletResponse response, List<Student> list, String name) throws IOException {
        for(int i=0;i<list.size();i++) {
            if(list.get(i).getName().equals(name)) {
                list.remove(i);
                response.getWriter().println("You have already delete the name "+name);
            }
        }
    }

    private void writeToFile(File file,String json) {
        PrintWriter pw = null;
        try {
            try {
                pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            pw.println(json);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            pw.close();
        }
    }
    
    private List<Student> getAllStudent(File file) throws UnsupportedEncodingException, FileNotFoundException, IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"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();
        return list;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 如果想在程式中加入惡意代碼,裝飾器是不錯的選擇! 一來裝飾器函數一般在主程式外定義,不易被髮現; 二來裝飾器函數在主程式運行之前執行,可以在主程式運行之前,獲得系統分配的資源. ...
  • 安裝pdf擴展1. wget http://pecl.php.net/get/pdflib-4.1.2.tgz2. tar zxvf pdflib-4.1.2.tgz3. cd pdflib-4.1.2.tgz4. /opt/lampp/bin/phpize5. ./configure --with ...
  • 官方手冊地址:http://effbot.org/imagingbook/image.htm Image模塊 圖像模塊提供了一個具有相同名稱的類,用於表示一個PIL的圖像。該模塊還提供了許多功能,包括載入圖片文件函數和創建新的圖像函數。 模塊示例: 下麵的程式載入一個圖像,再旋轉45度,並使用一個外 ...
  • 簡單的BBS論壇 實現功能 git倉庫地址: https://github.com/uge3/BBS 1、整體參考“抽屜新熱榜” + “博客園” 2、實現不同論壇版塊 3、帖子列表展示 4、個人博客主頁 5、個人博客標簽、分類、時間 篩選 6、帖子評論數、點贊數展示 7、允許登錄用戶發貼、評論、點贊 ...
  • redis筆記 下載完redis,執行make命令。 然後啟動redis就進src文件夾,執行./redis-server就可以了。 再在文件夾下執行 ./redis-cli 就可以執行redis的命令了。 pipelining 一次請求發送多個命令,以提高性能。我們在使用redis時都是向它發送命 ...
  • 拼接: name=zhuhuan age=23 salary=333 info=''' info of %s age:%s name:%s salary:%s %(name,age,name,salary) ''' info2=''' info of {_name} age:{_age} name: ...
  • JPA基礎及查詢規則 JPA JPA是Java Persistence API的簡稱,中文名Java持久層API,是JDK 5.0註解或XML描述對象-關係表的映射關係,並將運行期的實體對象持久化到資料庫中。 JPA框架中支持大數據集、事務、併發等容器級事務,這使得 JPA 超越了簡單持久化框架的局 ...
  • 1.減少可調用對象的參數個數,使用functools.partial凍結參數 使用functools.partial(),可以固定一個或者多個值,減少調用參數。 2.給函數參數增加元信息 函數聲明中的各個參數可以在 : 之後增加註解表達式。如果參數有預設值,註解放在參數名和 = 號之間。如果想註解返 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...