百度百科說法:
Servlet(Server Applet)是Java Servlet的簡稱,稱為小服務(wù)程序或服務(wù)連接器,用Java編寫的服務(wù)器端程序,主要功能在于交互式地瀏覽和修改數(shù)據(jù),生成動(dòng)態(tài)Web內(nèi)容。
通俗講法:
是運(yùn)行在服務(wù)器端的一小段Java程序,接受和響應(yīng)從客戶端發(fā)送的請求
作用:
處理客戶端請求,并且對請求做出響應(yīng)
編寫一個(gè)serclet步驟
1、編寫一個(gè)類
繼承自HttpServlet
重寫doGet和doPost方法
2、編寫配置文件(web.xml)
先注冊后綁定
3、訪問
http://localhost/項(xiàng)目名/路徑
注意:
接收參數(shù): 格式:value=key
String value = request.getParameter("key");
例如:http://localhost/day09/hello?username=tom
中,String value = request.getParameter("username");
回寫參數(shù):
response.getWriter().print("success");
處理響應(yīng)中的亂碼問題:
resp.setContentType("text/html;charset=utf-8");一般放在第一行
以下是原碼:
public class RequestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); // 接收參數(shù) String value = req.getParameter("username"); System.out.println(value); //向?yàn)g覽器回寫數(shù)據(jù) resp.getWriter().print("data:"+value); resp.getWriter().print("你好"); } }