java_web 學習記錄(二):servlet

servlet 是sun公司制定的一種用於擴展web服務器功能的組件與規範,讓服務器能夠生成動態的頁面。

只需要寫一個java類繼承HttpServlet或者實現Servlet接口就可以實現我們自己的servlet。

下面我們來學習如何動態生成頁面。

一,在pom.xml中引入servlet api

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>3.1.0</version>
</dependency>

二,新建HelloServlet,繼承HttpServlet

package com.example.servlet;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.example.entity.UserInfo;

/**
 * 第一個servlet 應用
 * 
 * @author Administrator
 *
 */
public class HelloServlet extends HttpServlet {

	private static final long serialVersionUID = -7654863157709388449L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 設置請求參數編碼
		req.setCharacterEncoding("utf-8");

		String uri = req.getRequestURI();
		String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".do"));

		/**
		 * 動態生成頁面
		 */
		if ("/test_html".equals(path)) {
			// 設置響應格式
			resp.setContentType("text/html");
			// 獲取輸出流
			PrintWriter out = resp.getWriter();
			// 動態輸出頁面
			out.println("<html><head></head><body>hello servlet</body></html>");
			out.flush();
			out.close();
		}

		/**
		 * 重定向到另一頁面,url會改變
		 */
		if ("/test_redirect".equals(path)) {
			resp.sendRedirect("/webDemo/test_html.do");
		}

		/**
		 * 轉發到另一頁面,url不變 轉發後依然可以獲取到request,response中的參數
		 */
		if ("/test_dispatcher1".equals(path)) {
			req.setAttribute("msg", "share request attribute");
			RequestDispatcher rd = req.getRequestDispatcher("/webDemo/test_dispatcher2.do");
			rd.forward(req, resp);
		}

		/**
		 * 轉發到另一頁面,url不變 轉發後依然可以獲取到request,response中的參數
		 */
		if ("/test_dispatcher2".equals(path)) {
			resp.setContentType("text/html");
			String msg = (String) req.getAttribute("msg");
			PrintWriter out = resp.getWriter();
			out.println("<span style='color:red'>" + msg + "</span>");
			out.flush();
			out.close();
		}

		/**
		 * get請求,傳遞參數
		 */
		if ("/test_get_params".equals(path)) {
			// 1,設置字符以什麼樣的編碼輸出到瀏覽器
			resp.setCharacterEncoding("utf-8");
			// 2,獲取輸出流
			PrintWriter out = resp.getWriter();
			// 3,通過設置響應頭控制瀏覽器以UTF-8的編碼顯示數據,如果不加這句話,那麼瀏覽器顯示的將是亂碼
			resp.setHeader("content-type", "text/html;charset=UTF-8");

			String name = req.getParameter("name");
			Integer age = Integer.parseInt(req.getParameter("age"));

			out.println("<span>" + name + "的年齡是:</span><span style='color:red'>" + age + "</span>");
			out.flush();
			out.close();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		

	}

}

這裏說明一下:

1)  一般寫一個servlet都是繼承HttpServlet,因爲HttpServlet實現了Servlet的service方法,當請求到達時,會自動根據請求類型匹配,

所以這裏我們只需要根據請求類型實現doGet,doPost 方法就即可,

2) 避免請求響應中文亂碼,這裏需要設置統一編碼爲“utf-8”,

3) 回顧http協議定義的數據格式,get請求的請求參數是放在url後面的, 

4) 寫好的servlet 需要在web.xml中配置映射,當請求到達時,服務器會根據我們填寫的映射路徑找到相對應的servlet類

三,web.xml 配置 servlet 映射

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <servlet>
  	<servlet-name>HelloServlet</servlet-name>
  	<servlet-class>com.example.servlet.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>HelloServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
</web-app>
這裏的映射路徑我們填寫的是“*.do”,表示以“.do”結尾的路徑都可以訪問。
四,啓動訪問:

1) http://localhost:8088/webDemo/test_html.do ====== 返回響應:hello servlet

2) http://localhost:8088/webDemo/test_redirect.do ====== 重定向到/test_html.do,同樣返回響應:hello servlet

3) http://localhost:8088/webDemo/test_dispatcher1.do ======= 轉發到/test_dispatcher2.do ,返回響應:share request attribute

4) http://localhost:8088/webDemo/test_get_params.do?name=張三&age=33 ====== 傳遞參數,返回響應:張三的年齡是:33

===============================================================================================================

get請求介紹到這裏,接下來我們來演示post請求,post請求的請求參數是放在消息體裏面的,我們在頁面使用表單提交方式

五,在webapp目錄下新建login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form id="form" action="/webDemo/login.do" method="post">
<label>用戶名</label>
<input type="text" id="name" name="name" />
<br/>
<label>密碼</label>
<input type="text" id="password" name="password" />
<br/><br/>
<button οnclick="function(){document.getElementById('form').submit();}">登錄</button>
</form>
</body>
</html>
六,實現doPost方法
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//設置請求參數編碼
		req.setCharacterEncoding("utf-8");
		
		String uri = req.getRequestURI();
		String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf(".do"));
		
		/**
		 * 表單提交post請求
		 */
		if ("/login".equals(path)) {
			//設置響應格式
			resp.setContentType("text/html");
			resp.setCharacterEncoding("utf-8");
			
			String name = req.getParameter("name");
			String password = req.getParameter("password");
			
			//獲取輸出流
			PrintWriter out = resp.getWriter();
			if (name.equals("李四") && password.equals("123")) {
				out.println("<span>登錄成功</span>");
			} else {
				out.println("<span>用戶名或密碼錯誤</span>");
			}
			
			out.flush();
			out.close();
		}
	}

七,啓動測試:http://localhost:8088/webDemo/login.html ==== 響應成功

八,post請求我們演示了表單提交的方式,從servlet中我們是通過參數名從request對象中獲取的,

這裏有一篇博客寫的很好,詳細說明了五種獲取參數的方式,大家可以都試一下,深入理解。

博客地址:http://www.cnblogs.com/zhanghaoliang/p/5622900.html

九,從servlet版本3.0以後支持註解的方式標註請求路徑,不需要在web.xml中配置了,下面我們來看一下。

新建測試servlet:

package com.example.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 使用servlet3.0提供的註解
 * @author Administrator
 *
 */
@WebServlet(urlPatterns="/simple/servlet")
public class SimpleServlet extends HttpServlet{

	private static final long serialVersionUID = 5776879605113453644L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().println("...............");
	}
}
啓動訪問:

=============================================================================

其他註解大家自行學習測試吧,下篇,我們重點來學習,java_web 學習記錄(三):ajax









發佈了50 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章