如何使用servlet和阿贾克斯? [英] How to use Servlets and Ajax?

查看:169
本文介绍了如何使用servlet和阿贾克斯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

每当我打印的东西在servlet中,并用web浏览器调用它,它会返回一个包含文本的新页。有没有一种方法来打印使用Ajax在当前页面中的文本?

解决方案

事实上,关键词是AJAX:异步JavaScript和XML 的。然而,过去几年中它比通常的异步JavaScript和JSON 的。基本上,你让基于响应数据JS执行异步HTTP请求,并更新HTML DOM树。

由于它是pretty的一个繁琐工作,使其在所有浏览器的工作(特别是互联网浏览器与其他人),有大量的图书馆内采用单功能简化了这一点,如 jQuery的,的原型 MooTools的。因为jQuery是最流行的,我会用它在下面的例子。

开球例子返回字符串为纯文本

创建一个 /some.jsp 如下图所示(注:code没有想到的JSP文件被放置在一个子文件夹):

<!DOCTYPE HTML> < HTML LANG =EN>     < HEAD>         <冠军> SO质疑4112686< /标题>         &所述;脚本的src =的http://$c$c.jquery.com/jquery-latest.min.js>&所述; /脚本>         <脚本>             $(文件)。在(点击,#somebutton,函数(){//当HTML DOM,单击事件上的ID为somebutton元素调用,执行以下功能...                 $获得(someservlet功能(responseText的){//执行的Ajax GET请求someservlet的网址,并执行与Ajax响应文本下面的函数...                     $(#somediv)文本(responseText的)。 //找到ID为somedivHTML DOM元素,并设置其文本内容与响应文本。                 });             });         < / SCRIPT>     < /头>     <身体GT;         <按钮ID =somebutton> $这里p $ PSS< /按钮>         < D​​IV ID =somediv>< / DIV>     < /身体GT; < / HTML>

创建一个的doGet()方法,一个servlet看起来是这样的:

@覆盖 保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     字符串文本=一些文本;     response.setContentType(text / plain的); //设置响应的内容类型,这样的jQuery知道什么可以期待的。     response.setCharacterEncoding(UTF-8); //你要一统天下,是吧?     。response.getWriter()写(文本); //写响应体。 }

地图这个servlet对 / someservlet 的URL模式/ someservlet / * 如下(很明显, URL模式是自由的选择,但你需要更改 someservlet URL的JS code例子在所有地方相应的):

@WebServlet(/ someservlet / *) 公共类SomeServlet延伸的HttpServlet {     // ... }

或者,当你不能在一个Servlet 3.0兼容的容器,但(Tomcat 7的,Glassfish的3,JBoss AS中6等或更高版本),然后映射它的web.xml 的老式方法(参见我们的servlet的wiki页面):

<的servlet>     < servlet的名称>&someservlet LT; / Servlet的名称>     <的servlet类> com.example.SomeServlet< / Servlet的类> < / servlet的> < Servlet映射>     < servlet的名称>&someservlet LT; / Servlet的名称>     < URL模式> / someservlet / *< / URL模式> < / Servlet映射>

现在打开的http://本地主机:8080 /环境/ test.jsp的在浏览器和preSS按钮。你会看到,在div的内容得到与servlet响应更新。

返回名单,其中,字符串> 为JSON

使用 JSON 而非纯文本作为响应格式,你甚至可以得到一些措施进一步。它允许更多的动力。首先,你想有一个工具,Java对象和JSON字符串之间进行转换。有很多人,以及(见底部此页面的概述)。我个人最喜欢的是谷歌GSON 。下载并把它的JAR文件在你的web应用的 / WEB-INF / lib目录文件夹。

下面是它显示一个例子名单,其中,字符串> < UL><李> 。该servlet:

@覆盖 保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     名单<字符串>名单=新的ArrayList<字符串>();     list.add(ITEM1);     list.add(项目2);     list.add(item3的);     JSON字符串=新GSON()的toJSON(列表)。     response.setContentType(应用/ JSON);     response.setCharacterEncoding(UTF-8);     。response.getWriter()写(JSON); }

