Write Operations in DWR

Write operations are not allowed with the default session setting for the OpenViewInSession filter which is commonly defined in web.xml as a hibernate filter. If you want to enable write operations when using DWR (Direct Web Remoting), one of the ways is to declare a filter for DWR urls. Put the following configuration in your web.xml, also please note the url pattern in filter-mapping element.


<filter>
<filter-name>dwrWriteHibernateFilter</filter-name>
<filter-class>
some.package.name.OpenWriteSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>dwrWriteHibernateFilter</filter-name>
<url-pattern>*.dwr</url-pattern>
</filter-mapping>

The filter class as follows:

// more imports
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;

public class OpenWriteSessionInViewFilter extends OpenSessionInViewFilter {

protected Session getSession(SessionFactory sessionFactory)
throws DataAccessResourceFailureException {
Session session = super.getSession(sessionFactory);
session.setFlushMode(FlushMode.COMMIT);
return session;
}

protected void closeSession(Session session, SessionFactory factory) {
session.flush();
super.closeSession(session, factory);
}
}

Web Applications with AJAX, Servlets and JSON (Chinese Version)

在这篇文章中,我想说明如何的JSON(JavaScript对象
符号)和Java Servlet可以同时使用在一个小的AJAX((Asynchronous JavaScript and XML)的应用。

为了作简要介绍那些谁不熟悉使用JSON密切。JSON是一种表示数据,这使得工作轻量级语法
它比更愉快,使AJAX应用程序的XML 快。此外,当使用JSON工作,没有任何一个XML需要
解析。

在下面的例子,我将创建一个回调的servlet 获取并分析了RSS提要。然后解析数据被传递到饲料
在一个客户端JSON的形式。这些数据然后格式化并提交 给用户。客户端使用AJAX调用来查询的servlet。

对于这种应用,我使用了三个第三方库:

图书馆提供的JSON和JSON的JSON.org – RPC的Java的,允许以建立并轻松地通过Java代码解析JSON数据延长。该库可以运行在一个如Tomcat,JBoss和其他J2EE应用服务器的Servlet容器。

项目罗马
罗马是一个开放源码的Java工具,用于分析,生成和发布RSS和Atom馈送。

JDOM的XML解析器
JDOM是一个基于Java的“文档对象模型的XML文件”。 JDOM的服务作为DOM的相同目的,但更容易使用

这些库中包含的源代码,附带这篇文章。此应用程序的例子还包括作为一个WAR档案,随时可以在Tomcat部署。
以下是我的servlet实现。该servlet饲料获取并分析数据。前面提到的JSON库让我轻松地创建和填充JSON对象。

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

/**
* @author Alexander Zagniotov (http://javabeans.asia)
*/
public class JsonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String BLOG_URL = "http://javabeans.asia/rss.xml";
	private static final String CONTENT_TYPE = "application/json";
	private FeedFetcherCache feedInfoCache = null;
	private FeedFetcher feedFetcher = null;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		feedInfoCache = HashMapFeedInfoCache.getInstance();
		feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		SyndFeed feed = this.feedFethcer(BLOG_URL);
		if (feed != null) {
			String json = this.feedToJSON(feed);
			response.setContentType(CONTENT_TYPE);
			response.setHeader("Cache-Control", "no-cache");
			response.getWriter().write(json);
		}
	}

	private SyndFeed feedFethcer(String url) {
		SyndFeed feed = null;
		try {
			feed = feedFetcher.retrieveFeed(new URL(BLOG_URL));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (FeedException e) {
			e.printStackTrace();
		} catch (FetcherException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return feed;
	}

	private String feedToJSON(SyndFeed feed) {

		JSONObject jsonObj = new JSONObject();
		JSONArray jsonEntryTitles = new JSONArray();
		jsonObj.put("blogtitle", feed.getTitle());
		jsonObj.put("blogdescription", feed.getDescription());
		jsonObj.put("bloglanguage", feed.getLanguage());
		jsonObj.put("bloglink", feed.getLink());
		jsonObj.put("author", feed.getCopyright());

		List<?> feedEntries = feed.getEntries();

		for (Object c : feedEntries) {
			SyndEntry syndicateEntry = (SyndEntry) c;
			jsonEntryTitles.put(syndicateEntry.getTitle());
		}

		jsonObj.put("blogentrytitles", jsonEntryTitles);
		return jsonObj.toString();
	}
}

正如你可以看到它是很容易的构建在服务器端JSON对象和数组并传递给客户端。对于本示例的目的,我从RSS饲料得到我的数据,但数据也可从数据库等来

以下是我的客户端实现。客户端的servlet查询使用AJAX调用。当一个AJAX调用返回从一个JSON的Servlet的响应对象的形式,对象数据的格式以及有关的RSS供稿信息呈现给客户端:

<html>
    <head>
    <title>Java Beans dot Asia</title>

    <script language="JavaScript" type="text/javascript">

        var httpRequest = null;

    function getDescriptionAsJSON() {
        var description = document.getElementById('description');
        description.innerHTML = "Loading, please wait ...";

        var url = "http://localhost:8080/json/json";
        if(window.XMLHttpRequest){
            httpRequest = new XMLHttpRequest();
        } else if(window.ActiveXObject){
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }

        httpRequest.open("GET", url, true);
        httpRequest.onreadystatechange = handler;
        httpRequest.send(null);
    }

    function handler() {
        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                processJSON(httpRequest.responseText);
            }
        }
    }

    function processJSON(jsonObjectString) {

        var description = document.getElementById('description');

        //Since JSON is a subset of JavaScript, I am using
        //JavaScript's own compiler to parse JSON in one line!

        var jsonObject = eval('(' + jsonObjectString + ')')
        var text = "";

        text += "Author: " + jsonObject.author + "< br />";
        text += "Blog Name: " + jsonObject.blogtitle + "< br />";
        text += "Blog URL: " +    jsonObject.bloglink + "< br />";
        text += "Blog Description: " +    jsonObject.blogdescription + "< br />";
        text += "Blog Language: " + jsonObject.bloglanguage + "< br />";

        description.innerHTML = text;
        var entries = "Last " + jsonObject.blogentrytitles.length + " blog entries are:nn";

        for (var index = 0; index < jsonObject.blogentrytitles.length; index ++) {
            entries += (index + 1) + ": " + jsonObject.blogentrytitles[index] + "n";
        }
        alert(entries);
    }

    </script>

    </head>
    <body>
        <img src="images/javabeansmugshot_120x120.jpg" border="1" />< br />< br />
        <div id="description"></div>< br />< br />
        <a href="javascript:void(0)" onclick="return getDescriptionAsJSON();">Click to get description!</a>
    </body>
