Servlet的初步了解 --- JavaWeb

如果从内置对象的常用角度来分析,常用:request、response、config、session、application,但是千万要记住:PageContext不能够在Servlet里取得,因为它属于JSP页面。
1、取得session对象
Session与浏览器中的Cookie有关,因为所有用户发送请求的时候,保存的Cookie都会随着头信息发送给服务器,那么如果用户要想取得session对象就可以通过HttpServletRequest接口完成,在此接口中定义有如下一个方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // 处理get请求 
    HttpSession session = request.getSession() ; 
    // 取得Session对象 
    System.out.println(session.getId() + " ********************");
}

2、取得application对象
JSP中有application对象往往会被getServletContext()方法所替代,实际上这个方法就可以通过Servlet的父类取得,在GenericServlet类中定义有取得对象的方法:public ServletContext getServletContext()。

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        // 处理get请求 
        ServletContext app = super.getServletContext() ;
        System.out.println(app.getRealPath("/") + " *************"); 
    }

要注意的是:
1、 HttpSession接口对象取得依靠的是HttpServletRequest(http协议);
2、 ServletContext接口对象取得依靠的是GenericServlet(不受协议控制)。


3、页面跳转
在JavaScript、JSP、HTTP中实现页面跳转有以下几种方法:

  • 客户端跳转(页面改变,执行完跳转,不能传递request属性);
  • 服务器端跳转(页面不改变,立刻无条件跳转,可以传递request属性);
    由JSP跳转到Servlet可以很简单实现,例如:超连接、window.location、头刷新(response.setHeader(“refresh”,”时间;URL=路径”) )、response.sendRedirect()、;

Servlet中的跳转:
客户端跳转:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // 处理get请求 
    request.setAttribute("att-1", "REQUEST 属性");
    request.getSession().setAttribute("att-2", "SESSION 属性"); 
    response.sendRedirect("show.jsp"); 
}

服务器端跳转:
必须依靠ServletRequest接口中提供的一个方法:public RequestDispatcher getRequestDispatcher(String path),跳转时必须跟上完整路径“/xxx”(“/”表示WEB项目的根目录)。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // 处理get请求 
    request.setAttribute("att-1", "REQUEST 属性");
    request.getSession().setAttribute("att-2", "SESSION 属性");
    rd.forward(request, response);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值