有很多方法可以处理 ajax 请求。最简单的方法(不一定是最好的)是创建一个 servlet 来处理您的 ajax 请求。下面的 servlet 示例将返回 json 字符串{ status: 'not logged in'}
:
package mycompany;
public CheckLoginServlet extends HttpServlet {
protected doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("application/json");
HttpSession session = req.getSession();
// do your stuff to check if user logged in here ..
PrintWriter writer = res.getWriter();
writer.append("{ status: 'not logged in' }");
}
}
在您的 web.xml 部署描述符文件中声明并映射此 servlet:
<web-app>
<servlet>
<servlet-class>mycompany.CheckLoginServlet</servlet-class>
<servlet-name>CheckLoginServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>CheckLoginServlet</servlet-name>
<url-pattern>/checklogin</url-pattern>
</servlet-mapping>
</web-app>
servlet 现在映射到http://myhost/myappname/checklogin
. 然后,您可以通过 jquery 向该 servlet 发送 ajax post 请求:
$.ajax('checklogin', {
type: 'POST'
}).done(function(res) {
console.log(res.status); // will give you 'not logged in'
});
这种方法当然是一种陈旧过时的方法,但它有助于您了解 servlet 基础知识。如果您正在构建真实的企业应用程序,请考虑使用Spring或JSF等 Web 框架。