我正在构建一个简单的Web应用程序并尝试创建登录页面。该页面包含一个带有加载Servlet的表单的JSP。
我已经使用GET方法运行表单了:
JSP看起来像这样:
<form method="get" action="Login">
Email:<input name="email"/>
Password:<input name="password"/>
<input type="Submit" value="Log in"/>
在Servlet中:
@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//Assign variables from the request parameters
String loginFormEmail = request.getParameter("email");
String loginFormPassword = request.getParameter("password");
此代码有效,但它包含URL字符串中的用户名和密码,因此显然不是很好的做法。我尝试使用POST来做这个,但我一直在收到错误。 (HTTP状态405 - 此URL不支持HTTP方法POST)
我需要知道如何使用POST将参数从JSP发送到Servlet。我认为这可能涉及使用RequestDispatcher对象,但我发现的所有教程都解释了使用RequestDispatcher将数据从Servlet发送到JSP,而不是相反。您是否可以使用Request Dispatcher将POST数据从JSP发送到Servlet?以及如何从Servlet访问这些参数? (对于POST,是否有相应的request.getParameter())
我知道使用POST仍然不安全,但是比在查询字符串中包含密码要好得多,我稍后会考虑安全性。
对于基本问题道歉,我在网上找到了很多教程,但似乎没有人回答这个具体问题。谢谢。
答案 0 :(得分:4)
尝试
<form method="POST" action="Login>
注意:method
代替type
来指定GET / POST。
但它并不比使用GET更“安全”。它们仍可在帖子正文中以明文形式提供。如果您希望它是安全的,请确保使用HTTPS。
修改强>
您现在已经修改了问题,看来您使用的是method
,而不是type
。因此,如果在将其更改为POST
后仍有错误,请指定您获得的错误。
<强> EDIT2 强>
您指定收到HTTP method POST is not supported by this URL
错误。这意味着您的servlet不接受POST
方法。这很可能意味着您继承了一些只接受GET
的基本servlet。查看servlet的所有代码会很有帮助。
答案 1 :(得分:0)
<form type="get" action="Login" method="POST">
Email:<input name="email"/>
Password:<input name="password"/>
<input type="Submit" value="Log in"/>
我建议您使用processRequest()
方法代替doPost()
。
答案 2 :(得分:0)
在元素中使用method =“POST”属性
答案 3 :(得分:0)
覆盖Login
类
HttpServlet#doPost()
方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
String loginFormEmail = request.getParameter("email");
String loginFormPassword = request.getParameter("password");
// do something to produce a response
}
这可能需要您更改可能被覆盖的service()
方法,无论HTTP方法如何,都可以调用processRequest()
方法。这取决于您未显示的Login
类实现的其余部分。
然后更改您的<form>
以发出POST
请求。
答案 4 :(得分:0)
尝试覆盖HttpServlet方法doPost()和doGet():
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
processRequest(request,response);
}