java的servlet是干嘛的_Servlet能够做什么?
Servlet是用Java代碼編寫的服務(wù)器方軟件程序,用于處理客戶機和服務(wù)器之間的消息傳遞。Java?Servlet?API為請求和響應(yīng)消息定義了一個標(biāo)準(zhǔn)接口,這樣Servlet就可以跨平臺和跨不同的Web應(yīng)用服務(wù)器間移植。
Servlet可以通過動態(tài)構(gòu)造一個發(fā)回客戶機的響應(yīng)來響應(yīng)客戶機請求。例如:下面是一個響應(yīng)HTTP請求的Servlet.源代碼如下:
package?com.servlet;
import?java.io.IOException;
import?java.io.PrintWriter;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
public?class?HelloServlet?extends?HttpServlet?{
public?HelloServlet()?{
super();
}
public?void?destroy()?{
super.destroy();?//?Just?puts?"destroy"?string?in?log
//?Put?your?code?here
}
public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
response.setContentType("text/html");
PrintWriter?out?=?response.getWriter();
out
.println("HTML?PUBLIC?\"-//W3C//DTD?HTML?4.01?Transitional//EN\">");
out.println("");
out.println("??
A?Servlet");out.println("??
");out.print("????This?is?");
out.print(this.getClass());
out.println(",?using?the?GET?method?and?say?you?hello");
out.println("??");
out.println("");
out.flush();
out.close();
}
public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
doGet(request,?response);
}
public?void?doPut(HttpServletRequest?request,?HttpServletResponse?response)
throws?ServletException,?IOException?{
//?Put?your?code?here
}
public?void?init()?throws?ServletException?{
//?Put?your?code?here
}
}
在Web.xml配置文件的配置如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
This?is?the?description?of?my?J2EE?component
This?is?the?display?name?of?my?J2EE?component
HelloServlet
com.servlet.HelloServlet
HelloServlet
/servlet/HelloServlet
在瀏覽器里輸入:
運行結(jié)果如下圖
由于Servlet是用Java編程語言編寫的,它們可以訪問整個Java?API集合。這就使它們非常適合實現(xiàn)復(fù)雜的商業(yè)應(yīng)用邏輯,特別是訪問企業(yè)中其它位置的數(shù)據(jù)。Java?Database?Connection(JDBC)?API就是一個示例,它允許Java程序訪問關(guān)系數(shù)據(jù)庫。一般我們不直接在Servelt里面寫JDBC編程,而是通過連接池技術(shù)或者Hibernate技術(shù)來實現(xiàn)JDBC的連接,后面會有綜合的例子。由于沒有與Servlet關(guān)聯(lián)的圖形,因此它不適合訪問GUI?Java?API(AWT/Swing)
可以多次調(diào)用一個Servlet來響應(yīng)來自多個客戶機的請求。這是一種多線程的工作方式,該Servlet只有一個實例,多個用戶通過多線程的訪問,來響應(yīng)給客戶的。因此,一個Servlet可以同時處理多個請求,并且可以使這些請求同步。Servlet可以將請求轉(zhuǎn)發(fā)到其它服務(wù)器和Servlet.
總結(jié)
以上是生活随笔為你收集整理的java的servlet是干嘛的_Servlet能够做什么?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 2020-09-17
- 下一篇: C++的三种容器适配器
