当前访客身份:游客 [ 登录 | 加入 OSCHINA ]

代码分享

当前位置:
代码分享 » Java  » Web编程
快速开发师

【jsp】VS【freemarker】IO

快速开发师 发布于 2016年05月20日 14时, 1评/702阅
分享到: 
收藏 +0
2
freemarker可以做很多事,例如生成本地文件,这或许是他和JSP典型的不同之处之一;但是学习freemarker需要成本,如果你没有时间去学习可以看看我这里的写的这个项目,用JSP也能非常简单就生成了本地文件,用JSP也是可以做代码生成器的,而且还很简单。筷子就很简单,你一定不会嘲笑发明筷子的那个人,因为人人都在用!

代码片段(6) [全屏查看所有代码]

1. [图片] freemarker.jpg    

2. [图片] JSP_MARKER项目.png    

3. [文件] jsp_marker.rar ~ 37KB     下载(73)     [全屏预览]

4. [代码]index.jsp ajax反提交     跳至 [4] [5] [6] [全屏预览]

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="<%=basePath%>/jquery.min.js"></script>
  </head>
  
  <body>
  	  <% 
  	  // 参数 设置到Session
  	  List user = new ArrayList();
  	  HashMap a = new HashMap();user.add(a);
  	  HashMap b = new HashMap();user.add(b);
  	  HashMap c = new HashMap();user.add(c);
  	  HashMap d = new HashMap();user.add(d);
  	  // 用户名
  	  a.put("col","username");a.put("desc","用户名");
  	  // 密  码
  	  b.put("col","password");b.put("desc","密  码");
  	  // 姓   名
  	  c.put("col","name");c.put("desc","姓名");
  	  // 性  别
  	  d.put("col","sex");d.put("desc","性别");
  	  
  	  session.setAttribute("user",user);
  	  
  	  %>
      <script type="text/javascript">
          // "D:\\tools\\Workspaces\\jsp_marker" 为我的eclipse项目jsp_marker的路径,右键项目->属性可复制真实项目路经 
	      $.ajax({
	        url:'<%=basePath%>/User.java.jsp',
	        type:'post',
	      	cache:false,
	      	success:function(result){
	      		alert(result);
	      		$.ajax({
	      			url:'<%=basePath%>//servlet/WriteServlet',
	      			type:'post',
	      			data:{'text':result,'savePath':'D:\\tools\\Workspaces\\jsp_marker\\User.java'},
	      			cache:false,
	      			success:function(result){
	      				alert(result+'请手动刷新项目');
	      			},
	      			error:function(result){
	      				alert(result);
	      			}
	      		});
	      	},
	      	error:function(err){
	      		alert(err);
	      	}
	      });
      </script>
  </body>
</html>

5. [代码]User.java.jsp 生成实体类模板     跳至 [4] [5] [6] [全屏预览]

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
public class User {
	<%
	// 获取参数user
	List user = (List)session.getAttribute("user");
	System.out.println(user);
	
	    /**(1)生成property **/
	for(int i=0;i<user.size();i++){
		Map map = (Map)user.get(i);
		String col = (String)map.get("col");
		String desc = (String)map.get("desc");
	%>
	/* <%=desc%> */
	private String <%=col%>;
	<%}%>
	
	<%	/**(2)生成getter **/
		for(int i=0;i<user.size();i++){
		Map map = (Map)user.get(i);
		String col = (String)map.get("col");
	%>
	<%--生成getter--%>
	public String get<%=col.substring(0,1).toUpperCase()+col.substring(1)%>(){
	
		return this.<%=col%>;
	}
	<%--生成setter--%>
	public void set<%=col.substring(0,1).toUpperCase()+col.substring(1)%>(String <%=col%>){
	
		this.<%=col%> = <%=col%>;
	}
	<%}%>
	
}

6. [代码]WriteServlet.java 输出Servlet 只负责生成文件     跳至 [4] [5] [6] [全屏预览]

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class WriteServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public WriteServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        String text = request.getParameter("text");
        String savePath = request.getParameter("savePath");
        FileOutputStream fos = new FileOutputStream(savePath);
        fos.write(text.getBytes("UTF-8"));
        fos.flush();
        fos.close();
        
		PrintWriter out = response.getWriter();
		out.print("write ok!");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

发表评论 回到顶部 网友评论(1)

  • 1楼:乌龟壳 发表于 2016-08-29 20:21 回复此评论
    给个建议,出案例代码的时候,尽量把所有东西都最精简化,影响理解的全部剔除。这样别人才有心思看。比如jsp生成文件,最简单清晰能说明的就是尽量精简地实现以下伪代码。

    public static int main(String[] args) {
       initData(xxxx);
       System.out.println(jsp2str(xxxxx));
    }

开源从代码分享开始 分享代码