我有一个servlet类,如下所示
public class test extends HttpServlet {
private adv1 adv1;
private adv2 adv2;
private adv3 adv3;
...
private adv50 adv50;
// INITIALIZING REFERENCE VARIABLES
init() {
ServletContext context = getServletContext();
adv1 = context.getServletContext("adv1");
adv2 = context.getServletContext("adv2");
adv3 = context.getServletContext("adv3");
....
adv50 = context.getServletContext("adv50");
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws java.io.IOException {
String type = req.getParameter("type");
// Now what i want is if i get a parameter value as adv2 then i should call a method in adv2 [eg.adv2.getText()], if parameter value is adv 49 i should call the method in adv 49.[eg adv49.getText()]
}
}
现在我想要的是如果我得到一个参数值为adv2然后我应该调用adv2中的方法,如果参数值是adv 49我应该调用adv 49中的方法。有没有任何简单的方法来做到这一点而不使用if(req.getParameter(“type”)。equals(“adv2”)){adv2.getText();} 50次?
答案 0 :(得分:2)
您所拥有的是String
,并且您想要查找与其对应的Object
。听起来像是我的地图:
// I'm assuming that this interface (or something like it) exists:
public interface Textual {
String getText();
}
// Then in the servlet...
private Map<String, Textual> advs = new HashMap<String, Textual>(50);
public init() {
advs.put("adv1", context.getServletContext("adv1"));
advs.put("adv2", context.getServletContext("adv2"));
...
}
public void doGet(HttpServletRequest req,HttpServletResponse res) {
String type = req.getParameter("type");
Textual adv = advs.get(type);
adv.getText(); // do something with this of course...
}
根据配置的脆弱性,重构init
方法实现也是一个非常好的主意。例如,定义包含Set
,adv1
,...的字符串的静态adv2
,然后在此集合上使用foreach循环来填充地图。如果您确定ID永远不会更改格式,您甚至可以使用1到50之间的简单循环,每次查找"adv" + i
。
答案 1 :(得分:1)
您的adv *变量应该扩展公共超类或实现通用接口。 因此,请参阅以下代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext context = getServletContext();
String type = request.getParameter("type");
Adv adv = (Adv)context.getAttribute(type);
if(adv != null){
...
// do something with your adv
}else{
...
// do something else
}
}
答案 2 :(得分:0)
您可以使用反射。如果你的servlet中有方法adv1,adv2等,你可以说:
getClass().getMethod(name).invoke(this);
答案 3 :(得分:0)
使用Map<String, TheTypeOfYourAdvVariables>
。你的代码片段不正确,所以我想你的意思是
private String adv1;
private String adv2;
public void init() {
ServletContext context = getServletContext();
adv1 = context.getInitParameter("adv1");
adv2 = context.getInitParameter("adv2");
}
所以,你可以使用Map<String, String>
并像这样填充它:
private Map<String, String> advs = new HashMap<String, String>();
public void init() {
ServletContext context = getServletContext();
adv1 = context.getInitParameter("adv1");
advs.put("adv1", adv1);
adv2 = context.getInitParameter("adv2");
advs.put("adv2", adv2);
}
然后你可以做
String theAdvType = request.getParameter("type");
String theAdvToUse = advs.get(theAdvType);
请注意,此说明很有用,因为它解释了如何使用地图。但在您的情况下,所有字符串都已存储在servlet上下文中,因此您实际上可以这样做:
String theAdvType = request.getParameter("type");
String theAdvToUse = servletContext.getInitParameter(theAdvType);