I am developing a login function by passing json object to servlet for validation. If the login/password match with DB. The page will redirect to a LoginOK page with the login ID and corresponding profile. Or redirect to an error page if login fail. Here my coding:
jsp:
function submitForm(thisObj, thisEvent) {
var sLogin = $('#userName').val();
var myData = {
"userName": sLogin
};
$.ajax({
type: "POST",
url: "login",
data: JSON.stringify(myData),
dataType: "json"
});
return false;
}
servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
int iCnt = iHitCnt++;
res.setContentType("application/json");
PrintWriter out = res.getWriter();
StringBuffer sbuffer = new StringBuffer();
String inLine = null;
String sUsername = "";
try{
BufferedReader reader = req.getReader();
while ((inLine = reader.readLine()) != null)
sbuffer.append(inLine);
if (sbuffer.length() != 0){
JSONObject jsObj = new JSONObject(sbuffer.toString());
sUsername = jsObj.optString("userName");
}
}catch(Exception e){
return;
req.setAttribute("ID",sUsername);
RequestDispatcher rd = req.getRequestDispatcher("ok.jsp");
rd.forward(req, res);
}
}
LoginOK.jsp:
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<%@ page language="java" contentType="text/html; charset=big5"%>
<%
String sRemoteAddr="";
String sID="";
session = request.getSession(true);
try {
sRemoteAddr=(String)request.getRemoteAddr();
sID=(String)request.getAttribute("ID");
} catch (Exception e) {
application.log("err");
}
%>
<font size=20><%= sID%></font>
</body>
</html>
But the RequestDispatcher.forward(req,res) not working. The servlet ok to get the user input but fail to forward a new page. Anyone can give help which part of coding I'm wrong? Thanks.