1. 程式人生 > 其它 >servlet層呼叫方法if和switch的區別

servlet層呼叫方法if和switch的區別

1.這樣是可行的

if("insert".equals(method)) {
    insert(request,response);

}
else if("delete".equals(method)) {
    try {
        delete(request,response);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
else if("update".equals(method)) {
    update(request,response);
}
else if("list".equals(method)) {
    try {
        list(request,response);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}}

  2.這樣不行

switch(method){
            case "insert":
                insert(request,response);break;
            case "delete":
             try {
                    delete(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "update":
                try {
                    update(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "list":
                try {
                    list(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;


        }

  3.但是這麼寫可以

switch (method){
            case "findAll"://查詢所有資料
                List<Student> list = studentRepository.findAll();//呼叫StudentRepository中的findAll()方法
                req.setAttribute("list",list);//存入request中
                req.getRequestDispatcher("index.jsp").forward(req,resp);//轉發到index.jsp中
            case "delete"://刪除操作
                String idStr=req.getParameter("id");
                Integer id=Integer.parseInt(idStr);
                studentRepository.deleteById(id);//根據id刪除
                resp.sendRedirect("/student");
                break;
            case "findById":
                idStr=req.getParameter("id");
                id=Integer.parseInt(idStr);
                req.setAttribute("student",studentRepository.findById(id));
                req.getRequestDispatcher("update.jsp").forward(req,resp);
                break;
            case "add":
                req.getRequestDispatcher("add.jsp").forward(req,resp);
        }