当前位置:网站首页>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 .
边栏推荐
- Google Earth engine (GEE) - tasks upgrade enables run all to download all images in task types with one click
- Redis入门完整教程:初识Redis
- heatmap. JS picture hotspot heat map plug-in
- Analysis of the self increasing and self decreasing of C language function parameters
- HMS core unified scanning service
- Photoshop batch adds different numbers to different pictures
- SHP data making 3dfiles white film
- Basic use and upgrade of Android native database
- Advantages of Alibaba cloud international CDN
- Wechat official account solves the cache problem of entering from the customized menu
猜你喜欢

JS 3D explosive fragment image switching JS special effect

A complete tutorial for getting started with redis: redis shell

位运算符讲解

Redis入门完整教程:集合详解

MariaDB的Galera集群-双主双活安装设置

EditPlus--用法--快捷键/配置/背景色/字体大小

Redis introduction complete tutorial: detailed explanation of ordered collection

CTF竞赛题解之stm32逆向入门

The initial arrangement of particles in SPH (solved by two pictures)

Redis入门完整教程:Bitmaps
随机推荐
Google Earth engine (GEE) - globfire daily fire data set based on mcd64a1
Qt加法计算器(简单案例)
Wechat official account solves the cache problem of entering from the customized menu
Talk about Middleware
Redis入门完整教程:Redis Shell
图片懒加载的原理
【图论】拓扑排序
Redis入门完整教程:发布订阅
Redis: redis configuration file related configuration and redis persistence
Servlet服务器端和客户端中文输出乱码问题
Sword finger offer 68 - ii The nearest common ancestor of binary tree
Notepad++ -- editing skills
Servlet+JDBC+MySQL简单web练习
微信公众号解决从自定义菜单进入的缓存问题
字体设计符号组合多功能微信小程序源码
SHP data making 3dfiles white film
Redis:Redis的事务
初试为锐捷交换机跨设备型号升级版本(以RG-S2952G-E为例)
Redis:Redis消息的发布与订阅(了解)
Docker镜像的缓存特性和Dockerfile