当前位置:网站首页>Servlet+JDBC+MySQL简单web练习
Servlet+JDBC+MySQL简单web练习
2022-07-04 22:44:00 【左明水】
Servlet+JDBC+MySQL简单web练习
一、Servlet结构
1〉构造函数constructor
2〉init();初始化——〉将web.xml中有关sql的配置和相关连接语句封装到该函数中。
3〉doGet();doPost();将数据库操作的sql语句封装到该函数。
4〉destory();将相关资源释放,如:关闭数据库语句封装到该函数中。
二、JDBC(oop)+Mysql(db开发)
1〉驱动文件包(*.jar)
2〉Connection与db建立连接.
3〉ResultSet(纪录结果集)
4〉get方法获取字段。
5〉释放资源。
三、从基本框架—-〉到流程思想。
实现一和二的资源整合。
四、步骤。
要求:已经在MySQL中建立school数据库、studentinfo(id,name,age)。
1〉建立一个webproject(web应用名myweb)
2〉在webproject中建立一个package(名为web)
3〉在package中建立一个servlet(名为MyServlet)
4〉完成一的转化(封装)
//初始化函数,连接数据库
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”);
//加载驱动,这一句也可写为:Class.forName(“com.mysql.jdbc.Driver”).newInstance();
//建立到MySQL的连接
conn = DriverManager.getConnection(url,user, pwd);
}catch(Exception ex){
System.out.println(“Error : ” + ex.toString());
}
}
//定义成员变量
Connection conn;
ResultSet rs;
//对数据库的操作
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决中文乱码问题
response.setContentType(“text/html;charset=utf-8”);//使浏览器默认编码为utf-8
//response.setCharacterEncoding(“utf-8”);//也可解决中文乱码
PrintWriter out = response.getWriter();
out.println(“”);
out.println(““);
out.println(” A Servlet“);
out.println(” “);
try{
//执行SQL语句
Statement stmt = conn.createStatement();//创建语句对象,用以执行sql语言
ResultSet rs = stmt.executeQuery(“select * from studentinfo”);
//处理结果集
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(“学生信息表”); out.println(“ | ||
---|---|---|
“);out.println(“学号1”);out.println(“ | “);out.println(“姓名”);out.println(“ | “);out.println(“年龄”);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();
}
//释放资源
public void destroy() {
super.destroy();
try{
rs.close();//关闭数据库
conn.close();
}catch(Exception ex){
System.out.println(“Error : ” + ex.toString());
}
自动生成的包
package web;
修改后导入的包(编程时系统会自动导入包)
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
完整代码如下:
package web;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Myservlet extends HttpServlet {
//定义成员变量
Connection conn;
ResultSet rs;
public Myservlet() {
super();
}
//初始化函数,连接数据库
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");
//加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的连接
conn = DriverManager.getConnection(url,user, pwd);
}catch(Exception ex){
System.out.println("Error : " + ex.toString());
}
}
//对数据库的操作
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决中文乱码问题
response.setContentType("text/html;charset=utf-8");//使浏览器默认编码为utf-8
//response.setCharacterEncoding("utf-8");//也可解决中文乱码
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{
//执行SQL语句
Statement stmt = conn.createStatement();//创建语句对象,用以执行sql语言
ResultSet rs = stmt.executeQuery("select * from studentinfo");
//处理结果集
out.println("<TABLE width=500; border=1; cellspacing=0 >");
out.println("<TR>");
out.println("<TH>");out.println("学生信息表"); out.println("</TH>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>");out.println("学号1");out.println("</TD>");
out.println("<TD>");out.println("姓名");out.println("</TD>");
out.println("<TD>");out.println("年龄");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();
}
//释放资源
public void destroy() {
super.destroy();
try{
rs.close();//关闭数据库
conn.close();
}catch(Exception ex){
System.out.println("Error : " + ex.toString());
}
}
}
6〉BuildPach——〉AddExternalArchives…
导入下载好的数据库连接包(mysql-connector-java.jar)
7〉保存后,将web应用发布到所配置好的tomcat上。
8〉启动tomcat。
9〉在浏览器URL栏输入http://localhost:8080/web应用名/servlet/servlet名
如:http://localhost:8080/myweb/servlet/Myservlet
10〉在浏览器上显示出:学生信息表。
11〉每次调试程序都要重启tomcat和重新发布到tomcat上。
边栏推荐
- Taobao commodity review API interface (item_review get Taobao commodity review API interface), tmall commodity review API interface
- 企业如何跨越数字化鸿沟?尽在云原生2.0
- Sword finger offer 65 Add without adding, subtracting, multiplying, dividing
- 刷题指南-public
- 时间 (计算)总工具类 例子: 今年开始时间和今年结束时间等
- 该如何去选择证券公司,手机上开户安不安全
- Create Ca and issue certificate through go language
- 攻防世界 MISC 进阶区 3-11
- Detailed explanation of heap sort code
- Attack and defense world misc advanced grace-50
猜你喜欢
A complete tutorial for getting started with redis: getting to know redis for the first time
MySQL Architecture - user rights and management
LabVIEW中比较两个VI
Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)
常用技术指标之一文读懂BOLL布林线指标
实战模拟│JWT 登录认证
Redis introduction complete tutorial: detailed explanation of ordered collection
Unity vscode emmylua configuration error resolution
Redis:Redis的事务
【室友用一局王者荣耀的时间学会了用BI报表数据处理】
随机推荐
PS style JS webpage graffiti board plug-in
mamp下缺少pcntl扩展的解决办法,Fatal error: Call to undefined function pcntl_signal()
SPH中的粒子初始排列问题(两张图解决)
Explanation of bitwise operators
【图论】拓扑排序
【ODX Studio編輯PDX】-0.2-如何對比Compare兩個PDX/ODX文件
【机器学习】手写数字识别
Talk about Middleware
C语言快速解决反转链表
Is Huatai Securities a nationally recognized securities firm? Is it safe to open an account?
[graph theory] topological sorting
Serial port data frame
Redis introduction complete tutorial: Collection details
[ODX studio edit PDX] - 0.2-how to compare two pdx/odx files of compare
Redis: redis configuration file related configuration and redis persistence
Editplus-- usage -- shortcut key / configuration / background color / font size
HMS core machine learning service
MySQL Architecture - logical architecture
cout/cerr/clog的区别
A complete tutorial for getting started with redis: getting to know redis for the first time