Reputation: 139
Help me to write spring web application to read from a file and display as a html page
jQuery(document).ready(function($){
$.ajax({
url : "../xml.txt",
type:"POST",
dataType: "text",
success : function (data) {
$('<pre />').text(data).appendTo('div');
window.location.href=contextPath+"http://localhost:8080/subin.html"
}
});
});
how to support this with spring ????
my controller class is
@Controller
@RequestMapping("/data")
public ModelAndView helloWorld() {
return new ModelAndView("hello", "message", "Spring MVC Demo");
}
@RequestMapping(value = "/data", method = RequestMethod.POST)
public @ResponseBody String getData(@RequestParam String name) {
String result = br.readLine();
return result;
}
}
Upvotes: 0
Views: 176
Reputation: 23014
You're probably best to not expose the real path of the file in the AJAX request. You can keep that abstract and let a controller method resolve the real path and load the file.
Something like:
jQuery(document).ready(function($){
$.ajax({
url : "/data?name=xml.txt", // Abstract path and filename
type:"GET",
dataType: "text",
success : function (data) {
$('<pre />').text(data).appendTo('div');
window.location.href=contextPath+"http://localhost:8080/subin.html"
}
});
});
The controller method that handles the AJAX request loads the file from its real location and returns the content.
@RequestMapping(value = "/data", params="name", method = RequestMethod.GET)
public @ResponseBody String getData(@RequestParam(value="name") String name) {
InputStream in = new FileInputStream("/real/path/" + name);
String contents = IOUtils.toString(in, "UTF-8");
return contents;
}
That example uses a FileInputStream
but depending upon your requirements you could load the file from different types of location - such as the classpath or a URI. Also note that it uses GET rather than POST.
Hope that helps.
Upvotes: 1