ajax实现读取文本文档到jsp页面

       如果项目很小,数据量也不大,就不需要用到数据库,这时候就需要用到文本文档了,再用ajax调用文本文档展示。真的是偷懒必备,哈哈哈哈哈

首先,在util里写一个写文件的方法:

public static void writeLogFile(String path, String context) {
		OutputStreamWriter writerStream = null;
		BufferedWriter bw = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			File file = new File(path);
			if(!file.exists())
				file.mkdirs();
			writerStream = new OutputStreamWriter(new FileOutputStream(path + File.separator + "log.txt", true),
					"UTF-8");
			bw = new BufferedWriter(writerStream);
			bw.append(sdf.format(new Date())).append("\t").append(context).append("<br />").write("\r\n");
			
			bw.flush();
		} catch (IOException e) {
			_log.error(e);
		} finally {
			try {
				if(bw != null)
					bw.close();
			} catch (IOException e) {
				_log.error(e);
			}
		}
	}

然后在controller写一个转发页面:

@RequestMapping(value = "/toLog.do", method = RequestMethod.GET)
    public String toLog(HttpSession session){
		
		UserBean userFront = (UserBean) session.getAttribute("userFront");
		
		if(userFront != null){
			return "/front/log";
		}
		else{
			return "/front/login";
		}	
		
	}

然后写一个log的jsp页面展示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>****</title>
<script type="text/javascript" src="<%=path%>/js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="<%=path%>/js/canvasjs.min.js"></script>

<script>
$(function(){
	parent.$.messager.progress();

	$.get('../log/log.txt',function(data){
		$('#mainbody').html(data);
		parent.$.messager.progress('close');
	});
});

</script>
</head>
<body>
	<div id="mainbody" style="width:90%"></div>
	
</body>
</html>


最后在你需要的所有方法里调用:

if (file != null) {
						File f = new File(path, file.getOriginalFilename());
						if (!f.exists())
							f.mkdirs();
						file.transferTo(f);
						ComUtil.writeLogFile(PathUtil.LOGPath(request), "你想做什么呀" + f.getName());
					}


发布了30 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/selinaqqqq/article/details/80366655
今日推荐