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