web.xml file configuration, Servlet API, several interfaces in Servlet

  web.xml file configuration                           

<servlet>
    <servlet-name>Servlet类名称</servlet-name>
    <servlet-class>Servlet所在位置</servlet-class>
    <load-on-startup>优先级</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>Servlet类名称</servlet-name>
  <url-pattern>映射地址</url-pattern>
</servlet-mapping>
  • <load-on-startup>num</load-on-startup>
    • When the WEB application starts, it will load and create the instance object of the servlet, and call the init() method of the servlet instance object. Application: Write an InitServlet for the WEB application. This servlet loads num as the priority at startup, and the smaller number is preferred. Level (range: 0-infinity)

  Servlet API                                   

HttpServletRequest 

The use of the HttpServletRequest interface is very similar to the request object of the JSP built-in object. The request object is actually an instance of the HttpServletRequest
interface implementation class, but its instantiation process is automatic and does not require customization.
In Servlet, the request object is also initialized by the container. If you want to use the request object in the program, you can use it directly without manual
initialization .

getRequestDispatcher(String path) 

Build a forwarding object, the parameter value is the address of the jump (show below)

 getHeaderNames()  Get the names of all request headers (show below)
getHeader(String name) Get the value corresponding to the request header name
method illustrate
public String getContextPath()  Returns the requested context path, which starts with "/" (i.e. returns the project name)
public Cookie[] getCookies()  Returns all cookie objects sent in the request, the return value is an array of cookies
public String getMethod() Returns the HTTP type used by the request, such as get, post, etc.
public String getQueryString()  Returns the string form of the parameters in the request, such as requesting MyServlet?username=timo, returns username=timo
public String getRequestURI() Returns the string form of the part between the hostname and the request parameter (without IP)
public StringBuffer getRequestURL()

Returns the requested URL without the requested parameters. Note that the data type returned by this method is
StringBuffer (with IP)

public String getServletPath() Returns the servlet path in the URI (the value in url-pattern), excluding the parameter information in the request
public HttpSession getSession() Returns the HttpSession object associated with the request
setAttribute(String name, Object o) set property value
getAttribute(String name) Get the attribute value (need to cast the type according to the set attribute)
setCharacterEncoding(String env)  Set character encoding set
getCharacterEncoding()  Get character encoding set
getParameter(String name) Get the value of the parameter, that is, get the value of ?user=timo&age=26
getParameterValues(String name) Get multiple values ​​of parameters, that is, get multiple values ​​of name in ?user=timo&name=jinxin
 getParameterNames()  The method of obtaining the name of the request parameter, that is, obtaining the name and age in ?user=timo&age=26 (there is a demo below)
getRemoteAddr() Get the IP of the sender of the request
getRemoteHost() Get the host name of the requester, if it cannot be resolved, return the IP directly

 

1  // getRequestDispatcher() usage 
2 RequestDispatcher d = request.getRequestDispatcher("/index.jsp");   // Get the forwarding object 
3 d.forword(request, response);   // Pass the request response to the next page
 4  
5  // getHeaderNames() combined with getHeader(String name) 
6 Enumeration<String> e = request.getHeaderNames();
 7  while (e.hasMoreElements()){
 8      String name = e.nextElement();
 9      System.out .print(name + ": " );
 10      String names = request.getHeader(name);
 11     System.out.println(names);
12 }
13 
14 // getParameterNames()跟getParameter(String name)联用
15 Enumeration<String> e1 = request.getParameterNames();
16 while(e1.hasMoreElements()){
17     String np = e1.nextElement();
18     System.out.println(np + ":");
19     String namer = request.getParameter(np); 
20     System.out.println(namer); 
21 }
22             

HttpServletResponse 

The use of the HttpServletResponse interface is very similar to the response object of the JSP built-in object. The response object is actually
an instance of the implementation class of the HttpServletResponse interface, but its instantiation process is automatic and does not require customization.
In Servlet, the response object is also initialized by the container. If you want to use the response object in the program, you can use it directly without manual
initialization .

method illustrate
public void addCookie(Cookie cookie) Write cookie information to the client
public void sendError(int sc)  Send an error response with error status code sc to the client
public void sendError(int sc, String msg)

Send a response containing error status code and error information to the client, the parameter sc is the error status code, and the parameter msg
is the error message

public void sendRedirect(String location)  Use the client to redirect to a new URL, the parameter location is the new address
setContentType(String type)  Set content type
setHeader(String name,String value)  Set response header information
setStatus  Set the response status code

 

1  /** 
2  * Several common uses of setHeader()
 3  */ 
4  
5  // Refresh the page once every 1 second 
6 response.setHeader("refresh", "1" );    
 7  
8  // Jump in 2 seconds Go to another page 
9 response.setHeader("refresh", "2;URL=otherpage.jsp" );
 10  
11  // Set no cache 
12 response.setHeader("expires", 0 );
 13 response.setHeader(" cache-control", "no-cache" );
 14 response.setHeader("pragma", "no-cache" );
15  
16  // Set compressed data 
17response.setHeader("content-encoding", "gzip");

  Several interfaces in Servlet                            

  ServletContext interface      

ServletContext defines a set of methods that a servlet can use to communicate with its servlet container. When the WEB container is started, it will create a corresponding ServletContext object for each web application, which represents the current web application.

The ServletContext object is contained in the ServletConfig object, and developers can obtain a reference to the ServletContext object through the ServletConfig.getServletContext method when writing servlets.

