Servlet的初步了解 --- JavaWeb

来源:互联网 发布:美股日内交易软件 编辑:程序博客网 时间:2024/06/11 23:45

如果从内置对象的常用角度来分析,常用: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
原创粉丝点击