`

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

    博客分类:
  • 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>













-
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics