JSP页面重定向后,JavaScript无法运行....任何解决方案?

时间:2015-02-28 18:39:49

标签: javascript jsp servlets

以下是代码:

<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
    con = DataSource.getInstance().getConnection();
    String sql = "select userid,password from users where userid=? and password=?";
    pstmt = con.prepareStatement(sql);
    pstmt.setString(1, username);
    pstmt.setString(2, password);
    rs = pstmt.executeQuery();
    if(!rs.isBeforeFirst())
    {
        response.sendRedirect("login.jsp");
        %>

        <script type="text/javascript">
            var x = document.getElementById("errorbox");
            alert(x);
            x.style.display = "block";
            x.innerHTML = "Ooops...User doesn't exist!!";
        </script>
        <%
    }
}
catch(Exception e)
{
    e.printStackTrace();
}
%>

这是项目的目录结构..

WebContent  
|  
|---Meta-Inf  
|  
|---resources  
|      |____CSS  
|      |____JS  
|      |____images  
|---Web-Inf  
|  
|-----login.jsp  
|-----verify.jsp

资源文件包含用于存储css,javascript和图像资源的css,js和images文件夹。所有.jsp文件都在WebContent目录下。

当用户无法通过身份验证时,我使用sendRedirect(“login.jsp”)并在该页面上有div元素,其display属性设置为none。所以我想使用JavaScript来设置要显示的属性:block。但重定向后JavaScript无法正常工作。

1 个答案:

答案 0 :(得分:0)

Javascript代码绑定到一个网页。

当您在代码示例中发送Javascript代码时,您将其添加到当前在JSP中构建的页面,在本例中为verify.jsp(我想)。然后,浏览器会收到此代码以及将用户重定向到login.jsp的请求。

当它执行此操作时,verify.jsp页面将被卸载,并包含其中包含的所有Javascript代码。如果您希望在目标网页login.jsp上执行Javascript代码,则必须在此页面中添加。

如果您希望将登录页面的验证和呈现保存到不同的文件中,则必须在您重定向到的URL中包含先前登录失败的信息,例如:< / p>

response.sendRedirect("login.jsp?loginfailed=1");

并在login.jsp

中查看此内容
if (request.getParameter("loginfailed") == "1") {
    %>
    <div id="errorbox">
        Ooops...User doesn't exist!!
    </div>
    <%
}