码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet初步

时间:2015-09-10 19:42:46      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getSession().setAttribute("hello","Hello Servlet!");
        //response.sendRedirect(request.getContextPath()+"/01/02jstl.jsp");
        /*客户端跳转需要在服务端Seesion存值,不建议*/
        
        request.setAttribute("hello","Hello Servlet!");
        //web中WEB-INF下的路径在客户端无法访问,在服务端可以访问,安全性!
        RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/01/02jstl.jsp");
        rd.forward(request,response);
        /*服务端跳转,Dispatcher可以自动添加上下文路径,forward*/
        
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

}
/////////////////////////多业务支持
@WebServlet("/user02.do")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public UserServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
         * 动态获取访问的是哪一个操作
         * 1.if else会随着方法的增多而增多,不易管理(反射)
         * */
        request.setCharacterEncoding("UTF-8");//post传送需在服务端设置编码格式
        String method=request.getParameter("method");
        if("list".equals(method)){
            list(request,response);
        }else if("register".equals(method)){
            register(request,response);
        }else if("add".equals(method)){
            add(request,response);
        }
    }
    
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users=(List<User>) request.getSession()
                .getServletContext().getAttribute("storeUsers");
        request.setAttribute("users", users);
        request.getRequestDispatcher("/WEB-INF/user02/list.jsp").forward(request, response);
    }

    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/user02/register.jsp").forward(request, response);
    }
    
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String username=request.getParameter("username");
        String nickname=request.getParameter("nickname");
        int age=Integer.parseInt(request.getParameter("age"));
        
        /*
         * 此处将用户存储到application中
         * */
        List<User> users=(List<User>) request.getSession()
                .getServletContext().getAttribute("storeUsers");
        if(users==null){
            users=new ArrayList<User>();
        }
        User u=new User(username,nickname,age);
        System.out.println(u);
        users.add(u);
        request.getSession()
            .getServletContext().setAttribute("storeUsers",users);
        response.sendRedirect("user02.do?method=list");
    }

}
//////////////////////////////////////////////////MVC 初步
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        try {
            String method=request.getParameter("method");
            Method m=this.getClass().getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            String rel=(String) m.invoke(this,request,response);
            String redirStr="redirect:";
            if(rel.startsWith(redirStr)){//判断是服务端跳转还是客户端跳转
                response.sendRedirect(rel.substring(redirStr.length()));
            }else{
                request.getRequestDispatcher("/WEB-INF/"+rel).forward(request, response);
            }
            } catch (SecurityException e) {
            e.printStackTrace();
        }catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        
    }
}

@WebServlet("/user03.do")
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;
       
    public UserServlet() {
        super();
    }

    /*这是第3版,基于反射,父类BaseServlet继承HttpServlet实现service方法进行方法调用
     * 所有本类作为子类不需要实现doPost()和doGet(),只需要自己的逻辑方法
     * 不足之处:每个执行方法最后跳转代码都相同,应该想办法解决:参考list()和BaseServlet.class
     * */
    @SuppressWarnings("unchecked")
    public String list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users=(List<User>) request.getSession()
                .getServletContext().getAttribute("storeUsers");
        request.setAttribute("users", users);
        //request.getRequestDispatcher("/WEB-INF/user03/list.jsp").forward(request, response);
        return "user03/list.jsp";
    }

    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getRequestDispatcher("/WEB-INF/user03/register.jsp").forward(request, response);
        return "user03/register.jsp";
    }
    
    public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("子类增加方法测试:delete");
        return "user03/register.jsp";
    }
    
    public String update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("子类增加方法测试:update");
        return "user03/update.jsp";
    }
    
    @SuppressWarnings("unchecked")
    public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String username=request.getParameter("username");
        String nickname=request.getParameter("nickname");
        int age=Integer.parseInt(request.getParameter("age"));
        
        /*
         * 此处将用户存储到application中
         * */
        List<User> users=(List<User>) request.getSession()
                .getServletContext().getAttribute("storeUsers");
        if(users==null){
            users=new ArrayList<User>();
        }
        User u=new User(username,nickname,age);
        System.out.println(u);
        users.add(u);
        request.getSession()
            .getServletContext().setAttribute("storeUsers",users);
        //response.sendRedirect("user03.do?method=list");
        return "redirect:user03.do?method=list";
    }

}




Servlet初步

标签:

原文地址:http://my.oschina.net/686991/blog/504615

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!