请求转发和重定向:
//请求转发
//request.getRequestDispacher(地址).forward(请求对象,响应对象)
/*
特点:
1)整个过程一次请求
2)地址栏不会发生变化
3)不能访问外部资源
4)效率高
5)绝对路径 绝对路径的/代表的是根目录之后的根
6)请求转发之后的代码会继续执行 所以习惯性在后面添加一个return 语句
*/
//相对路径
// request.getRequestDispatcher("requestServlet2").forward(request, response);
//绝对路径
// request.getRequestDispatcher("/requestServlet2").forward(request, response);
// request.getRequestDispatcher("http://www.baidu.com").forward(request, response);
// return;
//重定向
//response.sendRedirect(地址);
/*
特点:
1)整个过程两次请求
2)地址栏会发生变化
3)能访问外部资源
4)效率偏低
5)绝对路径 绝对路径的/代表的是端口号之后的根
6)习惯性在后面添加一个return 语句
*/
// response.sendRedirect("requestServlet2");
// response.sendRedirect("http://www.baidu.com");
// response.sendRedirect("/RequestWeb2/requestServlet2");
//推荐绝对路径写法
response.sendRedirect(request.getContextPath()+"/requestServlet2");
在jsp页面中:
//使用EL表达式${pageContext.request.contextPath}获取项目绝对路径根目录相当于/webroot
<form id="userForm" action="${pageContext.request.contextPath}/user" method="get">
username: <input type="text" name="username"> <br>
age: <input type="text" name="age"> <br>
email: <input type="text" name="email"> <br>
<button type="submit" id="userSubmit">提交</button>
</form>
action中使用${pageContext.request.contextPath}
如果JSP页面中有basePath:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//request.getContextPath()获取根目录,即/根目录名,我的是/apartment
String path = request.getContextPath();
/*request.getScheme()获取协议http,
request.getServerName()获取服务器名字,本例中是localhost
request.getServerPort()获取服务器端口号,我的是8080
path即上面的根目录/apartment
basePath = http://localhost:8080/apartment/
这个语句是用来拼装当前网页的相对路径的。
<base href="...">是用来表明当前页面的相对路径所使用的根路径的。
比如,页面内部有一个连接,完整的路径应该是 http://localhost:8080/apartment/resident/addResident.jsp
其中http://server/是服务器的基本路径,apartment是当前应用程序的名字,那么,我的根路径应该是那么http://localhost:8080/apartment/。
有了这个 <base ... >以后,我的页面内容的连接,我不想写全路径,我只要写 resident/addResident.jsp就可以了,注意不加/
服务器会自动把 <base ...>指定的路径和页面内的相对路径拼装起来,组成完整路径。
如果没有这个 <base...>,那么我页面的连链接就必须写全路径,否则服务器会找不到,没有就写上面写到的
全路径EL表达式${pageContext.request.contextPath}/resident/addResident.jsp
*/
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>住户列表</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="css/resident.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/resident/add.js"></script>
</head>