package com.hanqi; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class saveuser extends HttpServlet { private static final long serialVersionUID = 1L; public saveuser() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //设置字符集 response.setContentType("text/html; charset=UTF-8"); String strUserid = request.getParameter("userid"); //获取传递过来的参数 String strUsername = request.getParameter("username"); String strPW = request.getParameter("password"); if(strUserid == null||strUserid.trim().length()==0) { //判断获取的参数是否为空 response.getWriter().append("用户ID不能为空"); } else if(strUsername == null||strUsername.trim().length()==0) { response.getWriter().append("用户名称不能为空"); } else { try { Class.forName("oracle.jdbc.driver.OracleDriver"); //注册Oracle String url = "jdbc:oracle:thin:@localhost:1521:orcl"; //设置连接oracle数据库 Connection conn = DriverManager.getConnection(url, "test1204", "1234"); //登录oracle, 连接oracle用户 if(conn!=null) { //操作数据库 String sql = "insert into T_Test (user_id, user_name, password)"+"values(?,?,?)"; //设置oracle语句的命令 //执行语句的类 PreparedStatement ps = conn.prepareStatement(sql); //创建类ps, 并下达执行命令 strUsername = new String(strUsername.getBytes("iso-8859-1"),"utf-8"); //转码 ps.setString(1, strUserid); //设置写入oracle表中的值 ps.setString(2, strUsername); ps.setString(3, strPW); int row = ps.executeUpdate(); //执行语句的命令并返回数据行数 if(row>0) { response.getWriter().append("保存数据成功, 保存"+row+"条数据成功!"); } else { response.getWriter().append("保存数据失败"); } ps.close(); conn.close(); } else { response.getWriter().append("连接数据库失败"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().append(e.getMessage()); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form id="uform" action="saveuser" method="post"> 用户代码:<input id="userid" type="text" name="userid" width=30 /> <br><br> 用户名称:<input id="username" type="text" name="username" width=30 /> <br><br> 登录密码:<input id="password" type="password" name="password" width=30 /> <br><br> 确认密码:<input id="queren" type="password" name="queren" width=30 /> <br><br> <input type="submit" value="提交" /> </form> </body> </html>