在JS code:

$(文件)。在(点击,#somebutton,函数(){//当HTML DOM 点击事件被调用的元素ID为somebutton,执行以下功能...     $获得(someservlet功能(responseJson){//执行的Ajax GET请求someservlet的网址,并执行与Ajax响应JSON如下功能...         变量$ UL = $(< UL>中)。appendTo($(#somediv)); //创建HTML< UL>元素,并把它添加到HTML DOM元素的ID为somediv。         $每个(responseJson,函数(指数,项目){//遍历JSON数组。             $(<李>)文本(项目).appendTo($ UL)。 //创建HTML<李>元素,设置其文本内容与当前迭代的项,并将其追加到的< UL取代。         });     }); });

请注意,jQuery的自动解析响应作为JSON和直接给你一个JSON对象( responseJson )的功能,参数,当你设置响应内容类型设置为应用程序/ JSON 。如果忘记设置它,或者依靠文本/纯的text / html ,那么<默认code> responseJson 参数不会给你一个JSON对象,而是一个普通的字符串。

返回地图&LT;字符串,字符串&GT; 为JSON

下面是它显示地图&LT另一个例子,字符串,字符串&GT; &LT;选项&GT;

@覆盖 保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     地图&LT;字符串,字符串&GT;选项​​=新的LinkedHashMap&LT;字符串,字符串&GT;();     options.put(值1,label1的);     options.put(值2,标签2);     options.put(值3,LABEL3);     JSON字符串=新GSON()的toJSON(选项)。     response.setContentType(应用/ JSON);     response.setCharacterEncoding(UTF-8);     。response.getWriter()写(JSON); }

和JSP的:

$(文件)。在(点击,#somebutton,函数(){//当HTML DOM 点击事件被调用的元素ID为somebutton,执行以下功能...     $获得(someservlet功能(responseJson){//执行的Ajax GET请求someservlet的网址,并执行与Ajax响应JSON如下功能...         变量$选择= $(#someselect); //找到ID为someselectHTML DOM元素。         $ select.find(选项),删除()。 //查找所有的子元素标签名选项,并删除它们(只是prevent重复的选项,当按钮是pressed再次)。         $每个(responseJson,功能(键,值){//遍历JSON对象。             $(&LT;选项&gt;中)。VAL(密钥)的.text(值).appendTo($选择); //创建HTML&LT;选项&GT;元素,将其值设置与当前迭代项及其文本内容与当前迭代的项目,最后追加到的&lt;选择取代。         });     }); });

&LT;选择一个id =someselect&GT;&LT; /选择&GT;

返回名单,其中,实体&GT; 为JSON

下面是它显示的最后一个例子名单,其中,产品&GT; &LT;表&gt; 其中产品类有属性龙ID 字符串名称 BigDecimal的价格。该servlet:

@覆盖 保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     名单&LT;产品&GT;产品= someProductService.list();     JSON字符串=新GSON()的toJSON(产品)。     response.setContentType(应用/ JSON);     response.setCharacterEncoding(UTF-8);     。response.getWriter()写(JSON); }

在JS code:

