所以我有一个简单的html网页,其中包含一个表单。我想将表单数据作为JSON对象发送到jsp,而jsp又将使用该数据来查询数据库(这是一个雇员目录)。有没有办法在不将webapp设置为HTTPServlet的情况下执行此操作?如果是这样,我该怎么办?如果没有,使用HTTPServlet方法就像导入HTTPServlet类一样简单吗?
我用来在html中创建对象的代码是:
<script>
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formData = JSON.stringify(jQuery("form").serializeArray());
//console.log("Form Data: " + formData);
});
});
</script>
答案 0 :(得分:1)
为了提交表单数据(如果是或不是JSON)进行某些服务器端处理(在您的情况下,查询数据库),您必须使用HTTPServlet设置您的webapp。
在最低限度,您将需要以下内容。
一个HTML表单,其method
属性设置为post
,其action
设置为servlet的URL:
<form name="login-form" method="post" action="LoginServlet">
Username: <input type="text" name="username"/> <br/>
Password: <input type="password" name="password"/> <br/>
<input type="submit" value="Login" />
</form>
Java HTTP servlet:
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
}
}
如果您有web.xml
文件,请确保它使用Servlet 3.0规范:
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">