在一个JSP页面中,操作数据库

下面的代码是在一个jsp页面中实现数据库的操作。
也是为了加深对servlet的理解,
这样看来,对servlet还有许多不明之处。

比如:
1、if(userName != null && password != null )所起的作用
2、为什么要对
request.getRequestDispatcher("htmlTest.jsp").forward(request,response);
进行注释?


htmlTest.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>
<%@ page isELIgnored="false" %>
<%
request.setCharacterEncoding("utf-8");

String userName = request.getParameter("userName");
String password = request.getParameter("passWord");

if(userName != null && password != null ){

String sql = "insert into admin (username,pwd) values ('"+ userName +"','"+password +"')";

Connection conn = null;
Statement st = null;

String url = "jdbc:oracle:thin:@loacalhost:1521:orcl";
String user = "admin";
String pwd = "admin";

try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url,user,pwd);
st = conn.createStatement();
st.executeUpdate(sql);

}catch(SQLException e){
e.printStackTrace();
}finally{
if(st!= null){
st.close();
}
if(conn!= null){
conn.close();
}

}

request.setAttribute("Message","insert into :"+userName+" success!");

//此行如不注释掉,数据库中会连续插入170多条记录,
//而且也不返回htmlTest.jsp页面。
//request.getRequestDispatcher("htmlTest.jsp").forward(request,response);
}
%>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>htmlTest.jsp</title>
</head>
<body>
<form method="post" action="/wishingWall/htmlTest.jsp">
用户名:<input id="userName" name="userName" type="text"/><br/>
密码:<input id="passWord" name="passWord" type="passWord"/><br/>
<input type="submit" value="提交"/>

</form>
<p style="color:red;">${requestScope.Message }</p>
</body>

</html>




-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值