帮助我编写spring应用程序从文件中读取并显示为html页面。
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"
}
});
});
如何用春天来支撑这个?
我的控制器类是
@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;
}
}
发布于 2013-12-09 10:13:32
最好不要在AJAX请求中公开文件的真实路径。您可以保留该抽象,并让控制器方法解析真实路径并加载文件。
类似于:
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"
}
});
});
处理AJAX请求的控制器方法从其实际位置加载文件并返回内容。
@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;
}
该示例使用FileInputStream
,但取决于您的需求,您可以从不同类型的位置(如类路径或URI )加载文件。还请注意,它使用GET而不是POST。
希望这能有所帮助。
https://stackoverflow.com/questions/20465349
复制相似问题