这是我第一次设置Java Servlet,我试图在用户单击特定按钮时从JSP表单中的输入字段中将值检索到Java Servlet中。我也不确定我是否使用了正确的做法来创建我的Servlet。我只需右键单击我的Apache Tomcat 8.0服务器,然后选择新的Servlet。
Java Servlet:
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
答案 0 :(得分:3)
您的请求属性的名称是{J}页面上添加的uname
和psw
。所以你必须像这样改变你的doPost方法。
String username = request.getParameter("uname");
String password = request.getParameter("psw");
或
您必须在jsp页面中更改您的表单,如下所示:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>