JAVA开发(4) - Servlet中的几个对象

 Servlet中的几个对象:

HttpServletRequestHttpSessionServletContext,这三个对象都有

void setAttribute(String name, Object o)void removeAttribute(String name)<?XML:NAMESPACE PREFIX = O ?>

这两个方法,通过这两个方法我们可以很方便的进行参数的传递。

三个对象的作用域的大小分别由小到大。当我们把一个对象通过void setAttribute(String name, Object o)添加到这三个对象中的时候,除非我们显示的调用void removeAttribute(String name)或者当这三个对象自己销毁否则不会释放这些对象占用的空间,所以我们在将一个对象通过setAttribute添加到这三个对象时,需要注意用完了就remove(当然用完以后这个添加到的对象本身就快销毁时,我们也没必要多此一举)。而且尽量当对象存放在HttpServletRequest,然后才是HttpSession最后才是ServletContext。尽量不要把大对象存放在这些对象中,因为一个进程占用的资源毕竟是有限的。

Servlet中路径跳转的问题:

让我们先通过一个例子来看一下HttpServletRequest的获取路径的一些方法的返回值。

ServletPath:

 

package squall.servlet.path;



import java.io.IOException;

import java.io.PrintWriter;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;





public class ServletPath extends HttpServlet

...{



protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException

...{

showParam(req,resp);

}



protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException

...{

showParam(req,resp);

}

private void showParam(HttpServletRequest req, HttpServletResponse resp) throws IOException

...{

resp.setContentType("text/html");

PrintWriter out = resp.getWriter();

String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ";





out.println(docType + "<HTML> " + "<HEAD><TITLE> pathshow"

+ "</TITLE></HEAD> " + "<BODY BGCOLOR="#FDF5E6"> "

+"getContextPath(): " + req.getContextPath() + " </br>"

+"getPathInfo(): " + req.getPathInfo() + " </br>"

+"getRequestURI(): " + req.getRequestURI()+ " </br>"

+"getRequestURL(): " + req.getRequestURL()+ " </br>"

+"getServletPath(): " + req.getServletPath()+ " </br>"

+"getQueryString(): " + req.getQueryString()+ " </br>"

);



out.println("</body></html>");

}



}

你可能感兴趣的:(java,开发,的,中)