Java Web 笔记(4)
11、Filter (重点)
Filter:过滤器 ,用来过滤网站的数据;
- 处理中文乱码
- 登录验证….

Filter开发步骤:
导包
编写过滤器
- 导包不要错

实现Filter接口,重写对应的方法即可
```java
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
//Chain : 链
/*
1. 过滤中的所有代码,在过滤特定请求的时候都会执行
2. 必须要让过滤器继续同行
chain.doFilter(request,response);
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前....");
chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止!
System.out.println("CharacterEncodingFilter执行后....");
}
//销毁:web服务器关闭的时候,过滤会销毁
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
```
在web.xml中配置 Filter
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是 /servlet的任何请求,会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
<!--<url-pattern>/*</url-pattern>-->
</filter-mapping>
12、监听器
实现一个监听器的接口;(有N种)
编写一个监听器
实现监听器的接口…
//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener { //创建session监听: 看你的一举一动
//一旦创建Session就会触发一次这个事件!
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
} ctx.setAttribute("OnlineCount",onlineCount); } //销毁session监听
//一旦销毁Session就会触发一次这个事件!
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
} ctx.setAttribute("OnlineCount",onlineCount); } /*
Session销毁:
1. 手动销毁 getSession().invalidate();
2. 自动销毁
*/
}web.xml中注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
看情况是否使用!
13、过滤器、监听器常见应用
监听器:GUI编程中经常使用;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("中秋节快乐"); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //设置窗体的布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,0,255)); //设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(0,255,0)); //设置背景颜色
frame.add(panel);
frame.setVisible(true);
//监听事件,监听关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
}
});
}
}
用户登录之后才能进入主页!用户注销后就不能进入主页了!
用户登录之后,向Sesison中放入用户的数据
进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp; if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
response.sendRedirect("/error.jsp");
} chain.doFilter(request,response);
14、JDBC
什么是JDBC : Java连接数据库!

需要jar包的支持:
- java.sql
- javax.sql
- mysql-conneter-java… 连接驱动(必须要导入)
实验环境搭建
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');
SELECT * FROM users;
导入数据库依赖
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
IDEA中连接数据库:

JDBC 固定步骤:
- 加载驱动
- 连接数据库,代表数据库
- 向数据库发送SQL的对象Statement : CRUD
- 编写SQL (根据业务,不同的SQL)
- 执行SQL
- 关闭连接
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users";
//5.执行查询SQL,返回一个 ResultSet : 结果集
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"));
}
//6.关闭连接,释放资源(一定要做) 先开后关
rs.close();
statement.close();
connection.close();
}
}
预编译SQL
public class TestJDBC2 {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());
//5.执行SQL
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功@");
}
//6.关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据的安全。
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(900) --100--> B(1100)
Junit单元测试
依赖
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!
@Test
public void test(){
System.out.println("Hello");
}

失败的时候是红色:

搭建一个环境
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(40),
money FLOAT
);
INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
@Test
public void test() {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).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("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Java Web 笔记(4)的更多相关文章
- Java Web 笔记(1)
JavaWeb 学习笔记,狂神说java,链接:https://www.bilibili.com/video/av68833391 Java Web 1.基本概念 1.1.前言 web开发: web, ...
- 1.JAVA WEB 笔记中文乱码
JAVA WEB 乱码问题解析 乱码原因 在Java Web开发过程中,经常遇到乱码的问题,造成乱码的原因,概括起来就是对字符编码和解码的方式不匹配. 既然乱码的原因是字符编码与解码的方式不匹配,那么 ...
- [转]Java Web笔记:搭建环境和项目配置(MyEclipse 2014 + Maven + Tomcat)
来源:http://www.jianshu.com/p/56caa738506a 0. 绪言 Java Web开发中,除了基础知识外,开发环境搭建,也是一项基本功.开发环境包括了IDE.项目管理.项目 ...
- Java WEB 笔记
1. 部署并启动 tomcat 服务器 1). 解压 apache-tomcat-version 到一个非中文目录下 2). 配置一个环境变量,JAVA_HOME(指向 JDK 安装目录)或 JRE_ ...
- Java Web 笔记(杂)
Java Web 概述 什么是Java Web 在Sun的Java Servlet 规范中,对Java Web 应用做了这样的定义: "Java Web" 应用由一组Servlet ...
- Java Web笔记(2)
学习笔记,狂神说java,链接:https://www.bilibili.com/video/av68833391 5.Maven 我为什么要学习这个技术? 在Javaweb开发中,需要使用大量的ja ...
- java Web笔记
Get:标记在地址栏中 放在请求行中显示get?Username=...Password=... Post:使用的是二进制的上传下载 请求行不显示信息 数据传输量大数据隐蔽对文本没有 pst不能再浏览 ...
- Java Web 笔记(3)
8.JSP 8.1.什么是JSP Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术! 最大的特点: 写JSP就像在写HTML 区别: HTML只 ...
- Java Web笔记之Servlet(1)
今天在学习Servlet时,使用浏览器显示的网页效果与预期的有差异,仔细查找发现实<!DOCTYPE>声明的问题,截图如下: 代码如下: package secondServlet; im ...
随机推荐
- windows 安装mongodb2
安装文件:mongodb-win32-x86_64-2008plus-ssl-3.2.6-signed.msi 电脑配置:win7 64位 MongoDB的安装很简单,设置好安装路径后,一直Next直 ...
- sharding-JDBC学习笔记
sharding-JDBC学习笔记 ShardingSphere ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC.Sharding-Pr ...
- 图像GIST特征和LMGIST包的python实现(有github)
1什么是Gist特征 (1) 一种宏观意义的场景特征描述 (2) 只识别"大街上有一些行人"这个场景,无需知道图像中在那些位置有多少人,或者有其他什么对 ...
- python 利用selenium爬取百度文库的word文章
今天学习如何使用selenium库来爬取百度文库里面的收费的word文档 from selenium import webdriver from selenium.webdriver.common.k ...
- CCNA的基础知识及要点
一.CCNA中的基础知识及要点: 2.网线的制作:568B:橙白,橙,绿白,蓝,蓝白,绿,棕白,棕 568A的排线顺序从左到右依次为:白绿.绿.白橙.蓝.白蓝.橙.白棕.棕.实验目的:初学者常为做网线 ...
- Codeforces_822
A.小的那个数的阶乘. #include<bits/stdc++.h> using namespace std; int a,b; int main() { ios::sync_with_ ...
- WeChall_Training: PHP LFI (Exploit, PHP, Training)
Your mission is to exploit this code, which has obviously an LFI vulnerability: GeSHi`ed PHP code 1 ...
- Codeforces_714_B
http://codeforces.com/problemset/problem/714/B 当不同大小整数有1.2个时,肯定成立,3个时,需要判断,大于等于4个,则肯定不成立. #include & ...
- 我的一个配置redux(实现一次存储与调用方法)之旅
前言 : 今天呢,就配置一下redux,redux的重要性呢,就叭叭叭一大堆,什么也没有带着配置一次来的重要,因为许多涉及到的属性和方法,用法是活的,但格式是需要记忆的. 过程中不要嫌我唠叨,有的地方 ...
- Scala 学习(10)之「集合 」
数组 定长数组 Array:采用()访问,而不是[],下标从 0 开始. val array1 = new Array[String](5) //创建数组 println(array1) //返回数组 ...