jsp+jdbc implements a method to connect to a database

  • 2021-01-22 05:17:46
  • OfStack

This article illustrates how jsp+jdbc can connect to a database. Share with you for your reference. The details are as follows:

The first attempt to JSP+jdbc, according to the examples in the book for a long time, is not connected to the database. So on the Internet to find materials, finally found that the old jar package and the new version of the database is directly incompatible. So under the new database jdbc package, tried 1, as expected done. Here, the program to share with you, the program to achieve the web login interface to extract the user name and password, and then the database username password corresponding, so as to decide whether the program through the login.

inc. jsp file:

<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.ResultSetMetaData"%>
String drv = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/demo";
String usr = "nari";
String pwd = "nari";

welcome. jsp file:


login_action. jsp file:

<%@ include file="inc.jsp" %>
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username == null || password == null){
boolean isValid = false;
String sql = "select * from user where username='"+username+"'and password='"+password+"'";
  Connection conn = DriverManager.getConnection(url, usr,pwd);
  Statement stm = conn.createStatement();
  ResultSet rs = stm.executeQuery(sql);
  if(rs.next())isValid = true;
}catch(Exception e){
}else response.sendRedirect("index.jsp");
<% /*
else response.sendRedirect("index.jsp");

index. jsp file:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    <base href="<%=basePath %>"/>
    <title>My JSP 'login.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="description" content="This is my page">
  miThis is my JSP page.<br>
<form name="form1" action="login_action.jsp" method="post">
<table width="200" border="1">
  <td colspan="2"> The login window </td>
  <td> The user name </td>
  <td><input type="text" name="username" size="10"/></td>
  <td> password </td>
  <td><input type ="password" name="password" size="10"/></td>
  <td colspan="2"><input type="submit" name="submit" value=" The login ">
  <a href="register.jsp"> Register a new user </a></td>

The program is published using tomcat and edited and debugged using myeclipse

Hope this article described to everyone jsp program design is helpful.

Related articles: