這個例子不錯,整理一下:本文主要描述servlet當中如何向台jsp頁面傳值,本例傳值部分分為三個部分,1 傳入一般字元串 2 傳入普通List 3 傳入帶有多個Map的list,頁面對傳入的值通過jstl和el運算式來進行處理。
1. 開始頁面jspservletjstl.jsp-----jsp頁面負責顯示
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" %> <html> <head> <title>jsp頁面</title> </head> <body> <FORM action="gojstl" method="post"> <input type="text" name="username"> <input type="submit"> </FORM> </body> </html>
2. web.xml配置-------web.xml檔案中包括了:<context-param>用來配置容器(Tomcat)初始化參數。<servlet>配置servlet名稱與類的關聯,以及該servlet所處理的內容。listener配置容器對事件的響應,如org.springframework.web.util.IntrospectorCleanupListener
<!-- jsp與jstl測試 --><servlet> <servlet-name>gojstl</servlet-name> <servlet-class>second.Gojstl</servlet-class>//類的位置</servlet><servlet-mapping> <servlet-name>gojstl</servlet-name> <url-pattern>/gojstl</url-pattern> //處理去往/gojstl路徑的訪問請求</servlet-mapping>
3. servlet類的處理---------servlet主要包括兩個方法,doGet和doPost。容器根據表單的不同來選擇使用哪個方法,get與post的請求就不說了。關於getParameter與getAttribute的區別見點擊開啟連結。關於forward與sendRedirect的區別見點擊開啟連結
package second;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class Gojstl extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); request.setAttribute("username",username);//向session中寫入String參數 Map map1 = new HashMap(); map1.put("username",username+1); map1.put("idcard","111111111111111111"); Map map2 = new HashMap(); map2.put("username",username+2); map2.put("idcard","2222222222222222222"); List list1 = new ArrayList(); list1.add(map1); list1.add(map2); List list2 = new ArrayList(); list2.add("map1"); list2.add("map2"); request.setAttribute("pagelist1",list1); request.setAttribute("pagelist2",list2);//同樣,寫入list參數 this.getServletContext().getRequestDispatcher("/showresult.jsp") .forward(request, response);//頁面跳轉 //response.sendRedirect("finish.jsp"); } }
4. 顯示處理頁面showresult.jsp----------JSTL是JSP的一個標籤庫,方便了JSP檔案的編寫。
<%@ page language="java" contentType="text/html; charset=UTF-8" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html><head><title>jstl的jsp寫法後台傳值</title></head><body><c:if test="${username == 'shane'}">判斷成功<br></c:if><c:forEach var="bl" items="${pagelist1}"> ${bl.username} ${bl.idcard} <br> </c:forEach><c:forEach var="b2" items="${pagelist2}"> ${b2} <br> </c:forEach></body></html>