[JSP] 实现请求转发

2023-07-06 17:00:19 浏览数 (2)

在服务器端对客户端请求时行转发对其它的对象,如果jsp网页或Servlet

用三个 jsp网页来演示转发:

forword1.jsp, 用来提交表单, 将表单内容提交给 forwrod2.jsp,  forward1.jsp代码如下:

代码语言:javascript复制
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Forward1</title>
    </head>
    <body>
        <h1>Forward1</h1>
        <form action="forward2.jsp">
            姓名: <input type="text" name="username"/>
            <input type="submit" name="submit" value="提交"/>            
        </form>
    </body>
</html>

forward2.jsp 功能是将客户端的请求的内容转发给forward3.jsp, 然后将网页forward3.jsp返回给客户端, forward2.jsp的代码如下:

代码语言:javascript复制
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Forward2</title>
    </head>
    <body>
        <h1>Forward2</h1>
        <%
            RequestDispatcher rd = request.getRequestDispatcher("forward3.jsp");
            rd.forward(request, response);        
        %>
    </body>
</html>

forward3.jsp是用来返回给客户端的, 代码如下:

代码语言:javascript复制
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Forward3</title>
    </head>
    <body>
        <h1>Forward3</h1>        
        <%   
            String username = request.getParameter("username");
        %>        
        用户名为: <%=username %>        
    </body>
</html>

0 人点赞