当前位置:网站首页>Servlet+jdbc+mysql simple web exercise

Servlet+jdbc+mysql simple web exercise

2022-07-04 23:14:00 Zuo Mingshui

Servlet+JDBC+MySQL Simple web practice

One 、Servlet structure
1〉 Constructors constructor
2〉init(); initialization ——〉 take web.xml In the relevant sql The configuration of and related connection statements are encapsulated in this function .
3〉doGet();doPost(); Operate the database sql Statements are encapsulated into this function .
4〉destory(); Release relevant resources , Such as : The close database statement is encapsulated in this function .

Two 、JDBC(oop)+Mysql(db Development )
1〉 Driver package (*.jar)
2〉Connection And db Establishing a connection .
3〉ResultSet( Record result set )
4〉get Method to get the field .
5〉 Release resources .

3、 ... and 、 From the basic framework —-〉 To process thought .
Realize the resource integration of one and two .

Four 、 step .
requirement : Already in MySQL To establish school database 、studentinfo(id,name,age).
1〉 Build a webproject(web Application name myweb)
2〉 stay webproject Create a package( be known as web)
3〉 stay package Create a servlet( be known as MyServlet)
4〉 Complete the transformation of one ( encapsulation )
// Initialization function , Connect to database
public void init() throws ServletException {
String url=”jdbc:mysql://localhost:3306/school”;
String user=”root”;
String pwd=”root”;
try{
Class.forName(“com.mysql.jdbc.Driver”);
// The load driver , This sentence can also be written as :Class.forName(“com.mysql.jdbc.Driver”).newInstance();
// Set up to MySQL The connection of
conn = DriverManager.getConnection(url,user, pwd);
}catch(Exception ex){
System.out.println(“Error : ” + ex.toString());
}
}

// Define member variables
Connection conn;
ResultSet rs;

// Operation on Database
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Solve the problem of Chinese garbled code
response.setContentType(“text/html;charset=utf-8”);// Make the browser default encoding utf-8
//response.setCharacterEncoding(“utf-8”);// It can also solve Chinese garbled code
PrintWriter out = response.getWriter();
out.println(“”);
out.println(““);
out.println(” A Servlet“);
out.println(” “);
try{
// perform SQL sentence
Statement stmt = conn.createStatement();// Create statement object , To carry out sql Language
ResultSet rs = stmt.executeQuery(“select * from studentinfo”);
// Processing result set
out.println(“

“);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
while (rs.next()){
String id=rs.getString(“id”);
String name=rs.getString(“name”);
String age=rs.getString(“age”);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
out.println(““);
}
out.print(“
“);out.println(“ Student information sheet ”); out.println(“
“);out.println(“ Student number 1”);out.println(““);out.println(“ full name ”);out.println(““);out.println(“ Age ”);out.println(“
“);out.println(id);out.println(““);out.print(name);out.println(““);out.println(age);out.println(“
“);
}catch(Exception ex){
System.out.println(“Error : ” + ex.toString());
}
out.println(” “);
out.println(““);
out.flush();
out.close();
}

// Release resources
public void destroy() {
super.destroy();
try{
rs.close();// Close the database
conn.close();
}catch(Exception ex){
System.out.println(“Error : ” + ex.toString());
}

Automatically generated packages
package web;

Imported package after modification ( When programming, the system will automatically import packages )
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

The complete code is as follows :
package web;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Myservlet extends HttpServlet {

// Define member variables 
Connection conn;
ResultSet rs;

public Myservlet() {
    super();
}

// Initialization function , Connect to database 
public void init() throws ServletException {
    String url="jdbc:mysql://localhost:3306/school";
    String user="root";
    String pwd="root";
    try{
        Class.forName("com.mysql.jdbc.Driver");
        // The load driver , This sentence can also be written as :Class.forName("com.mysql.jdbc.Driver").newInstance();
        // Set up to MySQL The connection of 
        conn = DriverManager.getConnection(url,user, pwd);
        }catch(Exception ex){
          System.out.println("Error : " + ex.toString());
          }
}

// Operation on Database 
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Solve the problem of Chinese garbled code 
    response.setContentType("text/html;charset=utf-8");// Make the browser default encoding utf-8
    //response.setCharacterEncoding("utf-8");// It can also solve Chinese garbled code 
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println("  <BODY>");
    try{
        // perform SQL sentence 
        Statement stmt = conn.createStatement();// Create statement object , To carry out sql Language 
        ResultSet rs = stmt.executeQuery("select * from studentinfo");
        // Processing result set 
        out.println("<TABLE  width=500; border=1; cellspacing=0 >");
        out.println("<TR>");
        out.println("<TH>");out.println(" Student information sheet "); out.println("</TH>");
        out.println("</TR>");
        out.println("<TR>");
        out.println("<TD>");out.println(" Student number 1");out.println("</TD>");
        out.println("<TD>");out.println(" full name ");out.println("</TD>");
        out.println("<TD>");out.println(" Age ");out.println("</TD>");
        out.println("</TR>");
        while (rs.next()){
            String id=rs.getString("id");
            String name=rs.getString("name");
            String age=rs.getString("age");
            out.println("<TR>");
            out.println("<TD>");out.println(id);out.println("</TD>");
            out.println("<TD>");out.print(name);out.println("</TD>");
            out.println("<TD>");out.println(age);out.println("</TD>");
            out.println("</TR>");
            }
        out.print("</TABLE>");
    }catch(Exception ex){
        System.out.println("Error : " + ex.toString());
    }
    out.println("  </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
}

// Release resources 
public void destroy() {
    super.destroy(); 
    try{
        rs.close();// Close the database 
        conn.close();
    }catch(Exception ex){
        System.out.println("Error : " + ex.toString());
    }
}

}

6〉BuildPach——〉AddExternalArchives…
Import the downloaded database connection package (mysql-connector-java.jar)
7〉 After the save , take web The application is published to the configured tomcat On .
8〉 start-up tomcat.
9〉 In the browser. URL Column input http://localhost:8080/web Application name /servlet/servlet name
Such as :http://localhost:8080/myweb/servlet/Myservlet
10〉 Display on the browser : Student information sheet .
11〉 Restart the debugging program every time tomcat And republish to tomcat On .

原网站

版权声明
本文为[Zuo Mingshui]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042244278238.html