1. 程式人生 > >jsp前後端互動以及請求轉發和請求包含

jsp前後端互動以及請求轉發和請求包含

request物件 作用: 獲得請求引數:
請求方式:

API: 獲得引數:

  • 前後端互動 涉及到前後端互動的都很重要

getParameter(“name”); 能夠獲得前段頁面提交的引數:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

getParameterValues(java.lang.String name)

Returns an array of String objects containing all of the values the given request parameter has,
or null if the parameter does not exist.
java.util.Map<java.lang.String,java.lang.String[]> getParameterMap()
Returns a java.util.Map of the parameters of this request.

jar包: commons-beanUtils.jar 依賴於
commons-logging.jar
jar包的依賴!

一般的通過物件獲取資料

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

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

/**
 * Servlet implementation class AServlet
 *  使用get 提交的方式: 完成引數的獲取: 
 *  
 *  getParameter(); 
 */
public class AServlet extends HttpServlet {
	

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
	    //核心的程式碼: 
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		PrintWriter out = response.getWriter();
		
		out.println("<font color='red'>"+username+"</font>");
		out.println("<font color='red'>"+password+"</font>");
		out.close(); 
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		//doGet(request, response);
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		PrintWriter out = response.getWriter();
		
		out.println("<font color='red'>"+username+"</font>");
		out.println("<font color='red'>"+password+"</font>");
		
//		=======================================
//		獲得同一個引數的名稱對應多個值的情況: 
		String[] values = request.getParameterValues("hobby");
		System.out.println(Arrays.toString(values));
		
		for (int i = 0; i < values.length; i++) {
			String val = values[i]+",";
			System.out.print(val);
		}
		
//		=======================================
		out.close(); 
	
	}

}

用javabean封裝前端傳過來的資料

import java.io.Serializable;
import java.util.Arrays;

/*
 * javaBean 
 * 滿足: 
 *  必須屬性: set/get後邊的內容稱之為屬性: 
 *  必須提供無引數的構造器: 
 *  最好: 提供實現Serializable 介面: 
 */
public class User implements Serializable {
	
	
	private static final long serialVersionUID = 1L;
	
	private String username; 
	private String password; 
	private String hobbies[];
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String[] getHobbies() {
		return hobbies;
	}
	public void setHobbies(String[] hobbies) {
		this.hobbies = hobbies;
	}
	/**
	 * @param username
	 * @param password
	 * @param hobbies
	 */
	public User(String username, String password, String[] hobbies) {
		super();
		this.username = username;
		this.password = password;
		this.hobbies = hobbies;
	}
	/**
	 * 
	 */
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", hobbies=" + Arrays.toString(hobbies) + "]";
	} 
	
	
	
}

使用jar包封裝資料

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.yidongxueyuan.domain.User;

/**
 * Servlet implementation class BServlet、
 * 將前段頁面提交的引數 封裝到map集合當中: 
 */
public class BServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//將獲得的的資料:
//		獲得前段的引數封裝map 集合當中: 
		Map<String, String[]> map = request.getParameterMap();
		System.out.println(map);
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		doGet(request, response);
		
		/*
		 * 提交的引數: 封裝javaBean  物件當中: 
		 */
//		獲得前段頁面的引數: 
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String[] values = request.getParameterValues("hobby");
		
		//準備一個javaBean物件: 
		User user = new User(); 
		user.setUsername(username);
		user.setPassword(password);
		user.setHobbies(values);
		
		
		System.out.println(user);
		System.out.println("======");
		doPost02(request,response); 
	}
	
	//使用jar包 : 快速的封裝資料: 
	/*
	 * 使用jar包;快速的封裝資料: 
	 * 物件當中的屬性和 前段提供的屬性必須一致: 
	 */
	public void doPost02(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    try {
	    	   Map<String, String[]> map = request.getParameterMap();	
	    	   //Apache組織提供了一個jar : commons元件: 
	    	   User user = new User();
			   BeanUtils.populate(user, map);
			   System.out.println(user);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}`在這裡插入程式碼片`

  • 請求轉發和請求包含:

重定向的原理:
重定向的第二次: 一定是get :
請求轉發和請求包含原理:
(1)一次請求,一次響應。
(2)位址列不會發生變化。 顯示的是第一次請求的地址。
(3)伺服器端的行為。
(4)只能轉發到站內資源。
(5)請求轉發對AServlet和BServlet的請求方法是相同的,即要麼都是GET,要麼都是POST,因為請求轉發是一個請求;

程式碼的實現:
CServlet: 負責轉發的Servlet
DServlet: 被轉發過來的Servlet:

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CServlet
 * 演示: 請求轉發: 
 */
public class CServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//負責轉發的Servlet: 
		
		//獲得一個請求分配器: 
//		RequestDispatcher dis = request.getRequestDispatcher("DServlet");
//		
//		//轉發到DServlet: DServlet 和CServlet 共享的是同一個request物件。 
//		dis.forward(request, response);
		
		
		//解決亂碼的相應頭資訊: 
		response.setHeader("content-type", "text/html;charset=utf-8");//告知客戶端瀏覽器 使用utf-8解析: 
		response.setCharacterEncoding("utf-8");// 設定響應輸出流的編碼是utf-8
		
		response.getWriter().println("this is CServlet....");
		
		//完成了請求轉發:
		request.getRequestDispatcher("/DServlet").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	
	}

}

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 被轉發過來的Servlet: 
 */
public class DServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//響應內容: 
		
		response.getWriter().println("轉發過來的DServlet......xxx");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

請求包含程式碼實現:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 負責請求包含的Servlet : 
 */
public class EServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("FServlet").include(request, response);
		//解決了響應亂碼的問題: 
	/*	response.setHeader("content-type", "text/html;charset=utf-8");//告知客戶端瀏覽器 使用utf-8解析: 
		response.setCharacterEncoding("utf-8");// 設定響應輸出流的編碼是utf-8
*/	   
		//設定頭: 
		response.setHeader("xxx", "mrguo");
		response.getWriter().println("負責包含的servlet .....E");;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FServlet
 * 這是被轉發過來的FServlet: 
 */
public class FServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解決了響應亂碼的問題: 
				response.setHeader("content-type", "text/html;charset=utf-8");//告知客戶端瀏覽器 使用utf-8解析: 
				response.setCharacterEncoding("utf-8");// 設定響應輸出流的編碼是utf-8
		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.getWriter().println("這是被請求包含過來的Servlet.......F");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

- 請求轉發和請求包含之間的區別:

相同點:原理相同
a: 轉發:負責轉發的servlet 留頭不留體: 設定的響應頭生效, 設定的響應體 不生效。
在上面的程式碼中c servlet的請求體沒有響應
b: 包含:負責包含的Servlet 留頭又留體: