当前位置:网站首页>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上。
边栏推荐
- The solution to the lack of pcntl extension under MAMP, fatal error: call to undefined function pcntl_ signal()
- P2181 对角线和P1030 [NOIP2001 普及组] 求先序排列
- Redis introduction complete tutorial: Collection details
- 攻防世界 MISC 進階區 Erik-Baleog-and-Olaf
- Set up a website with a sense of ceremony, and post it to 1/2 of the public network through the intranet
- Sword finger offer 68 - I. nearest common ancestor of binary search tree
- Advanced area of attack and defense world misc 3-11
- [try to hack] wide byte injection
- 为什么信息图会帮助你的SEO
- [graph theory] topological sorting
猜你喜欢

Redis入门完整教程:事务与Lua
![[sword finger offer] questions 1-5](/img/54/b70d5290978e842939db99645c6ada.png)
[sword finger offer] questions 1-5

Complete tutorial for getting started with redis: bitmaps

Hit the core in the advanced area of misc in the attack and defense world

Redis入门完整教程:Redis Shell

JS card style countdown days
![P2181 diagonal and p1030 [noip2001 popularization group] arrange in order](/img/79/36c46421bce08284838f68f11cda29.png)
P2181 diagonal and p1030 [noip2001 popularization group] arrange in order

MySQL Architecture - user rights and management

Redis démarrer le tutoriel complet: Pipeline

浅聊一下中间件
随机推荐
Redis入门完整教程:慢查询分析
Feature scaling normalization
Three stage operations in the attack and defense drill of the blue team
Explanation of bitwise operators
Attack and defense world misc advanced area ditf
【二叉树】节点与其祖先之间的最大差值
MySQL Architecture - logical architecture
Attack and defense world misc advanced area can_ has_ stdio?
Redis introduction complete tutorial: detailed explanation of ordered collection
【剑指Offer】6-10题
The overview and definition of clusters can be seen at a glance
【taichi】用最少的修改将太极的pbf2d(基于位置的流体模拟)改为pbf3d
One of the commonly used technical indicators, reading boll Bollinger line indicators
头文件重复定义问题解决“C1014错误“
On-off and on-off of quality system construction
Redis: redis configuration file related configuration and redis persistence
攻防世界 MISC 進階區 Erik-Baleog-and-Olaf
Redis入门完整教程:初识Redis
Unity Xiuxian mobile game | Lua dynamic sliding function (specific implementation of three source codes)
Redis入门完整教程:Redis Shell