You are currently browsing the tag archive for the ‘XStream’ tag.

I have not found any direct way to get ajax support with spring MVC. I got the same feature using jQuery , Spring MVC , XStream, Jettison

My problem was needed to show sate, city and county information against a given zip code in a portion of page without refreshing the page. So ajax is the best candidate here. But problem was I have not found any direct way to work ajax with Spring MVC. In Spring3 you can do it easily using ajax library but not supported in spring MVC.

I solve the problem using jQuery , Spring MVC , XStream, Jettison. Here I have given a step by step example of ajax and Spring MVC with JSON:

The simple jsp page where needed to show the information, I have excluded the tag  include part:

<html>
<head>
<script src="<c:url value="/javascripts/jquery/jquery-1.2.6.min.js"/>"> </script>
<script src="<c:url value="/javascripts/jquery/jquery.form.js"/>"> </script>
<script type="text/javascript">
function getInfo(frm){
if (frm.bZipCode.value == "")
alert("Hey! You didn't enter anything in zip code!");
else{
$.getJSON("<c:url value="/zipInfo.htm" />",     // url
{ zipId: frm.bZipCode.value },   // request params
function(json){           // callback
$(json.zipInfo).each(function() {
frm.bState.value =this.state;
frm.bCountry.value =this.conty;
frm.bCity.value =this.city;
});
}
);
}
}
</script>
</head>
<body>
<form:form commandName="providerForm"
onsubmit="return checkCreateSPForm(this);"
enctype="multipart/form-data">
<table border=0 cellpadding=0 cellspacing=0 width=100%>
<tr bgcolor="#FFFFFF">
<td width="18%">Enter Zip code and click on Info button to get related information</td>
<td width="80%"> <input type="text" name="bZipCode" id="bZipCode" size="25" maxlength="100" >
<input type="button" onclick="getInfo(this.form)" value="Get Info"/> </td> </tr>
<tr bgcolor="#FFFFFF">
<td width="18%">State</td>
<td width="80%"><input type="text" name="bState" id="bState" size="40" maxlength="100"> </td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="18%">Business County</td>
<td width="80%"><input type="text" name="bCountry" id="bCountry" size="40" maxlength="100"> </td>
</tr>
<tr bgcolor="#FFFFFF">
<td width="18%">Business City</td>
<td width="80%"><input type="text" name="bCity" id="bCity" size="40" maxlength="100"> </td>
</tr>
<tr>
<td> <input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>

Now going to the code where the server returns JSON data to the browser. Starting on the server side, we will see how we can use Spring MVC along with XStream and Jettison to serve up JSON data.

Bellow given the Spring MVC controller code:

@Controller
public class AdminController extends SimpleFormController{
@Autowired
IProviderService SPService;
@RequestMapping("/zipInfo.htm")
public ModelAndView years(@RequestParam("zipId") Long zipId) {
ModelAndView mav = new ModelAndView(JsonView.instance);
//getting zipInfo from database
ZipInfo zipInfo=SPService.getZipInfoById(String.valueOf(zipId));
if(zipInfo==null){
zipInfo=new ZipInfo();
zipInfo.setCity("city");
zipInfo.setConty("conty");
zipInfo.setState("state");
}
mav.addObject(JsonView.JSON_ROOT, zipInfo);
return mav;
}
}

The @Controller annotation tells Spring MVC to use this class as a controller

The @RequestMapping annotation maps the request URL to the handler method

A ModelAndView object is created with a view name of “mav” which will get mapped to jsp page

zipInfo load from database against the provided zipId and added to the Model And View

The @RequestMapping annotation maps the request URL to the handler method

The @RequestParam annotation maps a request parameter to a method argument

This ModelAndView is created using a simple JSON-rendering View class that I wrote called JsonView. Spring MVC makes is quite easy to write custom views, and JsonView is where XStream gets hooked in.

In summary, the controller responds URL, “zipInfo.htm”. It returns ZipInfo object as the response to the “zipInfo.htm” URL. Let’s take a look at the JsonView class, which renders the JSON result for the “zipInfo.htm” request:

import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.View;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class JsonView implements View {
public static final JsonView instance = new JsonView();
public static final String JSON_ROOT = "root";
// This instance of XStream is thread-safe. XStream is not
// thread-safe if auto-detection of annotations is used.
private XStream xstream = new XStream(new JettisonMappedXmlDriver());
private JsonView() {
// in a large project, listing every class with XStream
// annotations is not practical. 2 alternatives are:
// * traversing the classpath using a specified root package
// and calling processAnnotations
// * enabling annotation auto-detection, but then the XStream
// instance is not thread-safe
xstream.processAnnotations(ZipInfo.class);
}
public String getContentType() {
return "text/html; charset=UTF-8";
}
@SuppressWarnings("unchecked")
public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Object root = model.get(JsonView.JSON_ROOT);
if (root == null) {
throw new RuntimeException("JSON root object with key '"
+ JsonView.JSON_ROOT + "' not found in model");
}
PrintWriter writer = response.getWriter();
// even though the following method is "toXML" XStream is configured
// to use Jettison to output JSON instead
String json = xstream.toXML(root);
System.out.println("json: " + json);
writer.write(json);
}
}

Source

May 2024
S M T W T F S
 1234
567891011
12131415161718
19202122232425
262728293031  

RSS Hima’s Blog

  • An error has occurred; the feed is probably down. Try again later.