jsp-常用对象

    xiaoxiao2026-10-06  2

    request

    Cookie[] javax.servlet.http.HttpServletRequest. getCookies() 用于读取http请求的cookie,得到数组。 String javax.servlet.ServletRequest. getParameter(String arg0) 获得http请求的参数,同时适用于get请求与post请求。 void javax.servlet.ServletRequest. setCharacterEncoding(String arg0) 若http请求中有中文,可以对其进行编码,如用"utf-8"作为参数。 如果请求的URL为:http://localhost:8080/webapp/login 那么分别调用request.getContextPath( )、request.getServletPath( ) 、request.getURI( )、request.getURL( )分别返回什么路径? 1.request. getURI( )或者request.getRequestURI()返回HTTP请求行中请求URI的部分。上例中该方法将返回/webapp/login。 2.request. getContextPath( )返回web应用程序的路径,上例中该方法将返回/webapp。 3.request. getServletPath( ) 返回Servlet的路径。上例中该方法将返回/login。 4.request. getURL( )或者request.getRequestURL()返回请求的URL,上例中即为http://localhost:8080/webapp/login。

    response

    void javax.servlet.http.HttpServletResponse. addCookie(Cookie arg0) 给客户端添加cookie。

    响应图片资源

    response.setContentType("image/jpeg"); OutputStream outputStream =response.getOutputStream(); outputStream.write(captcha.getCaptchaImageData());//写入byte数组 outputStream.flush(); outputStream.close(); outputStream=null; response.flushBuffer(); out.clear(); out=pageContext.pushBody();//这些语句都为必须,不然会报<span style="font-family: Arial, Helvetica, sans-serif;">response.getOutputStream() has already been called 等错误。</span> void javax.servlet.http.HttpServletResponse. sendRedirect(String arg0) 令客户端跳转向到其他页面,普通的get请求,不携带额外数据。 浏览器地址栏内容也会改变。

    session

    session代表一次用户会话,从访问网站开始,到用户关闭浏览器为止。session范围内的属性可以在一个网站的多个页面跳转之间共享。通常用于 判断用户是否登录。 Object javax.servlet.http.HttpSession. getAttribute(String arg0) 返回session中arg0属性的值。返回是Object,通常需要再做类型转换。 void javax.servlet.http.HttpSession. setAttribute(String arg0, Object arg1) 设置session中arg0属性的值为arg1。 <% String str=(String)session.getAttribute("name"); if(str==null) session.setAttribute("name", new String("XiaoMing")); else out.write("your name is "+str); %> </body>一个页面中有了上述代码,那么两次访问网页的效果见下。

    application

    用于数据交换,对于整个web应用有效。范围从大到小依次是application\session\request\page.

    out

    out对象代表一个页面输出流,用于输出文本信息,如<% out.write();%> ,也可以使用<%=表达式%>,二者效果相同。 <%=表达式%>:百分号与等号不能有间隔,表达式语句最后没有分号。
    最新回复(0)