【发布时间】:2016-11-04 16:43:55
【问题描述】:
我正在尝试创建简单的登录页面。这是我的代码:
Servlet:
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
但是这个网址显示HTTP Status 405 - HTTP method GET is not supported
【问题讨论】:
-
你同时拥有基于注解的 servlet 配置 @WebServlet 和 web.xml,为什么?
-
请致电localhost:8080/AuthenticationUsingMySQL/index.html获取登录页面。这应该显示登录表单。通过 post 提交表单应该调用您的 servlet。也许你需要修复/检查一些网址。