在Servlet内实现跳转
常见的Servlet内跳转有两种:
(1)重定向:对应JSP内置对象中的sendRedirect
respose.sendRedirect(“URL地址”);
(2)服务器内跳转:对应JSP中的forward标签
ServletContext application = this.getServletContext();
ServletContext application = this.getServletContext();
RequestDispatcher rd = application.getRequestDispatcher(“URL地址”);
rd.forward(request, response);
编写跳转Servlet
创建一个名为JumpServlet的Servlet
代码如下:
package cn.lystery.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JumpServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String user = "Lystery";//模拟用户
req.setAttribute("user", user);
ServletContext application = this.getServletContext();
RequestDispatcher rd = application.getRequestDispatcher("/index.jsp");
rd.forward(req, resp);
}
}
配置Servlet
配置代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>JumpServlet</servlet-name>
<servlet-class>cn.lystery.servlet.JumpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JumpServlet</servlet-name>
<url-pattern>/JumpServlet</url-pattern>
</servlet-mapping>
</web-app>
编写index.jsp界面
index.jsp页面存在于WebContent目录下
编写index.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>欢迎界面</title>
</head>
<body>
欢迎<br>
<%=request.getAttribute("user") %>
</body>
</html>
部署并测试JumpServlet
在地址栏输入http://localhost:8080/MyServlet/JumpServlet
发现已经跳转到index.jsp界面,显示出对应内容
使用重定向进行跳转
对JumpServlet进行如下更改
package cn.lystery.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JumpServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String user = "Lystery";//模拟用户
req.setAttribute("user", user);
resp.sendRedirect("index.jsp");
}
}
测试发现 当运行是 地址路径变成index.jsp但是传递的参数不见了 这就是两者的区别