MENU

Catalog

response.sendRedirect () 的用法

September 20, 2018 • Read: 4015 • JSP阅读设置

sendRedirect()展开目录

response 和 request 一样都是 jsp 内置对象,request 是获取用户的请求,response 处理用户请求。sendRedirect () 函数的作用是重定向网页,向浏览器发送一个特殊的 Header,然后由浏览器来做重定向,转到指定的页面。下面我将创建四个页面,首先是 sex.jsp,有一个下拉列表和提交按钮确定,选择 “男”,就跳转到 male.jsp,选择 “女” 就跳转到 female.jsp,中间通过 sex_action.jsp 进行重定向

  • <!-- sex.jsp -->
  • <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  • <%
  • String path = request.getContextPath();
  • String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  • %>
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  • <html>
  • <head>
  • <base href="<%=basePath%>">
  • <title>Sex Select's page</title>
  • <meta http-equiv="pragma" content="no-cache">
  • <meta http-equiv="cache-control" content="no-cache">
  • <meta http-equiv="expires" content="0">
  • <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  • <meta http-equiv="description" content="This is my page">
  • </head>
  • <body>
  • <form action="<%=basePath%>c03/sex_action.jsp" method="post">
  • <select name="sex">
  • <option></option>
  • <option></option>
  • </select>
  • <button type="submit">提交</button>
  • </form>
  • </body>
  • </html>
  • <!-- sex_action.jsp -->
  • <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  • <%
  • String path = request.getContextPath();
  • String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  • %>
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  • <html>
  • <head>
  • <base href="<%=basePath%>">
  • <title>My JSP 'sex_action.jsp' starting page</title>
  • <meta http-equiv="pragma" content="no-cache">
  • <meta http-equiv="cache-control" content="no-cache">
  • <meta http-equiv="expires" content="0">
  • <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  • <meta http-equiv="description" content="This is my page">
  • </head>
  • <body>
  • <%
  • request.setCharacterEncoding("UTF-8");
  • String sex = request.getParameter("sex");
  • out.println(sex);
  • if("男".equals(sex)) {
  • response.sendRedirect("male.jsp");
  • return;
  • }
  • else if("女".equals(sex)) {
  • response.sendRedirect("female.jsp");
  • return;
  • }
  • %>
  • </body>
  • </html>
Last Modified: October 7, 2018
Archives Tip
QR Code for this page
Tipping QR Code