Login.jsp <%@ page contentType="text/html;charset=UTF-8" import="java.sql.*, javax.naming.*, javax.sql.*" %> <!DOCTYPE html> <html> <link rel="stylesheet" type="text/css" href="CSS/Login.css"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ログイン</title> </head> <body> <FORM method="POST" action= "${pageContext.request.contextPath}/Login"> <h1>ログイン</h1> ID<br> <INPUT type="text" name="number"><br><br> パスワード<br> <INPUT type="password" name="password"><br><br> <INPUT type="submit" value="ログイン" name="login"><br> <span class="label label-danger">${ErrMsg}</span> </FORM> </body> </html>
Login.java package webApplication; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; @WebServlet("/Login") public class Login extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ String num = request.getParameter("number"); String pass = request.getParameter("password"); System.out.println("number:"+ num); System.out.println("password:"+ pass); Connection db = null; java.sql.PreparedStatement ps = null; ResultSet rs = null; try { Context context = new InitialContext(); DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/kensyu"); db = ds.getConnection(); ps = db.prepareStatement("SELECT * FROM Test"); rs = ps.executeQuery(); HttpSession session = request.getSession(true); while(rs.next()) { if(num.equals(rs.getString("Test_id")) == true && pass.equals(rs.getString("password")) == true) { session = request.getSession(true); response.sendRedirect("EmpInfoServlet"); return; }else{ request.setAttribute("ErrMsg", "IDかパスワードが違います。"); RequestDispatcher dispatch = request.getRequestDispatcher("/Login.jsp"); dispatch.forward(request, response); return; } } }catch(NamingException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }finally { try { if(rs != null){rs.close();} if(ps != null){ps.close();} if(db != null){db.close();} }catch(SQLException e) { e.printStackTrace(); } } return; } }
データベースを照合してログイン画面を作って次のページへ~という処理をしたいのですが
このソースコードで実行してみるとデータベース上の一番上のデータしか
照合できず、他のデータはログイン出来なくなってしまいました。
まだJavaを初めて1ヶ月未満ですので、説明不足だと思いますが
何かアドバイスなどありましたら、よろしければご教授いただきたい所存です。
よろしくお願いいたします。
開発環境 Eclipse
サーブレット Tomcat
データベース MySQL
回答1件
あなたの回答
tips
プレビュー