当前位置:网站首页>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 .
边栏推荐
- Photoshop批量给不同的图片添加不同的编号
- Redis入门完整教程:GEO
- A complete tutorial for getting started with redis: getting to know redis for the first time
- Summary of wechat applet display style knowledge points
- Qt加法计算器(简单案例)
- Redis: redis transactions
- Is Huatai Securities a nationally recognized securities firm? Is it safe to open an account?
- Stm32 Reverse Introduction to CTF Competition Interpretation
- Duplicate ADMAS part name
- debug和release的区别
猜你喜欢

Redis入门完整教程:Pipeline

Redis introduction complete tutorial: Collection details
![[OpenGL] note 29 anti aliasing (MSAA)](/img/66/61f29e1c41d3099d55e2ead0a3b01e.png)
[OpenGL] note 29 anti aliasing (MSAA)

Redis getting started complete tutorial: Geo

A complete tutorial for getting started with redis: hyperloglog

Redis: redis transactions

The difference between debug and release

【图论】拓扑排序

初试为锐捷交换机跨设备型号升级版本(以RG-S2952G-E为例)

Tweenmax emoticon button JS special effect
随机推荐
位运算符讲解
Redis入门完整教程:哈希说明
Ffmpeg quick clip
[machine learning] handwritten digit recognition
A complete tutorial for getting started with redis: getting to know redis for the first time
Network namespace
Google Earth engine (GEE) - globfire daily fire data set based on mcd64a1
Google collab trample pit
【js】-【动态规划】-笔记
The solution to the lack of pcntl extension under MAMP, fatal error: call to undefined function pcntl_ signal()
[Taichi] change pbf2d (position based fluid simulation) of Taiji to pbf3d with minimal modification
Servlet+JDBC+MySQL简单web练习
heatmap. JS picture hotspot heat map plug-in
Complete tutorial for getting started with redis: bitmaps
为什么信息图会帮助你的SEO
该如何去选择证券公司,手机上开户安不安全
ETCD数据库源码分析——处理Entry记录简要流程
Redis: redis message publishing and subscription (understand)
Redis入门完整教程:客户端通信协议
A mining of edu certificate station