servlet对于多页面共享信息提供四种方式。
1.url重写的方式
在下面的例子中,每一次请求都通过doGet方法进行“分流”。
如果在网址中含有参数city且不为空,就调用showAttribute()方法下所包含的servlet页面,如果没有该参数或该参数对应值为空,则调用mainPage()方法下的页面。
if (request.getParameter("city") != null){..............showAttribute(request, response, city, page);}esle showMainPage(request, response)
在执行showMainPage()方法中,可以通过选择选项,进行url重写
选择不同的选项,其后添加??city=london&page=1或者?city=pairs&page=1,url改写为localhost:8080/Rewrite?city=london&page=1或localhost:8080/Rewrite?city=pairs&page=1重新调用doGet方法,因为其含有city参数且不为空,不再调用showMainpage()方法,改为调用showAttribute(request, response, city, page)方法,实现了多页面共享信息的目的。
import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/Rewrite")public class Rewrite extends HttpServlet { private static final long serialVersionUID = 1L; public Rewrite() { super(); } ArrayListlondonAttr = new ArrayList<>(10); ArrayList pairsAttr = new ArrayList<>(10); public void init() throws javax.servlet.ServletException{ for( int i = 0; i < 10; i++) { londonAttr.add("l " + (i+1)); } for( int i = 0; i < 10; i++) { pairsAttr.add("p " + (i+1)); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getParameter("city") != null) { System.out.println("attribute"); String city = request.getParameter("city"); int page = 1; int p = 1; if (request.getParameter("page") != null){ try { p = Integer.parseInt(request.getParameter("page")); //showAttribute(request, response, city, page); }catch (NumberFormatException e) {} } page = p; showAttribute(request, response, city, page); }else showMainPage(request, response); } public void showMainPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println(" select a city " + "london
" + "
pairs
" + ""); } public void showAttribute(HttpServletRequest request, HttpServletResponse response, String city, int page) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("
" + city +" " + ""); if(city.equals("london")) { for (int i = 5 * (page-1) ; i < 5 * (page-1) + 5; i++) { pw.println("
"); if(page == 1) pw.println("next"); if(page == 2) pw.println("pass"); pw.println("city list"); pw.println(""); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}" + londonAttr.get(i) + " "); } }else if(city.equals("pairs")) { for (int i = 5 * (page-1) ; i < 5 * (page-1) + 5; i++) { pw.println(" " + pairsAttr.get(i) + " "); } } pw.println("