0

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 :)

3 Answers 3

1

In case of JSP you can use session implicit object

<%= ((User) session.getAttribute("user")).getUsername %>
Sign up to request clarification or add additional context in comments.

Comments

0

You can retrieve value in your Home.html as below

<script type="text/javascript">
    $(document).ready(function() {
          userName = "{{user}}";
          $("#yourFieldName").val(userName);            
    });
</script>

Comments

0
  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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.