</html>

正如你可以看到,JSON数据可以很容易地解析对与Java的脚本eval()函数帮助客户端。为了提醒 – JSON是一个Java脚本的一个子集,因此的eval()将产生一个有效的对象。

请记住,有一个额外需要照顾时,使用eval。问题是,试用版本将编译并执行Java脚本代码,回来从响应。这可能导致安全风险,如果响应数据是来自不可信来源的到来。

就是这样。我希望这个例子是明确的和有用的:)

source code json and servlets

请注意,这个例子是我和测试其工作的罚款。源代码是因为前面提到的Eclipse项目中。你可以简单地创建一个从现有的Ant build.xml文件新的Java项目。

评论表示赞赏:)

干杯

Redefining Web Applications with AJAX, Servlets and JSON

In this article I would like to show how JSON (JavaScript Object Notation) and Java servlet can be used together in a little AJAX (Asynchronous JavaScript and XML) application.

To give brief description to those who are not closely familiar with JSON -

JSON is a lightweight syntax for representing data, which makes working with it much more pleasant than with XML and makes AJAX applications faster. Also, when working with JSON, there is no need for an XML parsing.

In the following example, I am going to create a callback servlet that fetches and parses an RSS feed. Then the parsed feed data is passed to the client side in a form of JSON. The data then formatted and presented to the user. The client uses AJAX call to query the servlet.

For this application, I used three third-party libraries:

  1. JSON library provided by JSON.org and extended by JSON-RPC-Java which allows to create and easily parse JSON data through Java code. This library can run in a Servlet container such as Tomcat, JBoss and other J2EE Application servers.
  2. Project ROME
    ROME is an set of open source Java tools for parsing, generating and publishing RSS and Atom feeds.
  3. JDOM XML parser
    JDOM is a Java-based “document object model” for XML files. JDOM serves the same purpose as DOM, but is easier to use

The libraries are included in the source code which accompanies this article. This application example is also included as a WAR archive, ready to be deployed on Tomcat.

The following is my servlet implementation. The servlet fetches and parses feed data. The JSON library mentioned previously allows me easily to create and populate JSON object.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

