zoukankan      html  css  js  c++  java
  • Servlet 网页重定向

    TestServletRedirect.java

    // 文件路径 D:ApacheServerweb_javaHelloWorldsrccom	estTestServletRedirect.java
    package com.test;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class TestServletRedirect {
    
        public void testfun(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // 浏览器重新请求的新地址,URL会变,生成一个 302 响应,暂时性重定向到后面的网址
            String location = "https://www.baidu.cn" ;
            // 方法一
            //response.sendRedirect(location);
            // 方法二
            //response.setStatus(response.SC_MOVED_TEMPORARILY);
            //response.setHeader("Location", location);
            
            
            //请求转发到本地的一个 jsp 或 servlet 例如 /TestServlet2 ,网页 url 不变,返回状态码不变,页面改变,并把当前页面请求信息转发到新地址。index.jsp 路径为 D:ApacheServerweb_javaHelloWorldWebContentindex.jsp 与 WEB-INF 同级目录下
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        
        }
    }

    index.jsp

    <% // 文件路径 D:ApacheServerweb_javaHelloWorldWebContentindex.jsp %>
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%
        request.setCharacterEncoding("UTF-8");
        //get 或者 application/x-www-form-urlencoded post 方式
        String username = request.getParameter("username");//获取 username 值
        String password = request.getParameter("password");//获取 password 值
        if ("admin".equals(username) && "admin".equals(password)) { // 用户名密码都为 admin
            //session.setAttribute("username", username);//在会话中保留 username 值供之后的页面调用
            request.getRequestDispatcher("login_success.jsp").forward(request, response);//请求转发,网页url不变,页面内容改变
        } else {
            response.sendRedirect("login_failure.jsp");//重定向请求,网页url变
        }
    %>
  • 相关阅读:
    053364
    053363
    oracle导出批量表N行记录
    053362
    053361
    053360
    053359
    053358
    053357
    053356
  • 原文地址:https://www.cnblogs.com/dreamhome/p/11486563.html
Copyright © 2011-2022 走看看