马上考试java web了,慌得一批,于是将老师的代码拷过来进行测试,开始配环境就弄了很久,然后遇上了页面跳转404的问题。
背景介绍
在一个文件夹里面有两个jsp文件,用于页面注册信息,然后跳转查看页面信息,两个文件在同一目录下。
代码
reginput.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getRealPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>学员注册</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div align="center">请输入注册信息
<form name="form1" method="post" action="reginfo.jsp">
<table border="0" align="center">
<tr>
<td>用户名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td height="19">密码:</td>
<td height="19"><input type="password" name="pwd"></td>
</tr>
<tr>
<td>信息来源:</td>
<td>
<input type="checkbox" name="channel" value="报刊">报刊
<input type="checkbox" name="channel" value="网络">网络<br/>
<input type="checkbox" name="channel" value="朋友推荐">朋友推荐
<input type="checkbox" name="channel" value="电视">电视
</td>
</tr>
<!-- 以下是提交、取消按钮 -->
<tr >
<td colspan="2" align="center" >
<input type="submit" name="Submit" value="提交">
<input type="reset" name="Reset" value="取消">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
reginfo.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>注册信息</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
String[] channels = request.getParameterValues("channel");
%>
<div align="center">你输入的注册信息
<table border="0" align="center">
<tr>
<td width="80" height="20">用户名:</td>
<td><%=name%></td>
</tr>
<tr>
<td height="20">密码:</td>
<td><%=pwd%></td>
</tr>
<tr>
<td height="20">信息来源:</td>
<td >
<%
if (channels != null) {
for (String channel: channels) {
out.print(channel+" ");
}
}
%>
</td>
</tr>
</table>
</div>
</body>
</html>
问题解决
此处点击提交之后,本应该是一个查看刚刚注册信息的页面,但是却成了404
问题就出在request.getContextPath()
这个函数找到相对路径,可返回站点的根路径
将相对路径修改位绝对路径request.getRealPath("/"),就可以了