/**
* @author Alexander Zagniotov (http://javabeans.asia)
*/
public class JsonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String BLOG_URL = &quot;http://javabeans.asia/rss.xml&quot;;
	private static final String CONTENT_TYPE = &quot;application/json&quot;;
	private FeedFetcherCache feedInfoCache = null;
	private FeedFetcher feedFetcher = null;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		feedInfoCache = HashMapFeedInfoCache.getInstance();
		feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		SyndFeed feed = this.feedFethcer(BLOG_URL);
		if (feed != null) {
			String json = this.feedToJSON(feed);
			response.setContentType(CONTENT_TYPE);
			response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
			response.getWriter().write(json);
		}
	}

	private SyndFeed feedFethcer(String url) {
		SyndFeed feed = null;
		try {
			feed = feedFetcher.retrieveFeed(new URL(BLOG_URL));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (FeedException e) {
			e.printStackTrace();
		} catch (FetcherException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return feed;
	}

	private String feedToJSON(SyndFeed feed) {

		JSONObject jsonObj = new JSONObject();
		JSONArray jsonEntryTitles = new JSONArray();
		jsonObj.put(&quot;blogtitle&quot;, feed.getTitle());
		jsonObj.put(&quot;blogdescription&quot;, feed.getDescription());
		jsonObj.put(&quot;bloglanguage&quot;, feed.getLanguage());
		jsonObj.put(&quot;bloglink&quot;, feed.getLink());
		jsonObj.put(&quot;author&quot;, feed.getCopyright());

		List&lt;?&gt; feedEntries = feed.getEntries();

		for (Object c : feedEntries) {
			SyndEntry syndicateEntry = (SyndEntry) c;
			jsonEntryTitles.put(syndicateEntry.getTitle());
		}

		jsonObj.put(&quot;blogentrytitles&quot;, jsonEntryTitles);
		return jsonObj.toString();
	}
}

As you can see it is very easy to construct JSON objects and arrays on the server side and pass them to the client. For the purpose of this example I am getting my data from RSS feed, but the data can also be coming from DB etc.

The following is my client implementation. The client queries the servlet using AJAX call. When an AJAX call returns a response from the servlet in a form of JSON object, the object data is formatted and information about the RSS feed is presented to the client:

&lt;html&gt;
    &lt;head&gt;
    &lt;title&gt;Java Beans dot Asia&lt;/title&gt;

    &lt;script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;&gt;

        var httpRequest = null;

    function getDescriptionAsJSON() {
        var description = document.getElementById('description');
        description.innerHTML = &quot;Loading, please wait ...&quot;;

        var url = &quot;http://localhost:8080/json/json&quot;;
        if(window.XMLHttpRequest){
            httpRequest = new XMLHttpRequest();
        } else if(window.ActiveXObject){
            httpRequest = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
        }

        httpRequest.open(&quot;GET&quot;, url, true);
        httpRequest.onreadystatechange = handler;
        httpRequest.send(null);
    }

    function handler() {
        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                processJSON(httpRequest.responseText);
            }
        }
    }

    function processJSON(jsonObjectString) {

        var description = document.getElementById('description');

        //Since JSON is a subset of JavaScript, I am using
        //JavaScript's own compiler to parse JSON in one line!

        var jsonObject = eval('(' + jsonObjectString + ')')
        var text = &quot;&quot;;

        text += &quot;Author: &quot; + jsonObject.author + &quot;&lt; br /&gt;&quot;;
        text += &quot;Blog Name: &quot; + jsonObject.blogtitle + &quot;&lt; br /&gt;&quot;;
        text += &quot;Blog URL: &quot; +    jsonObject.bloglink + &quot;&lt; br /&gt;&quot;;
        text += &quot;Blog Description: &quot; +    jsonObject.blogdescription + &quot;&lt; br /&gt;&quot;;
        text += &quot;Blog Language: &quot; + jsonObject.bloglanguage + &quot;&lt; br /&gt;&quot;;

        description.innerHTML = text;
        var entries = &quot;Last &quot; + jsonObject.blogentrytitles.length + &quot; blog entries are:nn&quot;;

        for (var index = 0; index &lt; jsonObject.blogentrytitles.length; index ++) {
            entries += (index + 1) + &quot;: &quot; + jsonObject.blogentrytitles[index] + &quot;n&quot;;
        }
        alert(entries);
    }

    &lt;/script&gt;

    &lt;/head&gt;
    &lt;body&gt;
        &lt;img src=&quot;images/javabeansmugshot_120x120.jpg&quot; border=&quot;1&quot; /&gt;&lt; br /&gt;&lt; br /&gt;
        &lt;div id=&quot;description&quot;&gt;&lt;/div&gt;&lt; br /&gt;&lt; br /&gt;
        &lt;a href=&quot;javascript:void(0)&quot; onclick=&quot;return getDescriptionAsJSON();&quot;&gt;Click to get description!&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;

As you could see, JSON data can be easily parsed on the client side with the help of Java script eval() function. To remind – JSON is a subset of Java script, therefore eval() will produce a valid object.

Keep in mind, that there is a need for extra care when using eval. The problem is that eval will compile and execute Java script code that coming back from the response. This could cause a security risk if the response data is coming from an untrusted source.

That’s it. I hope this example was clear and helpful :)

source json servlets ajax

Please note that this example was tested by me and its working fine. The source code as mentioned previously is included as Eclipse project. You can simply create a new Java project from the existing Ant build.xml file.

Comments/flames are appreciated :)

Cheers