静态web资源(如html 页面):指web页面中供人们浏览的数据始终是不变。
动态web资源:指web页面中供人们浏览的数据是由程序产生的,不同时间点访问web页面看到的内容各不相同。
静态web资源开发技术:HTML、CSS、JavaScript。
动态web资源开发技术:JSP/Servlet、ASP、PHP等。在Java中,动态web资源开发技术统称为Java Web。

ASP:微软,国内最早流行的是ASP,在HTML中嵌入了VB的脚本,ASP+COM,维护成本高。
PHP:开发速度很快,功能很强大,跨平台,代码简单,但是无法承载大访问量的情况(局限性)。
JSP/Servlet:sun公司主推的B/S架构,基于java语言,可以承载三高问题(高并发,高可用,高性能)。
B/S:浏览器和服务器;C/S:客户端和服务器。
服务器用来处理用户的一些请求,响应给用户一些数据。
IIS:微软的,主要用于ASP,Windows中自带的服务器。
**Tomcat:**Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个JavWeb初学者来说,是最好的选择。
Tomcat 实际上运行JSP 页面和Servlet。
安装Tomcat:官网下载(tomcat.apache.org/)压缩包,解压至指定目…
在bin目录下点击startup.bat启动,在浏览器网址栏输入localhost:8080测试。
网站是如何进行访问的:
Http(超文本传输协议):http是一个简单的请求-响应协议,它通常运行在TCP之上。(默认端口:80)
Https:443
Http请求

Http响应

请求方式:
get:请求能够携带的参数比较少,大小有限制,会在浏览器地址栏显示参数的内容,不安全,但是高效。
post:请求能够携带的参数没有限制,大小没有限制,不会再浏览器地址栏显示参数的内容,安全,但不高效。
响应状态码:
200:请求响应成功
3**:请求重定向
404:找不到资源
500:服务器代码错误,502:网关错误
Maven:项目架构管理工具,自动导入jar包(约定大于配置)。
下载Maven后解压,配置环境变量,将bin目录的路径配置到path中,在cmd中输入mvn-version,查看是否配置成功
在conf目录下setting的 下配置本地仓库
D:\Environments\apache-maven-3.6.3\maven-repo
在conf目录下setting的 中配置阿里云的镜像

pom.xml:maven的核心配置文件
由于maven的约定大于配置,我们之后写的配置文件可能无法导出或者无法生效,就需要在maven配置下面配置resouce。
servlet就是sun公司开发动态web的一门技术,sun公司在API中提供了一个接口叫Servlet,如果需要开发一个Servlet程序,需要编写一个类去实现Servlet接口,再把开发好的java类部署到web服务器中。
sun公司有两个Servlet接口的默认实现类:HttpServlet和GenericServlet
构建一个maven项目,删除里面的src项目,以后就直接新建model,这个空的工程就是Maven的主工程。
关于Maven父子工程的理解:
父项目中会有
- <module>servlet-01module>
子项目中有
-
-
javaweb-02-servlet -
com.zr -
1.0-SNAPSHOT -
3.Maven环境优化:修改web.xml为最新的,将Maven的结构搭建完整。
4.编写一个普通类,实现Servlet接口,继承HttpServlet。
- public class HelloServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //ServletOutputStream outputStream = resp.getOutputStream();
- PrintWriter writer = resp.getWriter(); //响应流
- writer.println("Hello Servlet");
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }
5.编写Servlet的映射:我们写的是java程序,但是要通过浏览器访问,而浏览器要连接web服务器,所以我们要在web服务器注册我们写的Servlet,还需要给它一个浏览器能够访问的路径。
-
hello -
com.zr.servlet.HelloServlet -
hello -
/hello
6.配置Tomcat
7.启动测试
Servlet是由Web服务器调用,web服务器收到请求后,会进行以下操作:

一个Servlet可以指定一个映射路径
-
hello -
/hello
一个Servlet可以指定多个映射路径
-
hello -
/hello -
-
hello -
/hello2 -
-
hello -
/hello3
3.一个Servlet可以指定通用映射路径
-
hello -
/hello/*
4.默认请求
-
hello -
/*
5.一个Servlet可以指定一些后缀或者前缀映射路径
-
hello -
*.zzr
优先级问题:
指定了固有的映射路径,优先级最高,找不到就会走默认的处理请求。
处理404页面
-
error -
com.zr.servlet.ErrorServlet -
error -
/*
web容器在启动的时候,它会为每一个web程序都创建一个ServletContext对象,它代表了当前的 web应用。
共享数据
我在这个Servle中保存的数据可以在另外一个Servle中拿到
- public class HelloServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("hello");
- //this.getInitParameter(); 初始化参数
- //this.getServletConfig(); Servlet的配置
- //this.getServletContext(); Servlet上下文
-
- ServletContext context = this.getServletContext();
- String username = "周周";
- context.setAttribute("username",username);//将一个数据保存在ServletContext中
-
- }
- }
- public class GetServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- ServletContext context = this.getServletContext();
- String username = (String) context.getAttribute("username");
-
- resp.setCharacterEncoding("utf-8");
- resp.setContentType("text/html");
- resp.getWriter().println("名字:"+username);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- }
- }
-
hello -
com.zr.servlet.HelloServlet -
-
-
hello -
/hello -
-
-
get -
com.zr.servlet.GetServlet -
get -
/get
测试访问结果
1.获取初始化参数
-
url -
jdbc:mysql://localhost:3306/mybaits -
-
gp -
com.zr.servlet.ServletDemo03 -
-
-
gp -
/gp -
- public class ServletDemo03 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- ServletContext context = this.getServletContext();
- String url = context.getInitParameter("url");
- resp.getWriter().println(url);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }
2.请求转发
- public class ServletDemo04 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- ServletContext context = this.getServletContext();
- RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
- requestDispatcher.forward(req,resp);//转发
-
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }
-
sd4 -
com.zr.servlet.ServletDemo04 -
sd4 -
/sd4
读取资源文件
properties
发现都被打包到了target下的class目录下,我们称这个路径为类路径classpath。
- public class ServletDemo05 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
- Properties properties = new Properties();
- properties.load(is);
- String username = properties.getProperty("username");
- String password = properties.getProperty("password");
- resp.getWriter().println("username:"+username);
- resp.getWriter().println("password:"+password);
-
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
-
sd5 -
com.zr.servlet.ServletDemo05 -
sd5 -
/sd5
-
-
-
src/main/resources -
-
**/*.properties -
**/ *.xml -
-
true -
-
-
src/main/java -
-
**/*.properties -
**/ *.xml -
-
true -
-
- //文件 db.properties
- username=root
- password=123456
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应一个HttpServletResponse。
简单分类
负责向浏览器发送数据的方法
- ServletOutputStream getOutputStream() throws IOException;
-
- PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
- void setCharacterEncoding(String var1);
-
- void setContentLength(int var1);
-
- void setContentLengthLong(long var1);
-
- void setContentType(String var1);
-
- void setDateHeader(String var1, long var2);
-
- void addDateHeader(String var1, long var2);
-
- void setHeader(String var1, String var2);
-
- void addHeader(String var1, String var2);
-
- void setIntHeader(String var1, int var2);
-
- void addIntHeader(String var1, int var2);
响应的状态码
- int SC_OK = 200;
- ...
- int SC_MULTIPLE_CHOICES = 300;
- int SC_BAD_REQUEST = 400;
- int SC_UNAUTHORIZED = 401;
- int SC_PAYMENT_REQUIRED = 402;
- int SC_FORBIDDEN = 403;
- int SC_NOT_FOUND = 404;
- ...
- int SC_INTERNAL_SERVER_ERROR = 500;
- int SC_BAD_GATEWAY = 502;
向浏览器输出消息
下载文件
- public class FileServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //1. 获取下载文件的路径
- String realPath = "D:\\IDEACode\\javaweb-02-servlet\\response\\src\\main\\resources\\1.PNG";
- System.out.println("下载文件的路径:"+realPath);
- //2. 下载的文件名
- String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
- //3. 让浏览器支持下载我们需要的东西
- resp.setHeader("Content-Disposition","attachment;filename="+fileName);
- //4. 获取下载文件的输入流
- FileInputStream in = new FileInputStream(realPath);
- //5. 创建缓冲区
- int len = 0;
- byte[] buffer = new byte[1024];
- //6. 获得OutputStream对象
- ServletOutputStream out = resp.getOutputStream();
- //7. 将FileOutputStream流写入到buffer缓冲区 将OutputStream缓冲区中的对象输出到客户端
- while ((len=in.read(buffer))>0){
- out.write(buffer,0,len);
-
- }
- in.close();
- out.close();
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
如何生成验证码:
- public class ImageServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //让浏览器5秒刷新一次
- resp.setHeader("refresh","5");
- //创建图片
- BufferedImage image = new BufferedImage(300,60,BufferedImage.TYPE_INT_RGB);
- //得到图片
- Graphics g = image.getGraphics(); //笔
- //设置图片的背景颜色
- g.setColor(Color.green);
- g.fillRect(0,0,300,60);
- //给图片写数据
- g.setColor(Color.magenta);
- g.setFont(new Font(null,Font.BOLD,70));
- g.drawString(makeNum(),0,60);
- //浏览器以图片的形式打开
- resp.setContentType("image/png");
- //网站存在缓存。不让浏览器缓存
- resp.setDateHeader("expires",-1);
- resp.setHeader("Cache-Control","no-cache");
- resp.setHeader("Pragma","no-cache");
-
- //把图片显示出来
- boolean write = ImageIO.write(image,"jpg",resp.getOutputStream());
-
- }
- //生成随机数
- private String makeNum(){
- Random random = new Random();
- String num = random.nextInt(9999999) + "";
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < 7-num.length(); i++) {
- sb.append("0");
- }
- num = sb.toString()+num;
- return num;
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
-
image -
com.zr.servlet.ImageServlet -
image -
/image
void sendRedirect(String var1) throws IOException;//重定向
- public class RedirectServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- /*
- resp.setHeader("Location","/r/image");
- resp.setStatus(302);
- */
-
- resp.sendRedirect("/r/image");
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
配置web.xml测试
重定向和转发的区别:
相同点:页面都会发生跳转
不同点:
index.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
Hello World!
- <%--提交的路径需要寻找到当前项目的路径--%>
- 用户名:"text" name="username">
- 密码 :"password" name="password">
- "submit">
-
success.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
Title success
- public class RequestTest extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- System.out.println("进入这个请求了");
-
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- System.out.println("username:"+username);
- System.out.println("password:"+password);
- resp.sendRedirect("/r/success.jsp");
-
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
-
test -
com.zr.servlet.RequestTest -
test -
/login
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有的信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
- public class LoginServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doPost(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- String[] hobbys = req.getParameterValues("hobbys");
-
- System.out.println("==================================");
- System.out.println(username);
- System.out.println(password);
- System.out.println(Arrays.toString(hobbys));
-
- //请求转发
- //这里的/代表当前的web应用
- req.getRequestDispatcher("/success.jsp").forward(req,resp);
-
- }
- }
index.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
登录 登录
- "text-align: center">
-
- 用户名:"text" name="username">
- 密码:"password" name="password">
- 爱好:
- "checkbox" name="hobbys" value="唱歌">唱歌
- "checkbox" name="hobbys" value="女孩">女孩
- "checkbox" name="hobbys" value="写字">写字
- "checkbox" name="hobbys" value="代码">代码
-
- "submit">
-
-
success.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
Title 登录成功
web.xml
-
LoginServlet -
com.zr.servlet.LoginServlet -
LoginServlet -
/login
cookie
session
常见应用:网站登录一次后,下次可以直接进入。
从请求中拿到cookie信息
服务器响应给客户端cookie
- //保存用户上一次访问的时间
- public class CookieDemo01 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //解决中文乱码
- req.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
-
- PrintWriter out= resp.getWriter();
- //cookie,服务器端从客户端获取
- Cookie[] cookies = req.getCookies();//返回数组,cookie可能存在多个
- //判断cookie是否存在
- if (cookies!=null){
- //如果存在
- out.write("你上一次访问的时间是:");
- for (int i = 0; i < cookies.length; i++) {
- Cookie cookie = cookies[i];
- //获取cookie的名字
- if (cookie.getName().equals("lastlogintime")){
- //获取cookie中的值
-
- long lastlogintime = Long.parseLong(cookie.getValue());
- Date date = new Date(lastlogintime);
- out.write(date.toLocaleString());
-
- }
- }
- }else{
- out.write("这是你第一次访问本站!");
- }
- //服务器给客户端发一个cookie
- Cookie cookie = new Cookie("lastlogintime", System.currentTimeMillis()+"");
- //有效期为1天
- cookie.setMaxAge(24*60*60);
- resp.addCookie(cookie);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
web.xml
-
CookieDemo01 -
com.zr.servlet.CookieDemo01 -
-
CookieDemo01 -
/c1
cookie:一般会保存在本地的用户目录下appdata;
删除cookie
session:
服务器会给每一个用户(浏览器)创建一个session对象
一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
用户登录之后,整个网站都可以访问,-->保存用户的信息
session和cookie的区别:
session保存数据
- package com.zr.pojo;
-
- public class Person {
- private String name;
- private int age;
-
- public Person() {
- }
-
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- @Override
- public String toString() {
- return "Person{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
- public class SessionDemo01 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //解决中文乱码
- req.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- //得到session
- HttpSession session = req.getSession();
-
- //给session存东西
- session.setAttribute("name",new Person("周周",1));
- //获得session的id
- String id = session.getId();
- //判断session是不是新创建的
- if(session.isNew()){
- resp.getWriter().write("session创建成功,ID:"+ id);
- }else {
- resp.getWriter().write("session已经存在,ID:"+ id);
- }
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
- public class SessionDemo02 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //解决中文乱码
- req.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- //得到session的数据
- HttpSession session = req.getSession();
-
- Person person = (Person) session.getAttribute("name");
- System.out.println(person);
-
- }
-
- @Overridejava
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
-
SessionDemo01 -
com.zr.servlet.SessionDemo01 -
SessionDemo01 -
/s1 -
-
SessionDemo02 -
com.zr.servlet.SessionDemo02 -
SessionDemo02 -
/s2
session手动注销
- public class SessionDemo03 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- HttpSession session = req.getSession();
- session.removeAttribute("name");
- //手动注销session
- session.invalidate();
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
jsp:java server pages,Java服务器端界面,和servlet一样,用于开发动态web技术。
特点
实体类
JavaBean有特定的写法:
一般用来和数据库的字段做映射 ORM;
ORM对象关系映射

建立数据库相应的字段后创建java实体类
- package com.zr.pojo;
- //实体类 一般是和数据库中的表结构一一对应的
- public class People {
- private int id;
- private String name;
- private int age;
- private String address;
-
- public People() {
- }
-
- public People(int id, String name, int age, String address) {
- this.id = id;
- this.name = name;
- this.age = age;
- this.address = address;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
-
- @Override
- public String toString() {
- return "People{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", age=" + age +
- ", address='" + address + '\'' +
- '}';
- }
- }
-
- <%@ page import="com.zr.pojo.People" %><%--
- Created by IntelliJ IDEA.
- User: zr
- Date: 2020/10/11
- Time: 22:08
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
Title - <%
- // People people = new People();
- // people.setAddress();
- // people.setId();
- // people.setAge();
- // people.setName();
- //和下面的等价
- %>
"people" class="com.zr.pojo.People" scope="page"/> "people" property="address" value="武汉"/> "people" property="id" value="1"/> "people" property="age" value="18"/> "people" property="name" value="小周"/> -
- 姓名:
"people" property="name"/> - id:
"people" property="id"/> - 年龄:
"people" property="age"/> - 地址:
"people" property="address"/>
MVC:model,view,controller 模型视图控制器
Model
View
Controller(Servlet)
工作流程:
1.浏览器通过视图向控制器发出请求;
2.控制器接收到请求后对数据进行封装,选择模型进行业务逻辑处理;
3.随后控制器将模型处理结果转发到视图或下一个控制器;
4.在视图层合并数据和界面模板生成HTML并做出最终响应。
Filter:过滤器,用来过滤网站的数据:
Filter
功能:
1、⽤来拦截传⼊的请求和传出的响应。
2、修改或以某种⽅式处理正在客户端和服务端之间交换的数据流。
如何使⽤?
与使⽤ Servlet 类似,Filter 是 Java WEB 提供的⼀个接⼝,开发者只需要⾃定义⼀个类并且实现该接⼝
即可。
Filter 的⽣命周期
当 Tomcat 启动时,通过反射机制调⽤ Filter 的⽆参构造函数创建实例化对象,同时调⽤ init ⽅法实现
初始化,doFilter ⽅法调⽤多次,当 Tomcat 服务关闭的时候,调⽤ destory 来销毁 Filter 对象。
⽆参构造函数:只调⽤⼀次,当 Tomcat 启动时调⽤(Filter ⼀定要进⾏配置)
init ⽅法:只调⽤⼀次,当 Filter 的实例化对象创建完成之后调⽤
doFilter:调⽤多次,访问 Filter 的业务逻辑都写在 Filter 中
destory:只调⽤⼀次,Tomcat 关闭时调⽤。
同时配置多个 Filter,Filter 的调⽤顺序是由 web.xml 中的配置顺序来决定的,写在上⾯的配置先调
⽤,因为 web.xml 是从上到下顺序读取的。
实际开发中 Filter 的使⽤场景:
1、统⼀处理中⽂乱码。
2、屏蔽敏感词。
监听器GUI编程中经常使用
Java连接数据库,导入JDBC依赖mysql-connector-java,IDEA中连接数据库
- public class TestJdbc {
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
- //配置信息
- String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
- String username = "root";
- String password = "123456";
- //加载驱动
- Class.forName("com.mysql.jdbc.Driver");
- //连接数据库
- Connection connection = DriverManager.getConnection(url, username, password);
- //向数据库发送sql的对象
- Statement statement = connection.createStatement();
- //编写sql
- String sql = "select * from users";
- //执行查询sql,返回一个结果集
- ResultSet rs = statement.executeQuery(sql);
-
- while (rs.next()){
- System.out.println("id="+rs.getObject("id"));
- System.out.println("name="+rs.getObject("name"));
- System.out.println("password="+rs.getObject("password"));
- System.out.println("email="+rs.getObject("email"));
- System.out.println("birthday="+rs.getObject("birthday"));
- }
- //关闭连接
- rs.close();
- statement.close();
- connection.commit();
- }
- }
预编译sql
Junit单元测试
依赖
-
junit -
junit -
4.12 -
test
简单使用
@Test注解只在方法上有效,只要加了这个注解的方法,就可以直接运行.
- public class TestJdbc3 {
-
- @Test
- public void test(){
- System.out.println("Hello");
- }
- }
转账事务(创建account表,字段id,name,money),使用单元测试
- public class TestJdbc3 {
-
- @Test
- public void test() {
- //配置信息
- String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
- String username = "root";
- String password = "123456";
- Connection connection=null;
- //加载驱动
- try {
- Class.forName("com.mysql.jdbc.Driver");
- //连接数据库
- connection = DriverManager.getConnection(url, username, password);
- //通知数据库开启事务
- connection.setAutoCommit(false);
- String sql1 = "update account set money=money-100 where name='A'";
- connection.prepareStatement(sql1).executeUpdate();
-
- //制造错误
- int i=1/0;
-
- String sql2 = "update account set money=money+100 where name='B'";
- connection.prepareStatement(sql2).executeUpdate();
-
- connection.commit();//以上sql都执行成功才提交
- System.out.println("提交成功!");
- } catch (Exception e) {
- try {
- //如果出现异常,就回滚事务
- connection.rollback();
- System.out.println("转账失败!");
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- e.printStackTrace();
- }finally {
- try {
- connection.close();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- }
- }
- }