先由表單提交數據到某驗證頁面:checkregister.jsp
<form method="POST"name="form1" action="checkregister.jsp" onsubmit="return check()">
在checkregister.jsp這里可以直接傳給數據庫,我加了一個頁面輸出,為了直觀的觀察數據:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登記驗證</title>
</head>
<body>
<%
/*瀏覽器提交的數據在提交給服務器之前設置編碼方式為UTF-8*/
request.setCharacterEncoding("UTF-8");
out.println("用戶名:"+request.getParameter("User")+"<br>");
out.println("密碼:"+request.getParameter("pwd")+"<br>");
out.println("性別:"+request.getParameter("sexy")+"<br>");
out.println("密保問題:"+request.getParameter("secret")+"<br>");
out.println("密保問題答案:"+request.getParameter("pwd2")+"<br>");
%>
<%
request.setCharacterEncoding("UTF-8");
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=Users";//此處為你的庫名
//Connection conn=null;
Connection conn=null;
String userName="sa";
String pwd="xxxx";//xxxx是你的數據庫登錄密碼
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(dbURL,userName,pwd);
String sql="insert into Users2(username,password,question,answer,gender)values(?,?,?,?,?)";//此處username等是指數據庫里的屬性名
PreparedStatement stmp=conn.prepareStatement(sql);
String username=request.getParameter("User");
String password=request.getParameter("pwd");
String question=request.getParameter("secret");
String answer=request.getParameter("pwd2");
//int gender=Integer.parseInt(request.getParameter("sexy"));
String gender=request.getParameter("sexy");
// 另外,setString中的數字順序對應sql語句參數順序!
stmp.setString(1,username);
stmp.setString(2,password);
stmp.setString(3,question);
stmp.setString(4,answer);
stmp.setString(5,gender);
int n=stmp.executeUpdate();
if(n==1){%>數據插入成功!<br><%}
else{%>數據插入失敗!<br><%}
%>
</body>
</html>
記得加入executeUpdate
