jsp中跳转servlet时候的相对路径问题。先看项目目录结构
jsp代码WebContent/admin/login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=ISO-8859-1">
<title>管理员登录</title>
</head>
<body>
<form action="../adminServlet?action=login" method="post">
<h1>管理员登录</h1>
<label>账号:</label> <input type="text" name="username" /> <br> <label>密码:<%=basePath%></label>
<input type="password" name="password" /><br> <input
type="submit" value="登录" />
<div>${requestScope.error}</div>
</form>
</body>
</html>
一般情况下, 我们在页面中使用资源(JSP. Servlet动态资源, 图片, css js 等静态资源)时, 都使用相对路径.
在form的action属性中:我们这里由于login.jsp在admin文件夹下,所以是
<form action="../adminServlet?action=login" method="post">
那为什么这样写?
action中形如: adminServlet?action=login, 或者./开始 以当前页面的访问路径作为根路径
http://localhost:8080/muke/admin/login.jsp->默认根路径:http://localhost:8080/muke/admin/
请求路径: http://localhost:8080/muke/admin/adminServlet?action=login
形如: /adminServlet?action=login, 以当前服务器的根路径作为相对路径的根路径
http://localhost:8080/muke/admin/login.jsp->默认根路径:http://localhost:8080/
请求: http://localhost:8080/adminServlet?action=login
形如:.. /adminServlet?action=login, 以当前路径的父路径作为根路径
http://localhost:8080/muke/login.jsp->默认根路径:http://localhost:8080/muke
http://localhost:8080/muke/adminServlet?action=login
servlet我们用注解的方法
它的路径,这样是在http://localhost/8080/muke/adminServlet.所以不管我们jsp在什么地方,我们只要根据jsp的相对路径匹配到http://localhost/8080/muke/下,就可以跳转到servlet,就是jsp请求路径为
http://localhost:8080/muke/adminServlet?action=login
《********************************************************************************************》
其实我们可以在用这样的方法,使得jsp中action就等于action=“adminServlet”.而不用加/或者./或者../等,就是我们不管jsp在哪里,把把jsp路径都改为绝对路径。
右键新建jsp页面,
然后next,不要点finish,我们来配置下模板
点击这里的jsp templates,然后
选中这一项,点击edit,编辑模板
<%@ page language="java" contentType="text/html; charset=${encoding}"
pageEncoding="${encoding}"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">
<base href="<%=basePath %>">
<title>Insert title here</title>
</head>
<body>
${cursor}
</body>
</html>
把这个粘进去,覆盖掉以前的所有。我们来说一下。
<%
String path = request.getContextPath();##获得当前目录名如这里是muke
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
request.getScheme():协议名,http。
request.getServerName():服务名,localhost。
request.getServerPort():端口号,8080。
path:目录名,muke。
<base href="<%=basePath %>">:用base标签,设置该jsp根目录为basePath里面的值,即http://localhost:8080/muke
这样我们在跳转时候,form里的action就不用费劲路径了,直接这样: