简体   繁体   中英

Use Java variable in HTML File

I made a LoginServlet with Java, that gets username and password from a database. Now I want to display the username on my website after logging in.

Servlet Code: public class LoginServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {

   String username = req.getParameter("username");
   String password = req.getParameter("password");

    Sql2o sql2o = DatabaseConnetcionProvider.getSql2oConnection();

    User user = UserDAO.findBenutzerByUsername(username, sql2o);


    if(user != null && user.getPassword().equals(password)){

        UserListe.getInstance().add(user);
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        resp.sendRedirect("/public/Home.html");
    } else {
        resp.sendRedirect("/public/Error.html");
    }

}

}

Now I want to display the username on my Website.

I hope you can help me :)

如果是JSP,则可以使用会话隐式对象

<%= ((User) session.getAttribute("user")).getUsername %>

You can retrieve value in your Home.html as below

<script type="text/javascript">
    $(document).ready(function() {
          userName = "{{user}}";
          $("#yourFieldName").val(userName);            
    });
</script>
  1. if the page is static html page,the static page can not handle the servlet page scope data,use jsp or other dynamic page to handle it,freemarker,velocity is suitable.
  2. in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}. you should review the pageScope,requestScope,sessionScope,applicationScope concept.
  3. sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please.
  4. if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic.

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