Servlet<3>

来源:互联网 发布:ubuntu安装分区格式 编辑:程序博客网 时间:2024/06/05 10:58

客户端跳转vs服务器端跳转

客户端跳转

RedirectServlet.java

package com.ruanku.web;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class RedirectServlet extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {request.setAttribute("requestKey", "requestValue");HttpSession session=request.getSession();//获取sessionsession.setAttribute("sessionKey", "sessionValue");ServletContext application=this.getServletContext();//获取applicationapplication.setAttribute("applicationKey", "applicationValue");response.sendRedirect("target.jsp");//客户端跳转or重定向}}
target.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h1>目标地址</h1>request值:<%=request.getAttribute("requestKey") %><br/>session值:<%=session.getAttribute("sessionKey") %><br/>application值:<%=application.getAttribute("applicationKey") %><br/></body></html>

xml

<servlet-name>redirectServlet</servlet-name><servlet-class>com.ruanku.web.RedirectServlet</servlet-class></servlet><servlet-mapping><servlet-name>redirectServlet</servlet-name><url-pattern>/redirect</url-pattern></servlet-mapping>

request取不到值,而session和application都能取到值

response.sendRedirect("target.jsp");//客户端跳转or重定向
跳转的代码

服务器跳转 

只需要把上面那行代码改为

<pre name="code" class="java">RequestDispatcher rd=request.getRequestDispatcher("target.jsp");rd.forward(request, response);//服务器调转or转发

重新配置xml遍可以访问 能取到request的值 

而且地址栏不会发生改变而客户端跳转地址栏会变为跳转后的jsp页面的地址 

http://localhost:8080/chap05/target.jsp

0 0
原创粉丝点击