自己写一个java代码mvc核心类(实际项目使用)

我以前是从php过渡到java语言中,php中有公认的smarty类来说实现mvc功能,而过得到java时候,本来想找类似的类,但是由于各种原因,却在我实际项目中没有用到,而是我自己写了一个简单实用的来完成mvc架构实现。

自己写一个java代码mvc核心类(实际项目使用)

mvc核心代码如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
/**
* Created by lt on 2016/9/10.
*/
public class MSmarty{
private String htmlfile;
private HashMap<string> assign=new HashMap<string>();
public MSmarty(String htmlfile){
this.htmlfile=htmlfile;
}
public void assign(String key,String value){
this.assign.put(key,value);
}
public String display(){
try {
BufferedReader fileReader = new BufferedReader(new FileReader(this.htmlfile));
String fileReaderLione=null;
String fileConnet="";
while ((fileReaderLione=fileReader.readLine())!=null){
fileConnet+=fileReaderLione;
}
fileReader.close();
Iterator<string> iterator=this.assign.keySet().iterator();
while (iterator.hasNext()){
String key=iterator.next();
fileConnet=fileConnet.replaceAll("\\",this.assign.get(key));
}
return fileConnet;
}catch (Exception e) {
System.out.print(e);
return "1";
}
}
}
/<string>/<string>/<string>

就是实现了视图层变量的替换,对我来说视图层中不该有if或for的存在,应该是逻辑层来实际的(三年前的一个代码了)。

案例一:(类基本用法)

MSmarty mSmarty=new MSmarty(Setup.get("home")+"/views/html/test.html"); //home有项目根目录
mSmarty.assign("str", "hello world");
String htmlStr=mSmarty.display();

html视图层:





<title>test1/<title>





案例二:(视图层嵌套,也可以说继承)

MSmarty BSmarty=new MSmarty(Setup.get("home")+"/views/html/basics.html"); //基础层对象
MSmarty mSmarty=new MSmarty(Setup.get("home")+"/views/html/show.html");
//嵌套层对象
mSmarty.assign("str","这是嵌套层内容");
BSmarty.assign("str", mSmarty.display());
String htmlStr=BSmarty.display();

basics.html视图层:





<title>test1/<title>


这是基础层的内容,如导航,字体css全项目设置




show.html视图层:


虽然这个类不复杂,但是对我来说已经满足的实际开发需求了,供大家借鉴。


分享到:


相關文章: