0

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;
  }
}
2
  • where is your controller code ? Commented Dec 9, 2013 at 7:31
  • @Bk Santiago here i pasted
    – SUBZ
    Commented Dec 9, 2013 at 7:55

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.