Since all servlets in a WEB application share the same ServletContext object, communication between servlet objects can be achieved through the ServletContext object. The ServletContext object is also commonly referred to as the context domain object.

The use of the ServletContext interface is very similar to the application object of the JSP built-in object. The application object is actually an instance of the ServletContext interface implementation class, but its instantiation process is automatic and does not require customization.

In Servlet, the application object must be obtained through the getServletContext() method of the HttpServlet interface. Use ServletContext as a domain object to share data among multiple servlet objects

So, the biggest role of ServletContext is: it can realize the communication between various Servlets! ! ! !

Get the ServletContext object:

    ServletContext con = request.getServletContext();

   ServletContext con = this.getServletConfig.getServletContext();

   ServletContext con = this.getServletContext();

方法 说明
void setAttribute(String name,Object obj)  设置共享属性
Object getAttribute(String name)  读取共享属性
void removeAttribute(String name) 移除共享属性
ServletContext getContext(String uri)  获取指定 uri的上下文对象
String getContextPath()  返回 web程序的上下文路径
String getInitParameter(String param)  获取上下文初始化参数,即获取web.xml中的<context-param>标签中的值
String getRealPath(String path)  返回资源在服务器上的真实路径,例如C:\Program Files\...
RequestDispatcher getRequestDispatcher(String path)  返回一个包装了路径信息的 Dispatcher对象

 

 1 /**
 2 * 关于getInitParameter()用法
 3 */
 4 
 5 // web.xml文件中
 6 <context-param>
 7     <param-name>username</param-name>
 8     <param-value>timo</param-value>
 9 </context-param>
10 <context-param>
11     <param-name>age</param-name>
12     <param-value>26</param-value>
13 </context-param>
14 
15 // Servlet中获取参数
16 ServletContext con = request.getServletContext();
17 con.getInitParameter("username");
18 con.getInitParameter("age");

 

  ServletConfig接口             

在 servlet 的配置项中,可以使用一个或多个<init-param>标签为当前 servlet 配置一些初始化参数。

web 容器在创建 servlet 实例对象时,会自动将这些初始化参数封装到一个 ServletConfig 对象中,并在调用 servlet 的 init 方法时,将 ServletConfig 对象作为参数传递给 servlet。

程序员通过操作 ServletConfig 对象就可以得到当前 servlet 的初始化参数信息

So,ServletConfig的作用是获取web.xml文件中的初始化参数

获取ServletConfig对象:

    ServletConfig config = this.getServletConfig();

方法 说明
public String getInitParameter(String name) 此方法返回 String 类型名称为 name 的初始化参数值
public Enumeration getInitParameterNames() 获取所有初始化参数名的枚举集合
public ServletContext getServletContext()  用于获取 ServletContext对象
public String getServletName()  返回 Servlet 对象的实例名,即获取类名

 

 

 

 

 

 1 /**
 2 * 关于ServletConfig的用法
 3 */
 4 
 5 // web.xml中
 6 <init-param>
 7     <param-name>username</param-name>
 8     <param-value>timo</param-value>
 9 </init-param>
10 <init-param>
11     <param-name>age</param-name>
12     <param-value>26</param-value>
13 </init-param>
14 
15 // Servlet中获取
16 ServletConfig config = this.getServletConfig();
17 // 通过getInitParameter()方法获取
18 String user = config.getInitParameter("username");
19 
20 // 通过getInitParameterNames()获取所有的参数名
21 Enumeration<String> e = config.getInitParameterNames();
22 while(e.hasMoreElements()){
23     String n = e.nextElement();
24     String v = config.getInitParameter(n);
25     System.out.println(v);
26 }

 

  RequestDispatcher接口         

要完成请求转发,那么就需要使用 javax.servlet. RequestDispatcher 接口 RequestDispatcher 对象由 Servlet 容器创建

  • 该对象封装了一个由路径标示的服务器资源
  • 利用该对象,可以把请求转发给其他的 Servlet 或者 JSP 页面

获取RequestDispatcher对象:

    ServletRequest接口提供的方法

        ---- getRequestDispatcher(String path);   该方法中参数路径可以以”/”开始,也可以不以”/”开始

    ServletContext接口提供的方法

        ---- getRequestDispatcher(String path);   该方法中参数路径必须以”/”开始,表示相对于上下文根路径

          ---- getNamedDispatcher(String name);   以部署描述符(web.xml)中的 Servlet 的名字作为参数,即要跳转的Servlet类名

方法 说明

void forward(ServletRequest req,
ServletResponse resp)

将请求从一个 Servlet 传递给另外一个 Servlet、JSP、HTML

void include(ServletRequest req,
ServletResponse resp)

 用于在响应中包含其他资源(Servlet/JSP/HTML)的内容

 

 

 

 

 

  几种跳转        

一、通过request.getRequestDispatcher()跳转\

1 RequestDispatcher r = request.getRequestDispatcher("/index.jsp");
2 r.foeword(request, response);

 

二、通过response.sendRedierct()跳转

三、通过response.setHeader()跳转

1 response.setHeader("refresh', "2;URL=index.jsp");  // 两秒之后跳转到index.jsp页面

 

四、通过RequestDispatcher对象实现servlet与Servlet之间的跳转

1 ServletContext sc = request.getServletContext();
2 RequestDispatcher rd = sc.getNamedDispatcher("要跳转的Servlet类名");
3 rd.forword(request, response);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325314323&siteId=291194637