当前位置:网站首页>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 .
边栏推荐
- MariaDB的Galera集群-双主双活安装设置
- 【taichi】用最少的修改将太极的pbf2d(基于位置的流体模拟)改为pbf3d
- 图片懒加载的原理
- Sword finger offer 68 - ii The nearest common ancestor of binary tree
- 壁仞科技研究院前沿技术文章精选
- Google Earth engine (GEE) - globfire daily fire data set based on mcd64a1
- 【js】-【动态规划】-笔记
- ETCD数据库源码分析——处理Entry记录简要流程
- 浅聊一下中间件
- MySQL数据库备份与恢复--mysqldump命令
猜你喜欢
One of the commonly used technical indicators, reading boll Bollinger line indicators
Redis getting started complete tutorial: publish and subscribe
QT drawing network topology diagram (connecting database, recursive function, infinite drawing, dragging nodes)
A mining of edu certificate station
Redis: redis message publishing and subscription (understand)
SHP data making 3dfiles white film
[machine learning] handwritten digit recognition
[Jianzhi offer] 6-10 questions
[OpenGL] note 29 anti aliasing (MSAA)
Google Earth engine (GEE) - globfire daily fire data set based on mcd64a1
随机推荐
P2181 diagonal and p1030 [noip2001 popularization group] arrange in order
Redis入门完整教程:有序集合详解
Is Huatai Securities a nationally recognized securities firm? Is it safe to open an account?
A complete tutorial for getting started with redis: redis shell
JS 3D explosive fragment image switching JS special effect
MariaDB的Galera集群应用场景--数据库多主多活
qt绘制网络拓补图(连接数据库,递归函数,无限绘制,可拖动节点)
【二叉树】节点与其祖先之间的最大差值
debug和release的区别
How to choose a securities company? Is it safe to open an account on your mobile phone
Redis getting started complete tutorial: hash description
vim编辑器知识总结
Redis入门完整教程:GEO
S32 Design Studio for ARM 2.2 快速入门
A complete tutorial for getting started with redis: getting to know redis for the first time
Qt个人学习总结
Insert sort, select sort, bubble sort
PS style JS webpage graffiti board plug-in
LabVIEW中比较两个VI
Redis introduction complete tutorial: Collection details