zoukankan      html  css  js  c++  java
  • javaEE servlet获取jsp内置对象

    既然jsp和servlet是等价的,在jsp中能够使用内置对象,那么在servlet中也能够使用。

    1.获得out对象

    能够使用例如以下代码获得out对象:

    import java.io.PrintWriter;

    ...

    public void doGet(HttpServletRequest request,HttpServletResponse response)throws 

    ServletException,IOException{

    PrintWriter out = reponse.getWriter();

    }

    ...

    只是默认情况下,out对象是无法打印中文的。这是由于out输出流中有中文却没有设置编码。解决问题能够将

    doGet代码改为:

    response.setContentType("text/html;charset=gb2312");

    PrintWriter out = response.getWriter();

    //使用out对象


    2.获得request和reponse对象

    ...

    public void doGet(HttpServletRequest request,HttpServletResponse response)throws 

    ServletException,IOException{

    //将reques參数当成request对象使用

    //将reponse參数当成response使用

    }

    ...


    3.获得session对象

    session对象相应的是HttpSession接口,在Servlet中它能够通过以下代码获得:

    import javax.servlet.http.HttpSession;

    ...

    public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

    HttpSession session = request.getSession();

    //将session当成session对象来使用

    }

    ...


    4.获得application对象

    application对象相应得是ServletContex接口,在Servlet中能够通过以下代码获得:

    import javax.servlet.ServletContext;

    ...

    public void doGet(HttpServletRequest request,HttpServletResponse response)throws 

    ServletException,IOException{

    ServletContext application = this.getServletContext();

    //将application当成application对象来使用

    }

    ...

    值得一提的是,能够使用application实现server内跳转。因为servlet和jsp的同质性,经常使用的servlet内跳转有两种:

    (1)重定向(相应jsp中的sendRedirect)

    response.sendRedirect("URL地址");

    (2)server内跳转(相应jsp中的forward)

    ServletContext application = this.getServletContext();

    RequestDispatcher rd = application.getRequestDispatcher("url地址");

    rd.forward(request,response);

    这两种在servlet内的跳转与jsp中提到的跳转是等效的。注意,两种情况下的url地址写法不一样。在第一种,假设写绝

    对路径,必须将虚拟文件夹跟文件夹写在里面,如"/Proj09/page.jsp"而另外一种方法中,不须要将虚拟路径根文件夹写在里

    面,如“/page.jsp”

  • 相关阅读:
    The Future of Middleware and the BizTalk Roadmap
    FW: How to spawn a process that runs under the context of the impersonated user in Microsoft ASP.NET pages
    Strips illegal Xml characters
    luogu P2280 激光炸弹(二维前缀和)
    luogu P2704 炮兵阵地(经典状态压缩DP)
    SP1716 GSS3 Can you answer these queries III (线段树维护最大连续子段和)
    二分图判定、匹配问题
    C++语法综合 | 基于char*设计一个字符串类MyString
    luogu P1044 火车进出栈问题(Catalan数)
    C++设计模式 | 三种设计模式基础
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3837098.html
Copyright © 2011-2022 走看看