Servlet簡介
- 什么是Servlet
Servelt是運(yùn)行在服務(wù)端的Java小程序。
servlet規(guī)范:包含三個(gè)技術(shù)點(diǎn)
- servlet技術(shù)
- filter技術(shù) -過濾器
- listener 技術(shù) - 監(jiān)聽器
- Servlet快速入門
實(shí)現(xiàn)步驟:
- 創(chuàng)建類實(shí)現(xiàn)Servlet接口
- 覆蓋尚未實(shí)現(xiàn)的方法
- 在web.xml進(jìn)行servlet的配置
在實(shí)際開發(fā)中雌贱,我們不會(huì)直接去實(shí)現(xiàn)Servlet接口啊送,因?yàn)槟菢有枰采w的方法太多。一般是創(chuàng)建類繼承HttpServlet.
實(shí)現(xiàn)步驟:
- 創(chuàng)建類繼承HttpServlet類
- 覆蓋doget 和dopost
- 在web.xml中進(jìn)行servlet的配置
Servlet 的API(生命周期)
Servlet接口中的方法
- init : 在 servlet 對象創(chuàng)建的時(shí)候執(zhí)行
- service : 每次請求都會(huì)執(zhí)行
- destroy: servlet 銷毀時(shí)候執(zhí)行
Service 的聲明周期
- Servlet創(chuàng)建:默認(rèn)第一次訪問servlet時(shí)創(chuàng)建該對象
- 何時(shí)銷毀: 服務(wù)器關(guān)閉了就銷毀了
- 每次訪問必然執(zhí)行的方法: service
利用Servlet完成登錄操作
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.獲得用戶名和密碼
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.從數(shù)據(jù)庫驗(yàn)證該用戶名和密碼是否正確
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
User user = null;
try {
user = runner.query(sql, new BeanHandler<User>(User.class), username, password);
} catch (SQLException e) {
e.printStackTrace();
}
//3.根據(jù)返回結(jié)果給用戶不同顯示信息
if (user != null) {
//登錄成功
response.getWriter().write("Yes,Login Success" + user.toString());
} else {
//登錄失敗
response.getWriter().write("sorry,Login fail");
}
}
ServletContext對象
1.什么是ServletContext對象
??????servletContext代表是一個(gè)web應(yīng)用的環(huán)境 上下文對象帽芽。ServletContext對象內(nèi)部封裝是該web 應(yīng)用的信息 Servlet對象一個(gè)web應(yīng)用只有一個(gè)對象删掀。
??????ServletContext對象的聲明周期
???? 在web應(yīng)用被加載的時(shí)候創(chuàng)建。在web應(yīng)用卸載的時(shí)候 銷毀
- 怎樣獲得ServletContext對象
???? ServletContext context = getServletContext();
3.ServletContext 作用
獲得初始化參數(shù)
獲得web應(yīng)用中任何資源的絕對路徑
String path = context.getRealPath(相對于該web應(yīng)用的一個(gè)相對地址)
- ServletContext 是一個(gè)域?qū)ο?br> 域?qū)ο髸r(shí):存儲數(shù)據(jù)的區(qū)域就是域?qū)ο?/li>
ServletContext域?qū)ο蟮淖饔梅秶赫麄€(gè)web應(yīng)用
實(shí)現(xiàn)servlet之間的通信
存對象:context.setAttribute(" " , " ");
取對象: String attribute = (String) this. getServletContext().getAttribute(" ");
我是一個(gè)自學(xué)Android和JavaWeb的菜鳥导街。如果可以Flower一下我的GitHub。感激不盡
https://github.com/FoxconnPeter