zoukankan      html  css  js  c++  java
  • Dynemic Web Project中使用servlet的 doGet()方法接收来自浏览器客户端发送的add学生信息形成json字符串输出到浏览器并保存到本地磁盘文件

    package com.swift.servlet;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;

    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;
    import com.swift.student.Student;

    @WebServlet("/add")
    public class AddStudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AddStudentServlet() {
    super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().append("Served at: ").append(request.getContextPath());
    int id=Integer.parseInt(request.getParameter("id"));
    String name=request.getParameter("name");
    int age=Integer.parseInt(request.getParameter("age"));
    Student st=new Student(id,name,age);
    Gson gson=new Gson();
    String json=gson.toJson(st);
    response.getWriter().append(json);
    FileOutputStream fos=new FileOutputStream("d:/1.json");//这里文件名的路径斜杠同注释的斜杠,Java之外的都用这个/
    OutputStreamWriter osw=new OutputStreamWriter(fos);//这个输出也可以了,能够输出字符串了
    osw.write(json);
    osw.flush();
    osw.close();
    // PrintWriter pw=new PrintWriter(osw);//包装类,得到更强的输出功能
    // pw.write(json);
    // pw.println();
    // pw.write(""");
    // pw.flush();
    // pw.close();

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }

    }

  • 相关阅读:
    JustOj 1936: 小明A+B
    Codeforce 835B
    Codeforce 835A
    Java读取Properties工具类
    IDEA2019 断点调试
    Pagination+AngularJS实现前端的分页
    PageHelper实现分页
    100多个免费API接口分享 调用完全不限次数,以后总用得着
    HDU 5763 Another Meaning KMP+DP
    Codeforces Round #365 (Div. 2) D. Mishka and Interesting sum 离线+线段树
  • 原文地址:https://www.cnblogs.com/qingyundian/p/7481800.html
Copyright © 2011-2022 走看看