2020-12-05王娟

--------"register.,jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="doregister.jsp" method="post">
                      用户名:<input type="text" name="username"/>
                        密码:<input type="password" name="password"/>
                        性别:<input type="radio" name="gender" value="男"/>男
             <input type="radio" name="gender" value="女"/>女
         <input type="submit" value="注册"/>
    </form>
</body>
</html>

<%@page import="com.itlaobing.dbhelper.DBHelper"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   //设置字符编码
   request.setCharacterEncoding("UTF-8"); 
   response.setCharacterEncoding("UTF-8");
   //获取表单数据
   String username = request.getParameter("username");
   String password = request.getParameter("password");
   String gender = request.getParameter("gender");
 ---------  doregister.jsp
   //调用添加的方法
   DBHelper helper = new DBHelper();
   int i =  helper.save(username, password, gender);
   //处理返回结果
   if(i > 0){
       request.getSession().setAttribute("msg", "注册成功");
       response.sendRedirect("register.,jsp");
   }else{
       
   }

%>
------ DBHelper
package com.itlaobing.dbhelper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DBHelper {
    /*定义方法*/
    public int save(String username,String password,String gender) throws Exception{ 
        //1.加载数据库的驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.创建数据库连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_user","root","");
        //3.拼写sql语句
        String sql ="INSERT INTO t_user (userName,`passWord`,gender)VALUES(?,?,?)";
        //4.发送sql
        PreparedStatement prepareStatement = connection.prepareStatement(sql);
        //给占位符赋值
        prepareStatement.setObject(1, username);
        prepareStatement.setObject(2, password);
        prepareStatement.setObject(3, gender);
        //5.执行sql
        int i = prepareStatement.executeUpdate();
        //7.关闭资源
        prepareStatement.close();
        connection.close();
        //返回结果
        return i;
    }
}

心得总结:今天老师讲的内容理解起来非常困难,只能在老师的帮助下才可以完成。

标签

评论

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1