jsp链接数据库代码

`<br data-filtered="filtered">
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

注册页面代码:

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.sql.*"%>
<%!
 public static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
 public static final String userName = "root";   //登录的用户名
 public static final String userPasswd = "taizhen";  //登录mysql密码
 public static final String dbName = "test";  //数据库名
 public static final String tableName="user"; //表名
 public static final String DBURL = "jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd;
%>

<%
  Connection conn = null ;
  PreparedStatement pstmt = null ;
  ResultSet rs = null ;
  boolean flag = false ; // 表示登陆成功或失败的标记
%>

<%

 String action = request.getParameter("action");
if(null==action){
	
}else{
	%>
	 
	  <%out.println(action); %>
	 <% 
	 String name = request.getParameter("username") ; // 接收表单参数
	 String password = request.getParameter("password") ; // 接收表单参数
	try{
		   Class.forName(DBDRIVER) ;
		   conn = DriverManager.getConnection(DBURL) ;
		   String sql = "SELECT name,password FROM user WHERE name=? AND password=?" ;
		   pstmt = conn.prepareStatement(sql) ;
		   pstmt.setString(1,name) ;
		   pstmt.setString(2,password) ;
		   rs = pstmt.executeQuery() ;
		   while(rs.next()){
		    // 如果有内容,则此处执行,表示查询出来,合法用户
		        flag = true ;
		  }
		 }catch(Exception e){
		 }finally{
		  try{
		   conn.close() ; // 连接一关闭,所有的操作都将关闭
		  }catch(Exception e){}
		 }
		%>
		<%out.println(flag); %>
		 <%out.println(action); %>
		<%

		 if(flag){
		 request.getSession().setAttribute("success", "登录");
		%>
		  <jsp:forward page="success.jsp"/>
		<%
		 }else{  // 登陆失败,跳转到failure.jsp
			 request.getSession().setAttribute("error", "登录");
			
		%> 
		 <jsp:forward page="error.jsp"/>  
		<%
		 }
}
 
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    

  </head>
  
  <body>
   <form action="login.jsp" method="post">
			<input type="hidden" name="action" />
			用户名:
			<input type="text" name="username" value="username"/>
			<br>
			密码:
			<input type="password" name="password" value="password"/>
			<br>
			<input type="submit" value="login" />
		</form>

  </body>
</html>

链接数据库代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.sql.*"%>
<%!
 public static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
 public static final String userName = "root";   //登录的用户名
 public static final String userPasswd = "taizhen";  //登录mysql密码
 public static final String dbName = "test";  //数据库名
 public static final String tableName="user"; //表名
 public static final String DBURL = "jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd;
%>

<%
  Connection conn = null ;
  PreparedStatement pstmt = null ;
  ResultSet rs = null ;
  boolean flag = false ; // 表示登陆成功或失败的标记
%>

<%

     String action = request.getParameter("username");
     if(action!=null){

    	 %>
    	 
    	  <%out.println(request.getParameter("password")); %>
    	 <% 
	 String name = request.getParameter("username") ; // 接收表单参数
	 String password = request.getParameter("password") ; // 接收表单参数
	 String linkman=request.getParameter("linkman");
	 String qq=request.getParameter("qq");
	
	try{
		   Class.forName(DBDRIVER) ;
		   conn = DriverManager.getConnection(DBURL) ;
		   String sql = "INSERT INTO user (name, password) VALUES (?,?)";
		   
		   pstmt = conn.prepareStatement(sql) ;
		   pstmt.setString(1,name) ;
		   pstmt.setString(2,password) ;
		  
		   int sql_update = pstmt.executeUpdate();
		  if(sql_update>0){
			  flag=true;
		  }
		 }catch(Exception e){
		 }finally{
		  try{
		   conn.close() ; // 连接一关闭,所有的操作都将关闭
		  }catch(Exception e){}
		 }
		%>
		
	
		<%

		 if(flag){
		 request.getSession().setAttribute("success", "注册");
		%>
		  <jsp:forward page="success.jsp"/>
		<%
		 }else{  // 登陆失败,跳转到failure.jsp
			 request.getSession().setAttribute("error", "注册");
			
		%> 
		 <jsp:forward page="error.jsp"/>  
		<%
		 }

     
     }else{}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 
    
    <title>My JSP 'register.jsp' starting page</title>
    
  </head>
  
  <body>
 
	<div class="loginbox registbox">
		
		<div class="login-content reg-content">
			<div class="loginbox-title">
				<h3>注册</h3>
			</div>
			<form id="signupForm" action="register.jsp" method="post">
			
			<div class="row">
				<label class="field" for="email">用户名</label>
				<input type="text"  class="input-text-user noPic input-click" name="username" id="email">
			</div>
			<div class="row">
				<label class="field" for="password">密码</label>
				<input type="password" value="" class="input-text-password noPic input-click" name="password" id="password">
			</div>
			
			<div class="row">
				<label class="field" for="contact">联系人</label>
				<input type="text" value="" class="input-text-user noPic input-click" name="linkman" id="contact">
			</div>
			<div class="row">
				<label class="field" for="company">公司名</label>
				<input type="text" value="" class="input-text-user noPic input-click" name="company" id="company">
			</div>
			<div class="row">
				<label class="field" for="tel">公司电话</label>
				<input type="text" value="" class="input-text-user noPic input-click" name="companytel" id="tel">
			</div>
			<div class="row">
				<label class="field" for="qq">QQ</label>
				<input type="text" value="" class="input-text-user noPic input-click" name="qq" id="qq">
			</div>
			
			<div class="row btnArea">
				<button class="login-btn" id="submit">注册</button>
			</div>
			</form>
		</div>
		<div class="go-regist">
			已有帐号,请<a href="/Demo/login.jsp" class="link">登录</a>
		</div>
	</div>
  </body>
</html>

登录失败代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'error.jsp' starting page</title>
    
	

  </head>
  
  <body>
    ${sessionScope.error }失败 <br>
  </body>
</html>

登陆成功代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
	
  </head>
  
  <body>
   ${sessionScope.success }成功! <br>
  </body>
</html>

数据库表:
Source Server         : localhost_3306
Source Server Version : 50528
Source Host           : localhost:3306
Source Database       : bbs

Target Server Type    : MYSQL
Target Server Version : 50528
File Encoding         : 65001

Date: 2016-06-04 09:25:01
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `linkman` varchar(255) DEFAULT NULL,
  `company` varchar(255) DEFAULT NULL,
  `companytel` varchar(255) DEFAULT NULL,
  `qq` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'admin', 'admin', null, null, null, null);
INSERT INTO `tb_user` VALUES ('2', 'user', 'user', null, null, null, null);`

