Java Servletを使用したログイン
Q&A
Closed
解決したいこと
JavaでJSPよりinput formで入力した情報でログインしたいのですが
session.Attributeのuserが毎回nullになります。
コードが多くなり申し訳ございません。
解決方法を教えて下さい。
発生している問題・エラー
エラーは出ておりません
Servlet
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(true);
String email = req.getParameter("email");
String password = req.getParameter("password");
try(Connection connection = DataSourceManager.getConnection()){
UserDao dao = new UserDao(connection);
UserDto user = dao.login(email, password);
session.setAttribute("user", user);
if(user == null) {
resp.sendRedirect("/weekend/login");
return;
}
resp.sendRedirect("/weekend");
}
}
DAO
public class UserDao {
protected Connection connection;
public UserDao(Connection connection) {
this.connection = connection;
}
public UserDto login(String email, String password) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT");
sb.append(" ID");
sb.append(" ,EMAIL");
sb.append(" ,NAME");
sb.append(" FROM USERS");
sb.append(" WHERE EMAIL = ?");
sb.append(" AND PASSWORD = ?");
try(PreparedStatement ps = connection.prepareStatement(sb.toString())){
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
UserDto user = new UserDto();
user.setId(rs.getInt("ID"));
user.setEmail(rs.getString("EMAIL"));
user.setName(rs.getString("NAME"));
return user;
}
return null;
}
}
jsp
<form action="login" method="post">
<div>
<label>E-mail</label>
<input type="text" name="email">
</div>
<div>
<label>Password</label>
<input type="password" name="password">
</div>
<div>
<button type="submit">Login</button>
<a href="/weekend">戻る</a>
</div>
</form>
DTO
setters getters処理はしております。
public class UserDto {
private int id;
private String email;
private String password;
private String name;
自分で試したこと
デバックをしたところemailやpasswordには値は入っています。
情報はSQLに入っています。
0 likes