servlet 向jsp传值 request接收不到对象


在页面中,servlet通过forward向jsp传送request和response,但是在jsp和servlet中打印request,已经更换。通过session传递可以接收到值,但是第二次赋值接受不到。
servlet代码:

   
  public class CheckUserAction extends HttpServlet {
  
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
try {
boolean flag = UserBizFactory.getUserBiz().isUsedUsername(username);
System.out.println(flag);
// request.setAttribute("isUsedUsername", flag);
request.getSession().setAttribute("isUsedUsername", flag);
request.getRequestDispatcher("/register.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

jsp代码:

   
  function check(){
  
var XMLRequest=null;
if(window.XMLHttpRequest){
XMLRequest=new XMLHttpRequest();
}else{
XMLRequest=new ActionXObject("Microsoft.XMLHTTP");
}
if(XMLRequest){
XMLRequest.onreadystatechange=function(){
if(XMLRequest.readyState==4){
return;
}
};
XMLRequest.open("post", "/SJWEBService/checkUserAction", true);
var msg="username="+username;
XMLRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XMLRequest.send(msg);
}
<%-- var flag=<%= request.getAttribute("isUsedUsername")%>; --%>
var flag=<%=request.getSession().getAttribute("isUsedUsername")%>;
alert(flag);
if(flag){
document.getElementById("checkUsername").innerText="用户名重复";
return false;
}else{
document.getElementById("checkUsername").innerText="用户名可用";
return true;
}
return false;
}

HTML代码:

   
  <form action="registerAction" method="post">
  
<table align="center">
<tr>
<td>username:</td>
<td><input name="username" id="username" type="text"
onchange="check()"></td>
<td style="color: red; width: 40%;" id="checkUsername">*</td>
</tr>
</table>
<input id="submit" type="button"value="submit">
</form>

求高手求大神~~~

servlet JSP

想死1遍吗 11 years, 9 months ago

代码就一个字:乱;JSP跟JS搞在一起,什么情况?
问题没找到,但是找到一个可能出BUG的地方,
var flag=<%=request.getSession().getAttribute("isUsedUsername")%>;
这个地方,应该是想通过JAVA脚本获取变量的值然后给JS对象吧,而且这个值应该是个字符串,那字符串应该加引号吧
var flag="<%=request.getSession().getAttribute("isUsedUsername")%>";
试试这样,再找问题吧

雾雨魔理纱 answered 11 years, 9 months ago

Your Answer