我一直在通过HTML页面调用servlet,而我的servlet代码如下:
import java.sql.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
public class validation extends HttpServlet
{
static PrintWriter pw = null;
public void doPost(HttpServletResponse response, HttpServletRequest request) throws ClassNotFoundException, SQLException, IOException, ServletException
{
pw = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
RequestDispatcher rd = request.getRequestDispatcher("new.html");
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/timetabledb", "root","`");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select password from users where username = '"+username+"';");
if(rs.next()==false)
{
pw.println("No such user found!");
}
else
{
if(password.equals(rs.getString("password")))
{
rd.forward(request, response);
}
else
{
pw.println("Invalid credentials!");
}
}
rs.close();
}
}
我的html页面是这样的:
<!DOCTYPE html>
<html>
<head>
<title>Login Page - SGMS</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
<div id = "container">
<div class = "welcome-head">
Welcome
</div>
<div class = "sw-head">
Semi-Automatic Schedule Generator & Maintenance Software
</div>
<span class="logo">
<img src="logo.gif" alt="Logo"/>
</span>
<div class = "form">
<form method="POST" action="validation">
<label for="inp-usr" class="inp">
<input type="text" name="username" id="inp-usr" placeholder=" " required="required">
<span class="label">Username</span>
<span class="border"></span>
</label>
<br>
<label for="inp-pwd" class="inp">
<input type="password" name="password" id="inp-pwd" placeholder=" " required="required">
<span class="label">Password</span>
<span class="border"></span>
</label>
<br><br><br>
<button class="validate-btn" onclick="show();">
Validate
</button>
</form>
</div>
</div>
</body>
</html>
但是问题是,每当我运行所有这些程序时,应用程序服务器就会说,该URL不支持POST方法。 我经常遇到此错误,请解释为什么发生所有这些错误。 我已经将servlet映射到了web.xml
谢谢。
答案 0 :(得分:1)
您在doPost
方法中犯了一个错误。您已将其声明为:
void doPost(HttpServletResponse response, HttpServletRequest request)
throws ClassNotFoundException, SQLException, IOException, ServletException
但正确的签名是这样:
void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
注意不同的参数顺序....
由于您的方法没有正确的签名,因此不会覆盖继承的版本。这意味着您的版本永远不会被调用。取而代之的是POST请求调用继承的方法...,并且该行为就是“不支持POST”。
解决方案:
doPost
方法的签名。 (例外情况也需要修复!)@Override
注释。@Override
的习惯……以便Java编译器可以向您指出错误。