11、Filter (重點) Filter:過濾器 ,用來過濾網站的數據; 處理中文亂碼 登錄驗證…. Filter開發步驟: 1. 導包 2. 編寫過濾器 1. 導包不要錯 實現Filter介面,重寫對應的方法即可 3. 在web.xml中配置 Filter 12、監聽器 實現一個監聽器的介面;( ...
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','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','[email protected]','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,"[email protected]");//給第四個占位符? 的值賦值為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();
}
}
}