因爲所在項目的框架是由內部人員開發的openx框架,即js+abstractServlet封裝了servlet層,面向接口編程mvc框架。
而今天又收到任務因爲ios端和android端的配置中心任務,要單獨寫一個Servlet接發請求。
在這個過程中遇到幾個沒碰到的異常,特地記錄一下。
一個是servlet版本異常。
因爲用的是maven構建的項目,因此提示使用2.5的servlet-api。但是會報錯。
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency>所以改用
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>並且scope爲provided,編譯時通過,運行時不通過。即可解決。
第二個是servlet引用mybatis的dao層接口。
一般習慣是直接autowired。但是servlet有自己的容器,無法直接引用spring的註釋。
所以使用
protected ConfDao confDao; protected ConfItemDao confItemDao; protected AppVersionDao appVersionDao; protected StageDao stageDao;
@Override public void init() throws ServletException{ super.init(); ServletContext servletContext = this.getServletContext(); WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); confDao = (ConfDao)context.getBean("confDao"); confItemDao = (ConfItemDao)context.getBean("confItemDao"); appVersionDao = (AppVersionDao)context.getBean("appVersionDao"); stageDao = (StageDao)context.getBean("stageDao"); }的方式獲取到spring容器中注入的bean。
第三個是通過拿到的對象數據解析成json數組返回
JSONStringer stringer = new JSONStringer();
stringer.array(); for(ConfItem item:query(entity.getId()).getItems()){ stringer.object().key(item.getKey()).value(item.getValue()).endObject(); } stringer.endArray();
resp.getOutputStream().write(stringer.toString().getBytes("utf-8")); resp.setContentType("text/json; charset=UTF-8");