簡単なログインページを作成しようとしています。ここに私のコードは次のとおりです。ServletとMysqlを使用した単純な認証
サーブレット:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/MySQLConnect")
public class MySQLConnect extends HttpServlet {
private static final long serialVersionUID = 1L;
//do post method calling
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo", "root", "admin");
//prepared statement for calling query
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
} catch (Exception e) {
e.printStackTrace();
}
finally{}
}
}
のindex.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="MySQLConnect">
UserName :<input type="text" name="user" /><br/><br/>
Password :<input type="password" name="pass" /><br/><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
のWeb.xml
<display-name>AuthenticationUsingMySQL</display-name>
<servlet>
<servlet-name>MySQLConnect</servlet-name>
<servlet-class>MySQLConnect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MySQLConnect</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
私は
http://localhost:8080/AuthenticationUsingMySQL/Login
を使用してページを開くしようとしています。しかし、あなたが直接あなたのwebservletなどのブラウザでTE URLを使用することはできません。このURL
同時にアノテーションベースのサーブレット設定@WebServletとweb.xmlの両方があります。なぜですか? – rkosegi
ログインページについては、http:// localhost:8080/AuthenticationUsingMySQL/index.htmlを呼び出してください。ログインフォームが表示されます。ポストを介してフォームを提出する場合は、サーブレットを呼び出す必要があります。多分あなたはいくつかのURLを修正/チェックする必要があります。 –