简体   繁体   English

在HTML文件中使用Java变量

[英]Use Java variable in HTML File

I made a LoginServlet with Java, that gets username and password from a database. 我用Java制作了LoginServlet,它从数据库获取用户名和密码。 Now I want to display the username on my website after logging in. 现在,我想在登录后在我的网站上显示用户名。

Servlet Code: public class LoginServlet extends HttpServlet { Servlet代码:公共类LoginServlet扩展了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 您可以在Home.html中检索值,如下所示

<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. 如果该页面是静态html页面,则该静态页面无法处理servlet页面范围数据,请使用jsp或其他动态页面进行处理,freemarker,速度合适。
  2. in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}. 在jsp中,可以使用EL Express显示数据。格式为$ {sessionScope.user}。 you should review the pageScope,requestScope,sessionScope,applicationScope concept. 您应该查看pageScope,requestScope,sessionScope,applicationScope概念。
  3. sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please. sendRedirect方法可能导致pageScope中的数据丢失,请选择正确的范围,然后使用redirect或Forward方法进行测试。
  4. if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic. 如果页面是静态页面,请使用AJAX发送请求并处理数据,jQuery库是经典的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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