1. 程式人生 > >【Servlet】Servlet應用的get、post訪問及和JSP的配合使用

【Servlet】Servlet應用的get、post訪問及和JSP的配合使用

Servlet是一種伺服器端的Java應用程式,具有獨立於平臺和協議的特性,可以生成動態的Web頁面。 

它擔當客戶請求(Web瀏覽器或其他HTTP客戶程式)與伺服器響應(HTTP伺服器上的資料庫或應用程式)的中間層。 

Servlet是位於Web伺服器內部的伺服器端的Java應用程式,與傳統的從命令列啟動的Java應用程式不同。

Servlet由Web伺服器進行載入,該Web伺服器必須包含支援Servlet的Java虛擬機器。

Servlet例項化過程

1. servlet容器負責建立servlet的一個例項(在第一次請求servlet的時候).

2. 容器呼叫該例項的init()方法完成初始化工作.

3. 如果容器對該servlet有請求,則呼叫此例項的service()方法,service()方法根據請求型別(get還是post)決定呼叫doXXX()方法.

4. 當web應用被終止時,容器在銷燬本例項前呼叫它的destroy()方法.

5. 銷燬並標記該例項以供作為垃圾收集.

在servlet生命週期中,servlet的初始化和和銷燬階段只會發生一次。

而service方法執行的次數則取決於servlet被客戶端訪問的次數。

Servlet如何處理請求

當用戶傳送一個請求到某個Servlet的時候,Servlet容器會建立一個ServletRequst和ServletResponse物件.

在ServletRequst物件中封裝了使用者的請求資訊,然後Servlet容器把建立好的ServletRequst和ServletResponse物件傳給使用者所請求的Servlet,Servlet把處理好的結果寫在ServletResponse中,最後Servlet容器把響應結果傳給使用者。

一個簡單的Servlet

package com.app.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 Jue extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.print("這是一個get");
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.print("這是一個post");
		out.close();
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

}

配置Servlet的web.xml

servlet和servlet-mapping中的servlet-name要保持一致。

url-pattern即是該servlet的訪問路徑。

<!--servlet邏輯名-->
	<servlet>
		<servlet-name>Jue</servlet-name>
		<servlet-class>com.app.servlet.Jue</servlet-class>
	</servlet>
<!--servlet對映-->
	<servlet-mapping>
		<servlet-name>Jue</servlet-name>
		<url-pattern>/jue.eee</url-pattern>
	</servlet-mapping>

Servlet的get訪問

Servlet預設的即為get訪問。

在位址列輸入:http://localhost:8888/WebDemo/jue.eee


Servlet的post訪問

Servlet的post訪問必須建立在JSP的表單的基礎上。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'MyJsp.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    This is my JSP page. <br>
	<form method="post" action="user.eee">
		<table cellspacing="5" align="center" width="840" border-collapse="collapse">
			<tr><td width="220" align="right"><img src="img/logo_login01.gif"/></tr>
            <tr ><td align="center"></td><td></td></tr>
  			<tr ><td align="right">賬  號:  </td>
  			<td><input type="text"id="username" name="username"style="height:25px;width:250px" vspace="5"></td></tr>
            <tr><td align="right">密  碼:  </td>
            <td><input id="password"type="password" name="password"style="height:25px;width:250px" vspace="5"></td></tr>
            <tr><td ></td><td><input type="checkbox">
            <font size="1" face="微軟雅黑" color="red">  記住我一週</font></td>
            <tr><td ></td><td>
         	<input type="submit" name="submit" value="LOGIN"/>
            <a href="https://passport.csdn.net/account/forgotpassword" target="_blank" align="right">
            <font size="1"><u>忘記密碼</u></font></a>
           </td></tr>
		</table>
	</form>
  </body>
</html>

訪問該表單所在頁面:http://localhost:8888/WebDemo/MyJsp.jsp


登入後,頁面即會跳轉至 Servlet 的post頁面 :http://localhost:8888/WebDemo/user.eee