经过一晚上的思考,我把我的通用代码管理做成了这样:后台维护、前台调用。
后台维护、贴出表结构和操作界面
展示页面通过监听器在web初始化的时候把数据存到application中,以MAP形式记录、以下为
@Component("DfcodeIntListener")
public class DfcodeIntListener implements ApplicationListener {
@Resource
private DfcodeIntServices dfcodeIntServices;
@Resource
private ServletContext servletContext;
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
// System.out.println("here:"+servletContext.getContextPath());
//初始化代码表的数据到内存中
servletContext.setAttribute("dfcodedata",dfcodeIntServices.listDffcode());
}
}
当有其它表中记录了代码表数据时,通过map.get(key)来取显示代码名称,其中有JS中使用及jsp中使用,
js中代码:
/**
* Created by liting on 2016/12/19
* 初始化代码数据到缓存中
*/
@Controller
@RequestMapping(value = "/data")
public class DfcodeIntController {
@RequestMapping(value = "/dffcode.html")
@ResponseBody
public Map dffcode(HttpServletRequest request, HttpServletResponse response) {
Map<String,String> map = (Map<String,String>)request.getSession().getServletContext().getAttribute("dfcodedata");
String key = request.getParameter("key");
String rs = "";
Map map1 = new HashMap();
try {
if (!StringFacs.isEmpty(key)) rs = map.get(key);
}catch (Exception e){
}
map1.put("rs",rs);
return map1;
}
}
function dffcodeconvert(paKey){
var ls = "";
$.ajax({
type: "GET",
url: g_BasePath + "data/dffcode.html",
data: {key: paKey},
async: false,
error: function (request) {
alert("出错了!");
},
success: function (data) {
ls = data;
}
});
return JSON.parse(ls).rs;
}
jsp中通过自定标签来取:
<tag>
<name>dffcode</name>
<tag-class>yys.lt.tags.DffcodeTag</tag-class>
<body-content>JSP</body-content>
<description>liting dffcode tag</description>
<attribute>
<name>codekey</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
package yys.lt.tags;
import yys.lt.tools.StringFacs;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.Map;
/**
* Created by liting on 2016/12/22.
*通过传入代码ID,返回代码名称
*
*/
public class DffcodeTag extends BodyTagSupport {
public String getCodekey() {
return codekey;
}
public void setCodekey(String codekey) {
this.codekey = codekey;
}
private String codekey;
@Override
public int doStartTag() throws JspException { // 在标签开始处出发该方法
int ri = BodyTagSupport.EVAL_BODY_INCLUDE;
//HttpServletRequest request=(HttpServletRequest) pageContext.getRequest();
Map<String,String> map = (Map<String,String>)pageContext.getServletContext().getAttribute("dfcodedata");
try {
if(!StringFacs.isEmpty(codekey)) pageContext.getResponse().getWriter().write(map.get(codekey));
} catch (IOException e) {
e.printStackTrace();
}finally {
return ri;
}
//BodyTagSupport.SKIP_BODY
// return ri;// 返回此则执行标签body中内容,SKIP_BODY则不执行
}
@Override
public int doEndTag() throws JspException {
return BodyTagSupport.EVAL_BODY_INCLUDE;
}
}