首先我们创建一个some.jsp如下(注意:不要将JSP文件放在子文件夹中,如果你这样做,请相应地更改servlet 的URL):
<!DOCTYPE html>
<html lang="en">
<head>
<title>TestAjax</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).on("click", "#somebutton", function() {
$.get("someservlet", function(responseText) {
$("#somediv").text(responseText);
});
});
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
使用如下doGet()方法创建一个servlet :
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
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(text); // Write response body.
}
将该servlet映射到URL模式/someservlet或/someservlet/*下面(URL模式可以自由选择,但需要将someservlet的所有位置相应地更改JS代码示例中的URL):
@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
// ...
}
或者,当你尚未使用Servlet 3.0兼容容器(Tomcat 7,Glassfish 3,JBoss AS 6等或更新版本)时,请以web.xml旧式进行映射:
<servlet>
<servlet-name>someservlet</servlet-name>
<servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>someservlet</servlet-name>
<url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>
现在在浏览器中打开http:// localhost:8080 / context / some.jsp,然后按按钮。你将看到,使用servlet响应更新了的div内容。