在做作业时,第一项任务严格地与servlet有关,然后在servlet之间传递值时,session.setAttribiute
和session.getAttribiute
工作正常。但由于使用servlet和jsp,我遇到了空值的问题。这是有问题的代码
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>
然后,在登录并重定向到index.jsp之后,我有Welcome的空白和注销按钮。有什么帮助吗?
对不起,伙计们,我只是Java太差了,仅此而已。我不知道当您想在JSP中输出值时,需要使用<%= %>
标记,而不是用于逻辑的<% %>
。