$(文件)。在(点击,#somebutton,函数(){//当HTML DOM 点击事件被调用的元素ID为somebutton,执行以下功能...     $获得(someservlet功能(responseJson){//执行的Ajax GET请求someservlet的网址,并执行与Ajax响应JSON如下功能...         变量$表= $(&LT;表&gt;)。appendTo($(#somediv)); //创建HTML&LT;表&gt;元素,并把它添加到HTML DOM元素的ID为somediv。         $每个(responseJson,函数(指数产品){//遍历JSON数组。             $(&LT; TR&gt;中)。appendTo($表)//创建HTML&LT; TR&GT;元素,设置其文本内容与当前迭代的项,并将其追加到的&lt;表&gt ;.                 .append($(&LT; TD&gt;中。)文本(product.id))//创建HTML&LT; TD&GT;元素,设置其文本内容与当前迭代的产品ID,并追加到的&lt; TR取代。                 .append($(&LT; TD&gt;中。)文本(product.name))//创建HTML&LT; TD&GT;元素,设置其文本内容与当前迭代产品的名称,将其附加到的&lt; TR取代。                 .append($(&LT; TD&gt;中)文本(product.price)。); //创建HTML&LT; TD&GT;元素,设置其文本内容与当前迭代产品的价格,其追加到的&lt; TR取代。         });     }); });

Ajaxifying现有的形式

您可以使用jQuery $。序列化() 轻松ajaxify现有POST方式没有收集和传递个人的形式输入参数摆弄周围。假设现有的形式,工作完全正常没有JavaScript / jQuery的:

&LT;形式ID =someform行动=someservlet方法=邮报&GT;     &LT;输入类型=文本名称=富/&GT;     &LT;输入类型=文本名称=酒吧/&GT;     &LT;输入类型=文本名称=巴兹/&GT;     &LT;输入类型=提交名称=提交值=提交/&GT; &LT; /形式GT;

您可以ajaxify它如下:

$(文件)。在(提交,#someform,函数(){     变量$形式= $(本);     $。员额($ form.attr(行动),$ form.serialize()函数(responseJson){         // ...     }); });

您可以在servlet的正常请求和Ajax请求如下区分

@覆盖 保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     字符串富=的request.getParameter(富);     字符串栏=的request.getParameter(巴);     字符串巴兹=的request.getParameter(巴兹);     布尔阿贾克斯=XMLHtt prequest.equals(request.getHeader(X-要求,随着));     // ...     如果(阿贾克斯){         //处理Ajax(JSON)响应。     } 其他 {         //处理正(JSP)的响应。     } }

借助的jQuery插件形式不会少跌多同上jQuery的例子,但它对于<$额外的透明支持C $ C>所要求的文件上传。的multipart / form-data的表格

参见:

  • 简单的计算器在JSP
  • 在阿贾克斯处理Servlet的输出
  • 从JavaScript调用Servlet的
  • <一个href="http://stackoverflow.com/questions/2263996/populating-child-dropdownlists-in-jsp-servlet">Populating孩子下拉菜单用JSP / Servlet的
  • JSON结果表
  • <一个href="http://stackoverflow.com/questions/5952670/is-it-a-good-practice-to-use-asynchronous-requests-in-this-scenario/">Is它一个很好的做法,在这种情况下使用异步请求?
  • <一个href="http://stackoverflow.com/questions/2600582/how-to-switch-easily-between-ajax-based-website-and-basic-html-website/">How阿贾克斯为基础的网站和基本的HTML网页之间轻松切换?
  • <一个href="http://stackoverflow.com/questions/6914152/how-to-upload-files-to-server-using-jsp-servlet-and-ajax">How使用JSP / Servlet和阿贾克斯的文件上传到服务器?

I'm very new to web apps and Servlets and I have the following question:

Whenever I print something inside the servlet and call it by the webbrowser, it returns a new page containing that text. Is there a way to print the text in the current page using Ajax?

解决方案

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of libraries out which simplifies this in single functions, like jQuery, Prototype, Mootools. Since jQuery is the most popular, I'll use it in the below examples.

Kickoff example returning String as plain text

Create a /some.jsp like below (note: the code doesn't expect the JSP file being placed in a subfolder):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Create a servlet with a doGet() method which look like this:

@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.
}

Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

<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>

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

Returning List<String> as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

Here's an example which displays List<String> as <ul><li>. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string.

Returning Map<String, String> as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<String, String>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Returning List<Entity> as JSON

Here's the last example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Ajaxifying an existing form

You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery:

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

You can ajaxify it as below:

$(document).on("submit", "#someform", function() {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(responseJson) {
        // ...
    });
});

You can in the servlet distinguish between normal requests and ajax requests as below:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON) response.
    } else {
        // Handle regular (JSP) response.
    }
}

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

See also:

这篇关于如何使用servlet和阿贾克斯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