Issue
while working on my homework first tasks were about servlets strictly and then when passing values between servlets the session.setAttribiute
and session.getAttribiute
worked OK. But since using servlets and jsp I have problems with empty values. Here's the code in question.
Servlet:
@WebServlet(name = "SubmitLoginServlet", value = "/submitLogin")
public class SubmitLogin extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Connection con = DatabaseConnection.initDatabase();
Statement statement = con.createStatement();
String sql = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String DBusername = resultSet.getString("name");
String DBpassword = resultSet.getString("password");
if(DBusername.equals(username) && DBpassword.equals(password)) {
request.getSession().setAttribute("username", "test");
// I USED "TEST" JUST FOR TESTING, STILL THE VALUE ON 'INDEX.JSP' IS EMPTY
request.getRequestDispatcher("/index.jsp").forward(request,response);
// response.sendRedirect("index.jsp");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// INDEX.JSP - pasted in this block because of bug with code formatting, sorry
// on top of the file I have <%@ page session = "false" %>
<div class="column is-one-fifth is-offset-two-fifths">
<%
HttpSession session = request.getSession(true);
if(session.getAttribute("username") == "" || session.getAttribute("username") == null) {
%>
<form action="register.jsp">
<button type="submit" class="button is-info is-fullwidth">Signup</button>
</form>
<form action="login.jsp" method="get">
<button type="submit" class="button is-success is-fullwidth">Login</button>
</form>
<% } else { %>
<h1 class="title"> Welcome <% request.getSession().getAttribute("username"); %></h1>
<button class="button is-danger">Logout</button>
<% } %>
</div>
Then after login and redirecting to index.jsp i have Welcome with empty space and logout button. Any help?
Solution
Sorry guys, I'm just terrible at Java that's all. I didn't know that when you want to output values in JSP you need to use <%= %>
tags instead of <% %>
that is used for logic.
Answered By - Swagnar
Answer Checked By - Senaida (JavaFixing Volunteer)