目录

B 一个web资源收到客户端A请求后,B他会通知客户端A去访问另外一个web资源C ,这个过程叫重定向,
URL会变
requset请求的是转发,URL不变
常见场景:

这个方法是重定向

package com.kuang.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/r/img");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}


面试题:重定向与转发的区别
重定向: 别找我 转发: 我帮你去拿
相同点:页面都会实现跳转
不同点:
重定向:url会变
转发:url不会变

总结:1.转发是一次请求,重定向是两次2.转发不会改变url,重定向会改变3.请求转发是在服务器内部完成的,而重定向是在客户端完成的4.转发的url必须是当前web工程内部的地址,重定向可以是任意地址
index.jsp
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目下的路径--%>
<%--${pageContext.request.contextPath}代表请求当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
表单验证和获取参数
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目下的路径--%>
<%--${pageContext.request.contextPath}代表请求当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
package com.kuang.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username:"+username);
System.out.println("password:"+password);
resp.sendRedirect("/r/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

文章详细阐述了在Web开发中,Servlet如何处理重定向和转发。重定向是一种客户端跳转,URL会发生变化,而转发则在服务器端完成,URL保持不变。示例代码展示了如何在Servlet中实现重定向到内部资源。此外,还提到了表单验证和参数获取的过程。
1279

被折叠的 条评论
为什么被折叠?



