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);
    }

    }

  • 相关阅读:
    客户(项目)经理应具备那些基本心理素质
    js 添加数组 删除数组
    c# ifram 刷新父页面
    [转].Net ajax检测用户名是否重复
    js 自动执行方法
    js 层 分页显示选择用户名
    c# Cookie的操作
    c# 取IE地址值
    js 弹出层无刷新分页
    iframe 无边框
  • 原文地址:https://www.cnblogs.com/qingyundian/p/7481800.html
Copyright © 2011-2022 走看看