View.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package cn.nosum.framework.mvc.v4.servlet;
  2. import cn.nosum.util.StringUtils;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.File;
  6. import java.io.RandomAccessFile;
  7. import java.util.Map;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10. /**
  11. * Created by Tom.
  12. */
  13. public class View {
  14. private File viewFile;
  15. public View(File templateFile) {
  16. this.viewFile = templateFile;
  17. }
  18. public void render(Map<String, ?> model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
  19. StringBuffer sb = new StringBuffer();
  20. RandomAccessFile ra = new RandomAccessFile(this.viewFile,"r");
  21. String line = null;
  22. while (null != (line = ra.readLine())){
  23. line = new String(line.getBytes("ISO-8859-1"),"utf-8");
  24. Pattern pattern = Pattern.compile("¥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE);
  25. Matcher matcher = pattern.matcher(line);
  26. while (matcher.find()){
  27. String paramName = matcher.group();
  28. paramName = paramName.replaceAll("¥\\{|\\}","");
  29. String paramValue = StringUtils.getString(model.get(paramName),"");
  30. line = matcher.replaceFirst(makeStringForRegExp(paramValue));
  31. matcher = pattern.matcher(line);
  32. }
  33. sb.append(line);
  34. }
  35. resp.setCharacterEncoding("utf-8");
  36. resp.getWriter().write(sb.toString());
  37. }
  38. //处理特殊字符
  39. public static String makeStringForRegExp(String str) {
  40. return str.replace("\\", "\\\\").replace("*", "\\*")
  41. .replace("+", "\\+").replace("|", "\\|")
  42. .replace("{", "\\{").replace("}", "\\}")
  43. .replace("(", "\\(").replace(")", "\\)")
  44. .replace("^", "\\^").replace("$", "\\$")
  45. .replace("[", "\\[").replace("]", "\\]")
  46. .replace("?", "\\?").replace(",", "\\,")
  47. .replace(".", "\\.").replace("&", "\\&");
  48. }
  49. }