我有一个web项目,我想做的就是将一个String发送到servlet然后将相同的字符串返回到jsp页面(formList.jsp)并显示它:
发送字符串的javascript代码:
$(document).ready(function(){
$('#submit').click(function() {
var value = $('#val').val();
$.ajax({
type:'POST',
data:{value:value},
url:'FormList',
success:function(result){
$('#res').text(result);
}
});
});
});
' FORMLIST' Servlet doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
String value = request.getParameter("value");
response.getWriter().print(value);
}
web.xml(位于WEB-INF中):
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<servlet>
<servlet-name>FormList</servlet-name>
<servlet-class>FormList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormList</servlet-name>
<url-pattern>/FormList</url-pattern>
</servlet-mapping>
</web-app>
但是当我点击提交按钮时,我得到的结果是formList.jsp页面HTML源:(<!DOCTYPE html PUBLIC ....
)
*我在servlet中重写服务方法以初始化formList.jsp
我认为doPost根本没有执行 任何帮助,请
答案 0 :(得分:0)
为FormList servlet提供不同的url映射。
我想在解决formlist.jsp和formlist servlet方面存在困惑。
答案 1 :(得分:0)
我强烈建议在有关如何使用servlet执行ajax的问题上查看BalusC的答案here。
我注意到你正在使用jquery,你也可以像这样创建你的ajax请求:
<script>
$(document).on("click", "#submit", function() {
var value = $('#val').val(); //get value you want to send
var params = {value : value}; //set it as one of the parameters
$.post("FormList", $.param(params), function(response) { //make ajax request
$('#res').text(response); //retrieve response and set it to #res
});
});
</script>
但无论如何,你之所以只看到html,是因为你没有回复任何回复。你需要这样做:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("value");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(value); // Write response body. (not print)
}