web.xml裏面能夠定義兩種參數:
(1)application範圍內的參數,存放在servletcontext中,在web.xml中配置以下:java
(2)servlet範圍內的參數,只能在servlet的init()方法中取得,在web.xml中配置以下:web
在servlet中能夠經過代碼分別取用:
app
System.out.println("下面的兩個參數param1是在servlet中存放的");ide
第一種參數在servlet裏面能夠經過getServletContext().getInitParameter("context/param")獲得
第二種參數只能在servlet的init()方法中經過this.getInitParameter("param1")取this
<context-param>
<param-name>count</param-name>
<param-value>1200</param-value>
</context-param>url
<servlet>
<description>loginServlet</description>
<display-name>loginServlet</display-name>
<servlet-name>loginServlet</servlet-name>
<servlet-class>loginServlet</servlet-class>
<init-param>
<description>系統初始化數</description>
<param-name>num</param-name>
<param-value>100</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>spa
獲取參數的方法以及異同cdn
String username=request.getParameter("username");
response.setCharacterEncoding("gb2312");
System.out.println("getServletContext():"+getServletContext());
ServletContext context=getServletConfig().getServletContext();
String num=context.getInitParameter("num");// <init-param> 獲取不到值
String count=context.getInitParameter("count");//<context-param> 獲取到值
System.out.println("num:"+num);//null
System.out.println("count:"+count);//1200
System.out.println("num:"+getServletConfig().getInitParameter("num"));//100獲取到值
System.out.println("count:"+getServletConfig().getInitParameter("count"));//null獲取不到值
System.out.println("request.getSession().getServletContext():"+request.getSession().getServletContext());
request.setAttribute("username", username);
PrintWriter out=response.getWriter();
out.println("獲取的用戶名是:"+username);xml
================================================================blog
一、URL中含有兩個問號'?? '的處理
解決:先以/*作全匹配,再分配給其他servlet進行處理, url的匹配順序,參考:http://tianya23.blog.51cto.com/1081650/1001568
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws IOException, ServletException {
- HttpServletRequest httpRequest = null;
- if (request instanceof HttpServletRequest) {
- httpRequest = (HttpServletRequest) request;
- } else {
- throw new RuntimeException("not http request");
- }
- String queryString = httpRequest.getQueryString();
- if (queryString != null && queryString.startsWith("?")) {
- request.getRequestDispatcher("/taobao").forward(httpRequest, response);
- } else {
- chain.doFilter(httpRequest, response);
- }
- }