简单servlet和jdbc回顾

主要写的是doPost方法的
类Servlet.java

package com.sinsoft.service;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * @auther madong
 * @date 2019/5/6-15:28
 */
@javax.servlet.annotation.WebServlet(name = "servlet")
public class Servlet extends javax.servlet.http.HttpServlet {
    private Connection conn = null;

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Writer out = response.getWriter();
        //向服务器发送请求获取到参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        String email = request.getParameter("email");
        String age = request.getParameter("age");
        if (password.equals(password2)) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://localhost:3306/test";
                conn = DriverManager.getConnection(url, "root", "000000");
                String sql = "INSERT INTO tr_user (username,password,email,age) VALUES (?,?,?,?)";
                Statement stmt = conn.createStatement();
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                pstmt.setString(3, email);
                pstmt.setString(4, age);
                pstmt.executeUpdate();
                pstmt.close();
                conn.close();
                response.setHeader("Content-Type", "text/html; charset=UTF-8");
                out.write("用户名:" + username);
                out.write("密码:" + password);
                out.flush();
                out.close();
            } catch (Exception e) {
                System.out.println("数据库连接失败!");
                e.printStackTrace();
            }
        }else {
            response.setHeader("Content-Type", "text/html; charset=UTF-8");
            out.write("两次输入的密码不一致");
        }



    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    }
}

页面index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



  
  登录


登录


用户名: 
密码:       
确认密码:
邮箱:       
年龄:       

web.xml文件配置







  
    Servlet
    com.sinsoft.service.Servlet
  

  
    Servlet
    /
  



你可能感兴趣的:(java)