程序描述:
编程实现某网站用户注册功能,要求编写JSP页面供用户输入注册信息,在接收页面获取用户输入的数据,在浏览器上输出的同时,将信息存放到数据库里。
代码:
注册HTML 页面:
<%@ page contentType="text/html;charset=utf-8" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="inquire"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录页面</title>
</head>
<body>
<p>注册信息</p><br/>
<form name="loginForm" method="post" action="NewRecord.jsp">
<table>
<tr>
<td>姓 名:<input type="text" name="username" id="username"></td>
</tr>
<tr>
<td>密 码:<input type="password" name="password" id="password"></td>
</tr>
<tr>
<td>确定密码:<input type="password" name="passwordq" id="passwordq"></td>
</tr>
<tr>
<td>性 别:<input type="text" name="psex" id="pSex"></td>
</tr>
<tr>
<td>学 历:<input type="text" name="plever" id="pLever"></td>
</tr>
<tr>
<td>注册时间:<input type="text" name="ptime" id="ptime"></td>
</tr>
<tr>
<td><input type="submit" value="注册" style="background-color:pink">
</td>
</tr>
</table>
</form>
</body>
</html>
注册jsp 页面
<%@ page contentType="text/html;charset=utf-8" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="inquire"%>
<HTML><BODY bgcolor=cyan>
<% request.setCharacterEncoding("utf-8");
String na=request.getParameter("username");
String pa=request.getParameter("password");
String paq=request.getParameter("passwordq");
String ts=request.getParameter("psex");
String tl=request.getParameter("plever");
String tt=request.getParameter("ptime");
%>
<%
if(!pa.equals(paq))
{
out.print("你的密码不一致,请重新输入\n");
}
%>
<%
%>
<BR>你的信息为:
<br/>
姓 名:<%=na %><br/>
密 码:<%=pa %><br/>
性 别:<%=ts %><br/>
学 历:<%=tl %><br/>
注册时间:<%=tt %><br/>
<inquire:AddRecord psex="<%=ts %>" password="<%=pa %>" plever="<%=tl %>" ptime="<%=tt %>" username="<%=na %>"></inquire:AddRecord>
<BR>
</BODY></HTML>
tag 文件:
<%@ tag pageEncoding="utf-8" %>
<%@ tag import="java.sql.*" %>
<%@ attribute name="username" required="true" %>
<%@ attribute name="password" required="true" %>
<%@ attribute name="psex" required="true" %>
<%@ attribute name="plever" required="true" %>
<%@ attribute name="ptime" required="true" %>
<%
String condition=
"INSERT INTO product VALUES"+
"("+"'"+username+"','"+password+"','"+psex+"','"+plever+"','"+ptime+"'"+")";
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e) {}
Connection con;
Statement sql;
ResultSet rs;
try{ String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mystar";
con=DriverManager.getConnection(uri,"sa","sa");
sql=con.createStatement();
sql.executeUpdate(condition);
con.close();
}
catch(Exception e)
{ out.print(""+e);
}
%>
注意问题:
【问题一】 汉字乱码
在每个jsp 页面 中加上 request.setCharacterEncoding("utf-8");
【问题二】 tag 连接数据库失败
首先检查要连接的数据库是否 一致(本人 弄乱了数据库 可吃大亏了~~白花花的时间啊)
【问题三】用tag中的 attribute 传参时 有的能传 有的不能传
从网上搜了好几天也没找的答案
当出现问题时 ,我们总是该来该去,别忘了重启tomcat
其次 要注意 attribute 里的命名 ,第一个字母 小写第二个大写 的 通通不行
这点害的我好几天没睡好啊
以此纪念逝去的时间