java反射减少servlet_利用java 反射机制来实现一个servlet处理多种请求
如果我們想在一個(gè)servlet中處理多種請求(比如新聞的添加、刪除),簡單的可以在jsp提交表單的action路徑中添加一個(gè)鍵值對,然后再servlet中接收后根據(jù)不同的值來調(diào)用不同的方法。
jsp端
1
2
3
4
servlet端
1 String method = request.getParameter("method");2 if(method.equals("add")){3 //處理添加
4 }5 else if(method.equals("delete")){6 //處理刪除
7 }
接下來說一下利用java的反射機(jī)制來處理相應(yīng)的業(yè)務(wù)。
jsp端
web.xml配置servlet-mapping的url-pattern為"*.newsServlet"
servlet端
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("UTF-8");
String servletPath = req.getServletPath();
//去掉servlet路徑中前面的/和后面的.newsServlet,只留下中間的請求類型
String methodName = servletPath.substring(1);
methodName = methodName.substring(0, methodName.length()-12);
System.out.println(methodName);
try {
//利用反射得到對應(yīng)請求類型方法的信息
Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
//利用反射調(diào)用執(zhí)行方法
method.invoke(this, req,resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
當(dāng)然servlet還要對應(yīng)著add.newsServlet和delete.newsServlet實(shí)現(xiàn)對應(yīng)的add(HttpServletRequest req, HttpServletResponse resp),和delete(HttpServletRequest req, HttpServletResponse resp)方法。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的java反射减少servlet_利用java 反射机制来实现一个servlet处理多种请求的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 单开程序_java生成jar包
- 下一篇: 博主:P60系列是华为8GB运存末代产品