如何使用Servlets和Ajax?

我是Web应用程序和Servlet的新手,我有以下问题:

每当我在servlet中打印一些东西并通过webbrowser调用它时,它就会返回一个包含该文本的新页面。有没有办法使用Ajax在当前页面中打印文本?

如何使用Servlets和Ajax?


慕无忌1623718
浏览 448回答 4
4回答

收到一只叮咚

我将向您展示一个servlet的完整示例以及ajax如何调用。在这里,我们将创建一个使用servlet创建登录表单的简单示例。的index.html<form>&nbsp;&nbsp;&nbsp; &nbsp;Name:<input type="text" name="username"/><br/><br/>&nbsp;&nbsp;&nbsp; &nbsp;Password:<input type="password" name="userpass"/><br/><br/>&nbsp;&nbsp;&nbsp; &nbsp;<input type="button" value="login"/>&nbsp;&nbsp;</form>&nbsp;&nbsp;这是ajax Sample&nbsp; &nbsp; &nbsp; &nbsp;$.ajax&nbsp; &nbsp; &nbsp; &nbsp; ({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: 'LoginServlet='+name+'&name='+type+'&pass='+password,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: url,&nbsp; &nbsp; &nbsp; &nbsp; success:function(content)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#center').html(content);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });LoginServlet Servlet代码: -&nbsp; &nbsp; package abc.servlet;import java.io.File;public class AuthenticationServlet extends HttpServlet {&nbsp; &nbsp; private static final long serialVersionUID = 1L;&nbsp; &nbsp; protected void doGet(HttpServletRequest request, HttpServletResponse response)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws ServletException, IOException&nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; doPost(request, response);&nbsp; &nbsp; }&nbsp; &nbsp; protected void doPost(HttpServletRequest request,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpServletResponse response) throws ServletException, IOException {&nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; HttpSession session = request.getSession();&nbsp; &nbsp; &nbsp; &nbsp; String username = request.getParameter("name");&nbsp; &nbsp; &nbsp; &nbsp; String password = request.getParameter("pass");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /// Your Codeout.println("sucess / failer")&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // System.err.println("Initial SessionFactory creation failed.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ex.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.exit(0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript
Java