Java教程

Java Web请求转发与重定向

本文主要是介绍Java Web请求转发与重定向,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

转发

①创建Servlet1 和Servlet2的Java文件

package zhuan;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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(value="/aaa")
public class Servlet1 extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//获取前台传过来的信息
		String username = req.getParameter("username");
		System.out.println(username);
		
		/***
		 * 1.请求转发必须以斜杠开头,斜杠表示http://ip:port/工程名/	。映射到web目录
		 * 2.※※※※※请求转发也可以转发到Web工程下:    req.getRequestDispatcher("/a/index.html");
		 * 	 ※※※※※需要注意的是 如果在a/index.html中存在超链接返回到另一个界面 通常需要使用base标签来设置当前页面的相对路径参照的地址
		 * 	 ※※※※※在<head></head>中定义<base href="http://localhost:8080/项目名/a/index.html">
		 */
		RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");
		
		requestDispatcher.forward(req, resp);
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
package zhuan;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet2 extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("我是Servlet2");
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}

②配置web.xml文件

<!-- servlet1 -->
<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-class>zhuan.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/servlet1</url-pattern>
</servlet-mapping>
	
<!-- servlet2 -->
<servlet>
    <servlet-name>Servlet2</servlet-name>
    <servlet-class>zhuan.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet2</servlet-name>
    <url-pattern>/servlet2</url-pattern>
</servlet-mapping>

重定向

 请求重定向的两种方式:

  • 方式一:设置响应头
resp.setStatus(302);
resp.setHeader("Location", "/response2");
  • 方式二:使用servlet提供的ap(推荐使用)
resp.sendRedirect("response2");

这篇关于Java Web请求转发与重定向的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!