目录
- package com.example.servletdemo1;
-
- import java.io.*;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
-
- public class HelloServlet extends HttpServlet {
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //获取表单数据
- String username = request.getParameter("username");
- String age = request.getParameter("age");
- String score = request.getParameter("score");
- //采用字符输出流
- BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test\\my\\tj.txt",true));
- bw.write(username+","+age+","+score);
- bw.newLine();
- bw.close();
- //响应客户端浏览器
- PrintWriter pw = response.getWriter();
- pw.println("Save Success");
- pw.close();
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doGet(request,response);
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
- version="4.0">
- <!-- 修改默认主页 -->
- <welcome-file-list>
- <welcome-file>/addStudent.html</welcome-file>
- </welcome-file-list>
- <!-- 配置Servlet -->
- <servlet>
- <servlet-name>studentServlet</servlet-name>
- <servlet-class>com.example.servletdemo1.HelloServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>studentServlet</servlet-name>
- <url-pattern>/cpc</url-pattern>
- </servlet-mapping>
- </web-app>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>保存学生信息</title>
- </head>
- <body>
- <form action="/demo2/cpc" method="get" autocomplete="off">
- 学生姓名:<input type="text" name="username"> <br/>
- 学生年龄:<input type="number" name="age"> <br/>
- 学生成绩:<input type="number" name="score"> <br/>
- <button type="submit">保存</button>
- </form>
- </body>
- </html>