生活随笔
收集整理的這篇文章主要介紹了
JavaWeb(九)——JavaBean、Filter
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. JavaBean
- 2. MVC三層架構(gòu)
- 3. Filter (重點(diǎn))
- 4. 監(jiān)聽器
- 5. 過濾器、監(jiān)聽器的常見應(yīng)用
1. JavaBean
實(shí)體類:一般都是和數(shù)據(jù)庫中的表結(jié)構(gòu)一一對(duì)應(yīng)
JavaBean有特定的寫法:
- 必須要有一個(gè)無參構(gòu)造
- 屬性必須私有化
- 必須有對(duì)應(yīng)的get/set方法;
一般用來和數(shù)據(jù)庫的字段做映射 ORM;
ORM :對(duì)象關(guān)系映射
- 表—>類
- 字段–>屬性
- 行記錄---->對(duì)象
class People{private int id
;private String name
;private int age
;private String address
;
}class A{new People(1,"美女1號(hào)",18,
"安徽");new People(2,"美女2號(hào)",27,
"杭州");new People(3,"美女3號(hào)",38,
"西安");
}
JavaBean屬性
- 一個(gè)JavaBean對(duì)象的屬性應(yīng)該是可訪問的。這個(gè)屬性可以是任意合法的Java數(shù)據(jù)類型,包括自定義Java類。
- 一個(gè)JavaBean對(duì)象的屬性可以是可讀寫,或只讀,或只寫。 getPropertyName() 和 setPropertyName() 兩個(gè)方法
進(jìn)行測試:
建立一個(gè)People 類
package com
.zz
.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
;}@Overridepublic String
toString() {return "People{" +"id=" + id
+", name='" + name
+ '\'' +", age=" + age
+", address='" + address
+ '\'' +'}';}
}
打開SQLyog軟件,創(chuàng)建數(shù)據(jù)庫jdbc,并在數(shù)據(jù)庫下創(chuàng)建表people
用IDEA連接jdbc數(shù)據(jù)庫
建立javabean.jsp
<%@ page contentType
="text/html;charset=UTF-8" language
="java" %>
<html>
<head><title>Title
</title
>
</head
>
<body><jsp
:useBean id
="people" class="com.zz.pojo.People" scope
="page"/><jsp
:setProperty name
="people" property
="id" value
="1" />
<jsp
:setProperty name
="people" property
="name" value
="小胖豬" />
<jsp
:setProperty name
="people" property
="age" value
="18" />
<jsp
:setProperty name
="people" property
="address" value
="安徽" /><%--得到
--%>
id:
<jsp
:getProperty name
="people" property
="id"/>;
姓名:
<jsp
:getProperty name
="people" property
="name"/>;
年齡:
<jsp
:getProperty name
="people" property
="age"/>;
地址:
<jsp
:getProperty name
="people" property
="address"/></body
>
</html
>
測試訪問結(jié)果:
2. MVC三層架構(gòu)
什么是MVC: Model view Controller 模型、視圖、控制器
2.1 早些年
用戶直接訪問控制層,控制層就可以直接操作數(shù)據(jù)庫;
servlet
--CRUD
-->數(shù)據(jù)庫
弊端:程序十分臃腫,不利于維護(hù)
servlet的代碼中:處理請(qǐng)求、響應(yīng)、視圖跳轉(zhuǎn)、處理JDBC、處理業(yè)務(wù)代碼、處理邏輯代碼架構(gòu):沒有什么是加一層解決不了的!
程序猿調(diào)用
|
JDBC
|
Mysql Oracle SqlServer
....
2.2 MVC 三層架構(gòu)
Model
- 業(yè)務(wù)處理 :業(yè)務(wù)邏輯(Service)
- 數(shù)據(jù)持久層:CRUD (Dao)
View
- 展示數(shù)據(jù)
- 提供鏈接發(fā)起Servlet請(qǐng)求 (a,form,img…)
Controller (Servlet)
- 接收用戶的請(qǐng)求 :(req:請(qǐng)求參數(shù)、Session信息….)
- 交給業(yè)務(wù)層處理對(duì)應(yīng)的代碼
- 控制視圖的跳轉(zhuǎn)
登錄
--->接收用戶的登錄請(qǐng)求
--->處理用戶的請(qǐng)求(獲取用戶登錄的參數(shù),username,password)
---->交給業(yè)務(wù)層處理登錄業(yè)務(wù)(判斷用戶名密碼是否正確:事務(wù))
--->Dao層查詢用戶名和密碼是否正確
-->數(shù)據(jù)庫
3. Filter (重點(diǎn))
Filter:過濾器 ,用來過濾網(wǎng)站的數(shù)據(jù);
- 處理中文亂碼
- 登錄驗(yàn)證….
Filter開發(fā)步驟:
(1)導(dǎo)包
在pom.xml文件內(nèi)進(jìn)行導(dǎo)包
<?xml version
="1.0" encoding
="UTF-8"?>
<project xmlns
="http://maven.apache.org/POM/4.0.0"xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance"xsi
:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion
><groupId>com
.zz
</groupId
><artifactId>javaweb
-filter
</artifactId
><version>1.0-SNAPSHOT
</version
><dependencies><!--Servlet依賴
--><dependency><groupId>javax
.servlet
</groupId
><artifactId>servlet
-api
</artifactId
><version>2.5</version
></dependency
><!--JSP依賴
--><dependency><groupId>javax
.servlet
.jsp
</groupId
><artifactId>javax
.servlet
.jsp
-api
</artifactId
><version>2.3.3</version
></dependency
><!--JSTL表達(dá)式的依賴
--><dependency><groupId>javax
.servlet
.jsp
.jstl
</groupId
><artifactId>jstl
-api
</artifactId
><version>1.2</version
></dependency
><!--standard標(biāo)簽庫
--><dependency><groupId>taglibs
</groupId
><artifactId>standard
</artifactId
><version>1.1.2</version
></dependency
><!--連接數(shù)據(jù)庫
--><dependency><groupId>mysql
</groupId
><artifactId>mysql
-connector
-java
</artifactId
><version>5.1.47</version
></dependency
></dependencies
></project
>
(2)編寫過濾器
- 實(shí)現(xiàn)Filter接口,重寫對(duì)應(yīng)的方法即可
CharacterEncodingFilter文件的代碼如下:
package com
.zz
.filter
;import javax
.servlet
.*
;
import java
.io
.IOException
;public class CharacterEncodingFilter implements Filter {public void init(FilterConfig filterConfig
) throws ServletException
{System
.out
.println("CharacterEncodingFilter初始化");}public void doFilter(ServletRequest servletRequest
, ServletResponse servletResponse
, FilterChain filterChain
) throws IOException
, ServletException
{servletRequest
.setCharacterEncoding("utf-8");servletResponse
.setCharacterEncoding("utf-8");servletResponse
.setContentType("text/html;charset=utf-8"); System
.out
.println("CharacterEncodingFilter執(zhí)行之前.....");filterChain
.doFilter(servletRequest
,servletResponse
);System
.out
.println("CharacterEncodingFilter執(zhí)行之后.....");}public void destroy() {System
.out
.println("CharacterEncodingFilter銷毀");}
}
package com
.zz
.servlet
;import javax
.servlet
.ServletException
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.IOException
;public class ShowServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{resp
.getWriter().write("你好,小姐姐");}@Overrideprotected void doPost(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{doGet(req
, resp
);}
}
<?xml version
="1.0" encoding
="UTF-8"?>
<web
-app xmlns
="http://xmlns.jcp.org/xml/ns/javaee"xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance"xsi
:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version
="4.0"><servlet><servlet
-name
>ShowServlet
</servlet
-name
><servlet
-class>com
.zz
.servlet
.ShowServlet
</servlet
-class>
</servlet
><servlet
-mapping
><servlet
-name
>ShowServlet
</servlet
-name
><url
-pattern
>/servlet
/show
</url
-pattern
></servlet
-mapping
><servlet
-mapping
><servlet
-name
>ShowServlet
</servlet
-name
><url
-pattern
>/show
</url
-pattern
></servlet
-mapping
><filter><filter
-name
>CharacterEncodingFilter
</filter
-name
><filter
-class>com
.zz
.filter
.CharacterEncodingFilter
</filter
-class></filter
><filter
-mapping
><filter
-name
>CharacterEncodingFilter
</filter
-name
><!--只要是
/servlet的任何請(qǐng)求,會(huì)經(jīng)過這個(gè)過濾器
--><url
-pattern
>/servlet
- 測試訪問結(jié)果:
訪問show 時(shí),沒有經(jīng)過過濾器,會(huì)出現(xiàn)亂碼問題
訪問servlet/show時(shí),經(jīng)過過濾器,不會(huì)出現(xiàn)亂碼問題
此時(shí)輸出控制臺(tái)顯示:
當(dāng)關(guān)閉服務(wù)器時(shí),輸出控制臺(tái)顯示:
4. 監(jiān)聽器
實(shí)現(xiàn)一個(gè)監(jiān)聽器的接口;(有N種)
(1)編寫一個(gè)監(jiān)聽器OnlineCountListener
實(shí)現(xiàn)監(jiān)聽器的接口HttpSessionListener…
package com
.zz
.listener
;import javax
.servlet
.ServletContext
;
import javax
.servlet
.http
.HttpSessionEvent
;
import javax
.servlet
.http
.HttpSessionListener
;
public class OnlineCountListener implements HttpSessionListener {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
);}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
);}}
(2)web.xml中注冊(cè)監(jiān)聽器
<!--注冊(cè)監(jiān)聽器
--><listener><listener
-class>com
.zz
.listener
.OnlineCountListener
</listener
-class></listener
><session
-config
><session
-timeout
>1</session
-timeout
></session
-config
>
(3)測試訪問結(jié)果:
5. 過濾器、監(jiān)聽器的常見應(yīng)用
監(jiān)聽器應(yīng)用:GUI編程中經(jīng)常使用
package com
.zz
.listener
;import java
.awt
.*
;
import java
.awt
.event
.WindowAdapter
;
import java
.awt
.event
.WindowEvent
;public class TestPanel {public static void main(String
[] args
) {Frame frame
= new Frame("中秋節(jié)快樂"); 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() {@Overridepublic void windowClosing(WindowEvent e
) {super.windowClosing(e
);}});}
}
過濾器應(yīng)用:用戶登錄之后才能進(jìn)入登錄成功頁面(主頁)!用戶注銷后就不能進(jìn)入登錄成功頁面了!
(1)用戶登錄之后,向Sesison中放入用戶的數(shù)據(jù)
(2)進(jìn)入主頁的時(shí)候要判斷用戶是否已經(jīng)登錄;要求:在過濾器中實(shí)現(xiàn)!
- 創(chuàng)建的文件有如下:
- 登錄頁面 Login.jsp 的代碼如下:
<%@ page contentType
="text/html;charset=UTF-8" language
="java" %>
<html>
<head><title>Title
</title
>
</head
>
<body><h1>登錄
</h1
>
<form action
="/servlet/login" method
="post"><input type
="text" name
="username"><input type
="submit">
</form
></body
>
</html
>
- 登錄成功頁面 success.jsp 的代碼如下:
<%@ page contentType
="text/html;charset=UTF-8" language
="java" %>
<html>
<head><title>Title
</title
>
</head
>
<body><h1>歡迎來到主頁
</h1
>
<p><a href
="/servlet/logout">注銷
</a
></p
></body
>
</html
>
- 登錄錯(cuò)誤頁面 error.jsp 的代碼如下:
<%@ page contentType
="text/html;charset=UTF-8" language
="java" %>
<html>
<head><title>Title
</title
>
</head
>
<body>
<h1>錯(cuò)誤
</h1
>
<h3>沒有權(quán)限,或者用戶名錯(cuò)誤!
</h3
>
<a href
="/Login.jsp">返回到登錄頁面
</a
></body
>
</html
>
package com
.zz
.servlet
;import javax
.servlet
.ServletException
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.IOException
;public class LoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{String username
= req
.getParameter("username");if(username
.equals("admin")){req
.getSession().setAttribute("USER_SESSION",req
.getSession().getId());resp
.sendRedirect("/sys/success.jsp");}else{resp
.sendRedirect("/error.jsp");}}@Overrideprotected void doPost(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{doGet(req
, resp
);}
}
package com
.zz
.servlet
;import javax
.servlet
.ServletException
;
import javax
.servlet
.http
.HttpServlet
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.IOException
;public class LogoutServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{Object user_session
= req
.getSession().getAttribute("USER_SESSION");if(user_session
!=null
){req
.getSession().removeAttribute("USER_SESSION");resp
.sendRedirect("/Login.jsp");}}@Overrideprotected void doPost(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{doGet(req
, resp
);}
}
package com
.zz
.util
;public class Constant {public static String USER_SESSION
="USER_SESSION";
}
<?xml version
="1.0" encoding
="UTF-8"?>
<web
-app xmlns
="http://xmlns.jcp.org/xml/ns/javaee"xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance"xsi
:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version
="4.0"><servlet><servlet
-name
>LoginServlet
</servlet
-name
><servlet
-class>com
.zz
.servlet
.LoginServlet
</servlet
-class></servlet
><servlet
-mapping
><servlet
-name
>LoginServlet
</servlet
-name
><url
-pattern
>/servlet
/login
</url
-pattern
></servlet
-mapping
><servlet><servlet
-name
>LogoutServlet
</servlet
-name
><servlet
-class>com
.zz
.servlet
.LogoutServlet
</servlet
-class></servlet
><servlet
-mapping
><servlet
-name
>LogoutServlet
</servlet
-name
><url
-pattern
>/servlet
/logout
</url
-pattern
></servlet
-mapping
>
</web
-app
>
-
測試訪問結(jié)果:
進(jìn)入登錄頁面
隨意輸入,如:2323,就進(jìn)入了登錄錯(cuò)誤頁面
輸入admin, 就進(jìn)入了登錄成功頁面,再點(diǎn)擊注銷按鈕
-
發(fā)現(xiàn)問題:點(diǎn)擊注銷后,即未登錄成功的情況下,就能直接訪問登錄成功頁面
-
解決方法
方法一(不推薦使用):
在登錄成功的頁面上進(jìn)行限制,即增加下圖紅方塊內(nèi)代碼。
同時(shí)在LogoutServlet 中增加如下代碼:
方法二(推薦使用):
添加一個(gè)過濾器,編寫SysFilter類,代碼如下:
package com
.zz
.filter
;import javax
.servlet
.*
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.IOException
;public class SysFilter implements Filter {public void init(FilterConfig filterConfig
) throws ServletException
{}public void doFilter(ServletRequest servletRequest
, ServletResponse servletResponse
, FilterChain filterChain
) throws IOException
, ServletException
{HttpServletRequest request
= (HttpServletRequest
) servletRequest
;HttpServletResponse response
= (HttpServletResponse
) servletResponse
;Object user_session
= request
.getSession().getAttribute("USER_SESSION");if(user_session
==null
){response
.sendRedirect("/error.jsp");}filterChain
.doFilter(request
,response
);}public void destroy() {}
}
在web.xml 中注冊(cè)過濾器:
<!--注冊(cè)過濾器
--><filter><filter
-name
>SysFilter
</filter
-name
><filter
-class>com
.zz
.filter
.SysFilter
</filter
-class></filter
><filter
-mapping
><filter
-name
>SysFilter
</filter
-name
><url
-pattern
>/sys
測試訪問結(jié)果:
進(jìn)入登錄頁面
輸入admin,進(jìn)入登錄成功頁面后,點(diǎn)擊注銷按鈕
再輸入sys/success.jsp后,不能再進(jìn)入登錄成功頁面,顯示進(jìn)入登錄錯(cuò)誤頁面
總結(jié)
以上是生活随笔為你收集整理的JavaWeb(九)——JavaBean、Filter的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。