简体   繁体   中英

I am trying to pass a value from servlet file to javascript file and i am keep getting null where am i doing wrong?

I am trying to pass a value from servlet to js and keep getting null where am i doing it wrong?

login.java-servlet

if(bt.equals("frname")){
    String user =request.getParameter("frname");
    String requester=(String) session.getAttribute("uname");
    session.setAttribute("passingv", requester);
    try {
        if (UserDao.validateUser(user)==true) { 
            UserDao.insertvalues(requester,user);
            request.getRequestDispatcher("main.jsp").forward(request, response);
        } else {
            out.println(" <script type='text/javascript'> ");
            out.println("alert('User doesnot exists');");
            out.println("</script>");
            response.sendRedirect("main.jsp");    
        }
    } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

main.jsp

<%=(String)session.getAttribute("passingv")%>

main.js

var test = '<%=(String)session.getAttribute("passingv")%>';
console.log(test);

You're setting it in the session but attempting to retrieve it from the request.

Also, if it's an external JS file (eg, not in the JSP), there's no sense in trying to use a scriptlet in it. You may process JS files as JSP files, but this can lead to additional issues. You may want to consider exposing the value in the JSP and retrieving it later from the JS, but there are multiple ways to handle this requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM