我正在尝试从我的servlet重定向到另一个页面,其中字符串值为null。当我运行代码时,它会保留在同一页面上,而不是重定向到我的错误页面。这是我的代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String emp = request.getParameter("emp")!=null ? request.getParameter("emp"): "";
MCenter mCenter = new MCenter();
mCenter = mCenterDAO.getMCenterPocByEmp(emp);
mCenter = mCenterDAO.getMCenterByObject(mCenter);
PrintWriter pw = response.getWriter();
String mPocName = mCenter.getMCenterPocName();
String mCenter = mCenter.getMCenterName();
if(mPocName == null || mCenter == null) {
request.getRequestDispacher("error.jsp").forward(request, response);
System.out.println("Null or not name " + mPocName + "center " + mCenter);
}
String json = getMCenterPoc(emp);
pw.print(json);
pw.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
我没有收到任何错误,打印输出给我null或值取决于是否有值。
答案 0 :(得分:1)
您必须在代码中进行以下更改。请求调度程序不能使用Ajax post。
src
或者您可以使用Ajax成功。通过这种方式,您不需要将代码更改为我的代码。 如果你想用Ajax做。
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String emp = request.getParameter("emp") != null ? request.getParameter("emp") : "";
MCenter mCenter = new MCenter();
mCenter = mCenterDAO.getMCenterPocByEmp(emp);
mCenter = mCenterDAO.getMCenterByObject(mCenter);
String mPocName = mCenter.getMCenterPocName();
String mCenter = mCenter.getMCenterName();
if (mPocName == null || mCenter == null) {
request.sendRedirect("error.jsp");
System.out.println("Null or not name " + mPocName + "center " + mCenter);
} else {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String json = getMCenterPoc(emp);
pw.print(json);
pw.close();
}
}
当然,您的servlet必须更改为以下内容。
var emp = $('#emp').val();
$.ajax({
type: "POST",
url: "yourServletName",
data: 'emp='+emp+'',
success: function(response) {
if(response='error'){
window.location.href='error.jsp';
}else{
//What you want
}
}
});
答案 1 :(得分:0)
您在UI中看不到任何内容,因为error.jsp
文件中没有任何内容(没有文字内容)。
您需要在 error.jsp 页面中添加一些文字:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
<p>Error has occurred!!!</p>
</body>
当您的请求转发到jsp / servlet / html时,并不意味着您的浏览器网址将被更改,只是您的请求将被转发到另一个资源以生成将发送给您的响应。该网址将保持不变。