Java Web笔记:Servlet跳转

客户端跳转

在Servlet中进行客户端跳转,直接调用HttpServletResponse中的sendRedirect()方法即可。
客户端跳转:
package com.zzh.Servlet;

import java.io.IOException;
import java.rmi.ServerException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.RepaintManager;

public class ServletClientRedirect extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServerException, IOException {
		req.getSession().setAttribute("name", "lunatictwo");
		req.setAttribute("info", "CSDN_blog");
		resp.sendRedirect("info.jsp");
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServerException, IOException {
		doGet(req, resp);
	}
}
配置web.xml
<servlet>
        <servlet-name>client</servlet-name>
        <servlet-class>com.zzh.Servlet.ServletClientRedirect</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>client</servlet-name>
        <url-pattern>/ServletClientRedirect</url-pattern>
    </servlet-mapping>
结果:
Java Web笔记:Servlet跳转_第1张图片
其中在客户端不能进行request属性的获取。

服务器端跳转

Servlet中没有jsp中的forward指令,因此要实现服务器端的跳转,必须依靠RequestDispatcher接口来完成。
使用服务器跳转:
package com.zzh.Servlet;

import java.io.IOException;
import java.rmi.ServerException;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.RepaintManager;

public class ServletServerRedirect extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServerException, IOException {
		req.getSession().setAttribute("name", "lunatictwo");
		req.setAttribute("info", "CSDN_blog");
		RequestDispatcher rd = req.getRequestDispatcher("info.jsp");
		try {
			rd.forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServerException, IOException {
		doGet(req, resp);
	}
}
配置web.xml
<servlet>
        <servlet-name>server</servlet-name>
        <servlet-class>com.zzh.Servlet.ServletServerRedirect</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>server</servlet-name>
        <url-pattern>/ServletServerRedirect</url-pattern>
    </servlet-mapping>

运行结果:

可以发现地址栏并没有变化,所以该跳转是服务器端跳转。











你可能感兴趣的:(Java Web笔记:Servlet跳转)