转载于:https://my.oschina.net/CarrieLiu/blog/1554512

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 JSP 页面,它展示了如何使用 JSP 和 JDBC 连接到数据库,执行模糊查询,并显示查询结果: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>模糊查询</title> </head> <body> <h1>模糊查询</h1> <% // 设置数据库连接信息 String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "123456"; // 获取查询关键字 String keyword = request.getParameter("keyword"); // 执行查询 Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); pstmt = conn.prepareStatement("SELECT * FROM mytable WHERE name LIKE ?"); pstmt.setString(1, "%" + keyword + "%"); rs = pstmt.executeQuery(); // 显示查询结果 while (rs.next()) { out.println(rs.getString("id") + "<br>"); out.println(rs.getString("name") + "<br>"); out.println(rs.getString("age") + "<br>"); } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } %> <form method="get"> <input type="text" name="keyword"> <input type="submit" value="查询"> </form> </body> </html> ``` 在上面的代码中,我们首先通过 `request.getParameter` 方法获取查询关键字。然后,我们使用 JDBC 连接到数据库,并使用 `PreparedStatement` 执行查询。在查询结果中,我们使用 `out.println` 方法将结果输出到页面上。最后,我们使用一个简单的 HTML 表单来允许用户输入查询关键字。 当用户点击查询按钮时,JSP 页面将重新加载,并显示查询结果。 请注意,这只是一个简单的示例。在实际应用中,您需要更加谨慎地处理用户输入,以避免 SQL 注入等安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值