servlet 案例

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求  并解析
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("返回陈宫了");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String[] like = request.getParameterValues("like");
        System.out.println("用户名是"+username);
        System.out.println("密码是"+password);
        System.out.println("爱好是"+ Arrays.toString(like));
        // 链接数据库 进行插入数据
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql:///cgbvn2111?characterEncoding=utf8";
            // 获取链接
            Connection conn = DriverManager.getConnection(url, "root", "123");
            String sql = "insert into servlet_user values(null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,Arrays.toString(like));
            ps.executeUpdate();
            ps.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
posted @ 2022-11-13 13:46  竹石2020  阅读(17)  评论(0编辑  收藏  举报