首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Servlet初步参数及其他

2012-12-26 
Servlet初始参数及其他最近在做一个东西的时候,用到servlet中的参数突然就分不清楚以下两者的关系:req.get

Servlet初始参数及其他

最近在做一个东西的时候,用到servlet中的参数突然就分不清楚以下两者的关系:

        req.getAttribute("name");        req.getParameter("name");

?汗颜啦,赶紧补习下。

?

这两个接口都位于ServletRequest中,用来处理请求间参数传递。首先来看看

?

public String getParameter(String name);

客户端和服务端之间的数据传递。比如从客户端发出一个http请求(GET/POST),请求中带有请求参数,那么就可以通过这个接口获取,其中所有的参数将作为String或null返回。比如有如下请求路径:

??? http://localhost:8080/sample/query.htm?name=aaa&age=12
那么可以通过以下方式获取到值

String name = req.getParameter("name")String age = req.getParameter("age")

当然,对POST请求中form表单的数据同样采用这种方式获取,其他类似的接口有:

public Enumeration getParameterNames();public String[] getParameterValues(String name);public Map getParameterMap();

?

public Object getAttribute(String name);

req.getAttribute()和setAttribute(String name, Object o)同时使用。考虑常见的场景,在执行一个查询操作后,需要将查询结果返回到页面展现,那么这个数据传递可以考虑如下使用
在servlet中:

req.setAttribute("list", new ArrayList<E>());

在页面需要获取到该数据

List list= (ArrayList)req.getAttribute("list");

?当然在现在的框架下这样的代码很少写了。

?

?

另一则,以下内容参考了http://hain.iteye.com/blog/70731

?

继续我们来看看servlet中的参数,主要有两种context-param和init-param

?

1、context-param 对应application范围内的参数,存放在servletcontext中,在web.xml中配置如下:

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/spring-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

?这是一个常见的加载spring的配置,这里需要在web容器启动时将spring的配置文件加载并将servletcontext装换为spring的容器中。当然基于这样的一个配置param-name是固定的contextConfigLocation了,可在相应的监听ContextLoaderListener父类中ContextLoader:

/** * Name of servlet context parameter (i.e., {@value}) that can specify the * config location for the root context, falling back to the implementation's * default otherwise. * @see org.springframework.web.context.support.XmlWebApplicationContext#DEFAULT_CONFIG_LOCATION */public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

这样就会根据这个路径去读取相关的配置文件完成加载,当然<context-param>是可以配置多个,同时也一般和一个listener相对应。
在servlet中获取该值使用

getServletContext().getInitParameter("contextConfigLocation"));

?

?

2、init-param这个就对应servlet中的参数,配置如下

<servlet><servlet-name>sales</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>name</param-name><param-value>this is a servlet init-param</param-value></init-param><load-on-startup>1</load-on-startup></servlet>

?在servlet中获取

this.getInitParameter("name")

热点排行