这样写可以换成switch了,但是如果cmds里有插入,删除还是需要修改switch的。 不如自定义enum类。 然后写成这样: switch(CMD_ENUM.parse(cmd_string)) { case CMD_ENUM.DOWNLOAD:... case CMD_ENUM.REGISTER:...}
这个一般这么做public static final int DOWN = 1 ;..... 然后switch() case 所以传入变量的时候..建议放数字...如果嫌麻烦..就弄个map吧..map.put("down",1) ;前提说明这样做没效率而且告诉你个秘密java里面if (){} if (){} if (){} if (){} if (){} if (){} 和 if(){} else if{} else if{} else if{} else if{} else if{} 没有区别的..这样如果你不用switch..他会给你从头比到尾的....
接分 String str="内容" List list=Arrays.asList("123","234","内容"); if(list.contains("str")){ sysout; }
如果是没的。也没什么好办法
if(str.equal("other1")){}else if(str.equal("other2")){}else if(str.equal("other3")){}else .......
switch(str.charAt(0)
{
case '1':
………
}[[/code]
否则的话,就视情况而定了。
你可将完整代码贴上来,大家帮你想想办法优化。
ruby的话switch就可以用字符串。
log.info("下载");
}else if(cmd.equal("upload")){
log.info("上传");
}else if(cmd.equal("getList")){
log.info("获取列表");
}else if(cmd.equal("register")){
log.info("注册");
}else if(cmd.equal("sort")){
log.info("排序");
}else if(.......就是类似上面的形式,用switch不行啊:
1.字符串
2.不是可以转换成int的字符串
3.用字符串中的某个字符也不行,可能出现重复
String cmd=request.getParameter("cmd"); if(cmd.equal("download")){
log.info("下载");
}else if(cmd.equal("upload")){
log.info("上传");
}else if(cmd.equal("getList")){
log.info("获取列表");
}else if(cmd.equal("register")){
log.info("注册");
}else if(cmd.equal("sort")){
log.info("排序");
}else if(.......
就是类似上面的形式,用switch不行啊:
1.字符串
2.不是可以转换成int的字符串
3.用字符串中的某个字符也不行,可能出现重复
谢谢你的提醒,这样可以防止NULL异常!
如果你想用switch的话.可以在页面选择的时候带一个值嘛.在实现里处理下嘛.
switch (Integer.parseInt(str){
case 1:{
...
break;
}
case 2:{
...
break;
}
case ...
}
不过这个方法有局限性,只能case整形或者能转变为整形的条件。如果条件比较复杂,就只能用你那个代码
//要保证cmds是有序的.
int index=Arrays.binarySearch(cmds,cmd);log.info(cmds[index]);
//
download=下载
//...//String str="download";
log.info(map.get(str));
不如自定义enum类。
然后写成这样:
switch(CMD_ENUM.parse(cmd_string)) {
case CMD_ENUM.DOWNLOAD:...
case CMD_ENUM.REGISTER:...}
如果你是struts的action,可以使用DispatchAction, 如果有必要的话也可以仿照它的做法自己写个工具类
String[] chineseCmds={"下载","获取列表","注册","排序","更新"....
//要保证cmds是有序的. 两者对应
int index=Arrays.binarySearch(cmds,cmd); log.info(chineseCmds[index]);
20楼的办法可行.做一Map,挺简单。
也可以考虑用Map
可以做一Map。做对应关系,使用的时候直接取就可以了。
应该不错的选择
用IF判断后并不只是输入日志,还有相应的业务代码啊!!真是不好意思!!String cmd=request.getParameter("cmd"); if(cmd.equal("download")){
log.info("下载");
/*下面是下载的处理代码*/
}else if(cmd.equal("upload")){
log.info("上传");
/*下面是上传的处理代码*/
}else if(cmd.equal("getList")){
log.info("获取列表");
/*下面是获取列表的处理代码*/
}else if(cmd.equal("register")){
log.info("注册");
/*下面是注册的处理代码*/
}else if(cmd.equal("sort")){
log.info("排序");
/*下面是排序的处理代码*/
}else if(.......
如果像这种的,用Map不就可以了吗。
String cmd=request.getParameter("cmd");
this.getClass().getMethod(cmd).invoke(null);public void upload(){
// upload...
}
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序");Iterator ite = keySet().iterator();
while(ite.hasNext()){
String key = (String)ite.next();
if cmd.equals(key){
log.info(m.get(key).toString());
break;
}
}
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序"); Iterator ite = m.keySet().iterator();
while(ite.hasNext()){
String key = (String)ite.next();
if cmd.equals(key){
log.info(m.get(key).toString());
break;
}
不同的业务cmd放在不同的文件中
写个map不容易维护,要是你一旦出错,去查看cmd和业务之间是否对应也是个困难
拆分cmd,就lz的写法我觉得不错啊,根据cmd去查看相关的业务很容易找到
你的意思是这样?
public interface Myfunction{
}public class Download implement Myfunction{}public class Register implement Myfunction{}
......//以下省略但是我怎样才能在收到cmd的时候选择不通的类啊?
嗯~~~如果没有其他方法只有用if else了~~
其实我只是怕我知道的不够多,写了那么多if else浪费时间~~~
用invoke()想法不错,但是因为每个方法的参数有可能不相同,就不好做了。
参数不同,你让它相同不就行了。Object[]做参数,方法里再转,或者你把request做参数,呵呵。
不建议你用这方法。
直接if else没什么不好地,而且便于阅读。
但是如果为了避免将来出现越来越多的if-else情况,就是说你可能会在后续过程中添加这样的配对组合,我推荐使用下command模式。把if中的条件和具体的行为变成方法封装起来,这样是比较好。程序员确实应该避免越来越多的if-else的情况,如果楼主也有这样的想法,可以去GOOGLE下命令模式。如果觉得模式比较麻烦,其实也没有什么关系
if(str.equal("1")){}else if(str.equal("1")){}else if(str.equal("1")){}else .......
结构已经很清晰了,能用switch代替更好,不能就用这个,再用Map什么的反而复杂化了。
然后
Myfunction mf = Class.forName(cmd).newInstance();
mf.xxxMethod();//接口里定义的方法。
Myfunction mf = Class.forName(cmd).newInstance();
mf.xxxMethod();//接口里定义的方法。
if / else 多了嘛 可以用switch-case 嘛
只能是int和枚举 型 啊
老大你懂 switch-case 吗?
只能是int和枚举 型 啊
if()
方法一
else if
方法二
.....
楼上有很多好意见了 用map或者枚举 看楼主喜好了
HttpServletRequest request, HttpServletResponse response)
throws IOException {
String cmd=request.getParameter("cmd").trim();//指令名,对应CommandProcess中的方法名
/*
* 指令列表
* 下载文件:cmd=download&file=product/mlns/C053.gif&userid=1
* 注册:cmd=register
* 登陆:cmd=login&userid=1&psw=jh45dd
* 修改密码:cmd=changePsw&userid=1&oldpswjh45dd&newpsw=kl8547
*/
CommandProcess commandProcess=new CommandProcess(request,response);
Method method = null;
try {
method = commandProcess.getClass().getMethod(cmd);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
log.info("找不到名为"+cmd+"的方法!请注意大小写!"+e.getMessage());
}
try {
method.invoke(commandProcess);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
import java.io.IOException;
import java.util.HashMap;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.iwit.noteService.bean.User;
import com.iwit.noteService.dao.DaoFactory;
import com.iwit.noteService.util.FunctionUtil;/**
*
* @author luhang E-mail:[email protected]
* @version 创建时间:Aug 18, 2009 11:46:33 AM
*
*/
public class CommandProcess {
Logger log = Logger.getLogger(CommandProcess.class);
HashMap<String,String> configs=DaoFactory.getConfigDao().getAllConfig();
HttpServletRequest request;
HttpServletResponse response;
public CommandProcess(HttpServletRequest request,
HttpServletResponse response) {
super();
this.request = request;
this.response = response;
}
/**
*
*下载文件
* @return 路径
*/
public void download(){
String result="Failure";
try {
int userid=Integer.parseInt(request.getParameter("userid"));
result=configs.get("download_url")+request.getParameter("file");
} catch (NumberFormatException e) {
// TODO: handle exception
}
try {
response.getWriter().write(result);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("Web相应异常!"+e.getMessage());
}
}
/**
* 用户注册
* @return ID+PSW
*/
public void register(){
String result="Failure";
String timmill=System.currentTimeMillis()+"";
String psw=FunctionUtil.GenerateRandomStr();
User user=new User(FunctionUtil.EncoderByMd5(psw),timmill);
if(DaoFactory.getUserDao().insertUser(user)){
log.debug("新用户注册成功!");
user=DaoFactory.getUserDao().getNewUserByRe(timmill);
result=user.getU_id()+"+"+psw;
}else{
log.info("新用户注册失败!");
}
try {
response.getWriter().write(result);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("Web相应异常!"+e.getMessage());
}
}
public void login(){
String result="Failure";
try {
int userid=Integer.parseInt(request.getParameter("userid"));
String psw=request.getParameter("psw");
User user=DaoFactory.getUserDao().getUserById(userid);
if(user.getU_psw().equals(FunctionUtil.EncoderByMd5(psw))){
log.debug("ID:"+userid+"登陆成功!");
result="Logined";
}else{
log.info("ID:"+userid+"登陆失败,密码错误!");
}
} catch (NumberFormatException e) {
// TODO: handle exception
log.info("非法的用户ID!"+e.getMessage());
}
try {
response.getWriter().write(result);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("Web相应异常!"+e.getMessage());
}
}
public void changePsw(){
String result="Failure";
try {
int userid=Integer.parseInt(request.getParameter("userid"));
String oldPsw=request.getParameter("oldpsw");
User user=DaoFactory.getUserDao().getUserById(userid);
if(user.getU_psw().equals(FunctionUtil.EncoderByMd5(oldPsw))){
String newPsw=request.getParameter("newpsw");
user.setU_psw(FunctionUtil.EncoderByMd5(newPsw));
if(DaoFactory.getUserDao().updateUser(user)){
log.debug("ID:"+userid+"密码修改成功!");
result="PswChanged";
}else{
log.debug("ID:"+userid+"密码修改失败!");
}
}else{
log.info("ID:"+userid+"旧密码错误!");
}
} catch (NumberFormatException e) {
// TODO: handle exception
log.info("非法的用户ID!"+e.getMessage());
}
try {
response.getWriter().write(result);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("Web相应异常!"+e.getMessage());
}
}
//下面还有好多方法........
}
然后switch() case 所以传入变量的时候..建议放数字...如果嫌麻烦..就弄个map吧..map.put("down",1) ;前提说明这样做没效率而且告诉你个秘密java里面if (){} if (){} if (){} if (){} if (){} if (){}
和 if(){} else if{} else if{} else if{} else if{} else if{}
没有区别的..这样如果你不用switch..他会给你从头比到尾的....
String str="内容"
List list=Arrays.asList("123","234","内容");
if(list.contains("str")){
sysout;
}
很有道理的,不要小看,能防止空指针!!
调用直接就是xxx.do?cmd=命令
或者自己写个Action,支持 xxx/命令.do格式的不就行了,这么麻烦啊
呃~~~注意看这个,我用的就是DispatchAction,自定义的Action方法command:
public ActionForward command(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
String cmd=request.getParameter("cmd").trim();//指令名,对应CommandProcess中的方法名
/*
* 指令列表
* 下载文件:cmd=download&file=product/mlns/C053.gif&userid=1
* 注册:cmd=register
* 登陆:cmd=login&userid=1&psw=jh45dd
* 修改密码:cmd=changePsw&userid=1&oldpswjh45dd&newpsw=kl8547
*/
CommandProcess commandProcess=new CommandProcess(request,response);
Method method = null;
try {
method = commandProcess.getClass().getMethod(cmd);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
log.info("找不到名为"+cmd+"的方法!请注意大小写!"+e.getMessage());
}
try {
method.invoke(commandProcess);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}我说的是在方法里面怎么避免大量的if else语句,如果都用DispatchAction中的方法更不好吧~~
Map m = new HashMap();
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序");
Iterator ite = m.keySet().iterator();
while (ite.hasNext()) {
String key = (String)ite.next();
if (cmd.equals(key)) {
log.info(m.get(key).toString());
break;
}
}
m.put("download","下载");
m.put("upload","上传");
...
m.put("sort","排序"); Iterator ite = m.keySet().iterator();
while(ite.hasNext()){
String key = (String)ite.next();
if cmd.equals(key){
log.info(m.get(key).toString());
break;
}