Creating programs in Java for the help of Servlets. Java. HTTP protocol and WEB Java servlet and web container

Golovna / Additional functionality

What are servlets? Servlets, servers, modules for processing HTTP and FTP requests, calling for portals (web gates).

The basis of these portals is a powerful WEB server - a program, like trimming a server socket, accepting and transmitting data. Mostly, for the sake of speed, the server is written not in Java, but as my own programming (for example, in C ++).

The link to the server is based on the underlying servlet. The data server itself is managed by the data server, and in the same way, it is taken into account that the data is being managed by the client. In fact, the underlying servlet is the "brain" of the server. The main function of this servlet is to read the request of the client, decrypt it, decrypt it, pass it to the servlet robot, which type of information to request. Most of all, for the sake of accessibility, the role of the base servlet is played by the server itself. For example, Jacarta Tomcat is behind such a scheme.

The small diagram shows the transmission of requests (request) and replies (response) between the server and servlets. qia scheme I represent the work of the HTTP server, which may contain JSP pages and two resources "/sample1" and "/sample2", for the processing of these two servlets - "Sample1 Servlet" and "Sample2 Servlet" are visible.

Rozberemo pokrokovo those that depict a little one:

  1. the client comes to the server
  2. the server sends a request to the basic servlet ("Basic Servlet")
  3. the underlying servlet forfeited the URI to the resource
    • If the URI specifies "/sample1", it will ask more(without change) is passed to the "Sample1 Servlet" servlet, which is sent and processed by the request
    • If the URI points to "/sample2", the server sends a request to the "Sample2 Servlet" servlet
    • in other cases, the request is passed to the "JSP Servlet" module
  4. the servlet to which control was passed, processes the data, creates a response (response), after which the response is forced back to the base servlet.
  5. base servlet, don't process data back, immediately send it back to the server
  6. the server sees the data to the client

In this way, it is possible to solve the task of processing the request on the logical part, for the skin from which it is necessary to provide its own module, its own "programming key". In fact, the steps of the payment can be more rich. For example, for the "GET" and "POST" methods, different modules can be matched.

Servlet interface

Combine all these modules that stink around each other to help the javax.servlet.Servlet interface

Let's look at this interface. New has a total of 5 methods:

Public void init(ServletConfig config) throws ServletException This method is invoked to inform the servlet about those that are included as a client request service module. The config parameter expands the javax.servlet.ServletConfig interface, which carries information about the server, the name of the servlet, the basic parameters, and other goodies. The javax.servlet.ServletConfig interface will be discussed a little further. It should be passed that after the call to the functions of the servlet, carefully save the config in itself in the change and see it for the help of another method: public ServletConfig getServletConfig() creation, other information about the servlet that can be reached by the public String getServletInfo() call

To process the request and take the result of the processing, the function

Public void service(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException In this function, two tools are passed to the code to process the data: one is for retrieving these types of the server, the other is for editing the result of the servlet robot. It seems that the request and response parameters separate the javax.servlet.ServletRequest and javax.servlet.ServletResponse interfaces.

After the server ceases to require the module, the method is invoked

Public void destroy() which ends all operations on the servlet object.

ServletConfig interface

4 methods, whose names speak for themselves, form the essence of the javax.servlet.ServletConfig interface:

Public String getServletName() public ServletContext getServletContext() public String getInitParameter(String name) java.util.Enumeration getInitParameterNames()

I think the recognition of all functions was sensible, krim

Public ServletContext getServletContext() This method turns on the same core tool for working with the server:

ServletContext interface

ServletContext - interface that provides access to the next core functions:

Public Object getAttribute(String name) public java.util.Enumeration getAttributeNames() public void setAttribute(String name, Object object) public void removeAttribute(String name) Chotiri methods for working with attributes. The role of attributes vikonuє whether there is an object of any class. The meta of these functions is to cross between non-binding servlets of different objects. public String getInitParameter(String name) java.util.Enumeration getInitParameterNames() Access to parameters such as starting the server. Here you can find the name of the host, the port and other port numbers. public int getMajorVersion() public int getMinorVersion() Check the version of the Servlet API. public String getMimeType(String file) Returns the MIME association type of the file, going to the one specified in the changed file. Guess how it happened to get MIME from the SimpleWEBServer program and evaluate the efficiency! public java.util.Set getResourcePaths() java.net.URL getResource(String path) throws java.net.MalformedURLException public InputStream getResourceAsStream(String path) Turn paths to available resources for the server and the resources themselves to look like URL and look like data streams . public RequestDispatcher getRequestDispatcher(path) public RequestDispatcher getNamedDispatcher(name) RequestDispatcher is a tool for requesting another resource. These functions are needed to select the object of the tool for these resources. So, let's say, to redirect requests to the "sample1" servlet from the body of the servlet, you can do this: getServletConfig().getServletContext().getNamedDispatcher("sample1").forward(request, response);

In general, the RequestDispatcher class includes only two methods:

public void forward(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException public void include(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException For example, servlet 1 has another word "test 1", then it calls include for servlet two, which has another word "test 2". Servlet 2 simply uses the word "and". The result of robotic servlet 1 is the row "Test 1 and Test 2". public void log(String msg) Write to server log. public void log (String message, Throwable throwable) Specify a culprit and a phrase to be written to the log after the throw is removed. public String getRealPath(String path) Translate path type "/index.html" to "http://host/contextPath/index.html" public String getServerInfo() Return server name. Public ServletContext getContext(String uripath) This method allows the ServletContext to be exchanged between different resources of the same server. public String getServletContextName() Turn the servlet name to which object belongs to the ServletContect interface.

ServletRequest interface

The ServletRequest interface is a tool for retrieving parameters from an HTTP request. This interface may have methods that are identical to the name given to the ServletContext:

Public Object getAttribute(String name) public java.util.Enumeration getAttributeNames() public void setAttribute(String name, Object o) public void removeAttribute(java.lang.String name) public String getServerName() public RequestDispatcher getRequest

Methods, which are left out, allow you to easily process the HTTP header request:

Public String getCharacterEncoding() public void setCharacterEncoding(String env) java.io.UnsupportedEncodingException Working with character encoding on HTTP header fields. The functions set the method of decoding CGI inputs from the %NN form of the primary character. For example, some standard is KOI8-R, windows-1251 or UTF-8 is necessary to decipher Cyrillic characters. public int getContentLength() public String getContentType() Reads "Content-Length", "Content-Type" fields from HTTP request. public jString getParameter(String name) public java.util.Enumeration getParameterNames() public String getParameterValues(String name) public java.util.Map getParameterMap() Functions to retrieve the HTTP header field from that value. public ServletInputStream getInputStream() throws java.io.IOException public java.io.BufferedReader getReader() throws java.io.IOException Reader zastosovuetsya for reading text information- vin automatically decrypts the rows in the same way up to the specified charset. Respect! J2EE version 1.3 has a bug: when decrypting the character %25 (the % character in Post and Get requests), Reader sees a pardon (a bug of notes on Tomcat 4 and Resign servers). It is possible that a similar bug can be used with other symbols. public String getProtocol() Get the HTTP version of the protocol for the request (for example, "HTTP/1.1"). public String getScheme() Turn the schema name on. For example, "http", "https", or "ftp". public int getServerPort() public String getRemoteAddr() public String getRemoteHost() public boolean isSecure() Server port, client IP address, client hostname, and ciphertext (over HTTPS protocol) public java.util.Locale getLo java.util.Enumeration getLocales() Localization of the document that is expected to be accepted by the client (the result of processing the "Accept-Language" field)

ServletResponse interface

The ServletResponse interface is the ultimate tool for enforcing data for the client. Useful methods this tool serve my own purpose:

Public java.lang.String getCharacterEncoding() public void setLocale(java.util.Locale loc) public java.util.Locale getLocale() The first way is to convert the MIME encoding type (eg UTF8) so that the information is displayed. The other two methods also work from charset. The stench speaks of language, which is written in documents (for example, Russian). public ServletOutputStream getOutputStream() throws java.io.IOException Turn the output stream for the servlet. Tsey potik vikoristovuetsya, for example, for seeing binary files. Text data can be displayed with the help of java.io.Writer: public java.io.PrintWriter getWriter() throws java.io.IOException This method automatically converts rows to the charset specified by getCharacterEncoding() and getLocale() methods. public void setContentLength(int len) This method sets the value of the HTTP header field "Content-Length" public void setContentType(String type) Method for overriding the MIME type in the document. HTTP header field "Content-Type". public void setBufferSize(int size) public int getBufferSize() public void flushBuffer() throws java.io.IOException public void resetBuffer() Right in that the data is being buffered. This means that the next part of these data will be seen by the client only after the buffer is filled. The designated methods allow, optionally, to set the edit buffer size, remove the edit buffer, initialize the edit to the client buffer without checking the data buffer, and also clear the data buffer. public boolean isCommitted() This method can be used to retrieve the ensign, which has already been sent to the client. The flag will be positive, as the HTTP header has already been sent. public void reset() Even though the HTTP header is not yet in control, this method "resets" the HTTP header to the value of "closed".

Servlet Types

Java Servlet API, the world's most powerful interface, also includes a few servlet classes that can be the basis for your programs.

The base for all these classes is the abstract class javax.servlet.GenericServlet:

Public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable

As can be seen from the assigned class, all methods of Servlet and ServletConfig interfaces can be used. Not implemented by the method

Public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException whichever is abstract.

On the basis of this class, another abstract class was created - javax.servlet.http.HttpServlet:

Public abstract class HttpServlet extends GenericServlet implements java.io.Serializable

This class has been created in a way that reaches the concept of "more efficiency for a programmer" and a lot of different methods:

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException protected void doGet(HttpServletRequest req, HttpServletResponse resp)ServiceException,Exception,Exception java.io.IOException protected void service(HttpServletRequest req, HttpServletRequest req, HttpServletRequest req, HttpServletRequest , ServletR esponse res) throws ServletException, java.io.IOException Different service(ServletRequest req, ServletResponse res) options for different HTTP DELETE and GET methods to PUT and TRACE.And in order to manually receive data over the CGI interface without decoding the header of the creation of the HttpServletRequest and HttpServletResponse classes, which are included in the HttpServlet package in the javax.servlet.http package protected long getLastModified(HttpServletRequest req) This method turns hour by hour value vin take from field "Date" HTTP for ask the head. If the field is not shown, then turn -1.

It is possible to parse the HttpServletRequest and HttpServletResponse interfaces. The stench is the downside of ServletRequest and ServletResponse.

HttpServletRequest creme methods, degrading ServletRequest types, may be similar methods:

Cookie getCookies() Returns the set of cookies sent by the client to the server.

The Cookie class, which belongs to the same javax.servlet.http package, can contain all information about cookies. The most important methods of this class

Int getMaxAge() String getName() String getValue() apparently, how many times has a cookie lost its life, that cookie has that value. Also Cookie (String name, String value) void setValue (String newValue) void setMaxAge (int expiry) to set a cookie, set its maximum age value. long getDateHeader(String name) Return the date from the HTTP header, so it is. int getIntHeader(java.lang.String name) Returns the numeric value of the field named name from the HTTP request header String getMethod() Returns the HTTP request method. String getQueryString() String getRequestURI() StringBuffer getRequestURL() Returns the string to be found in the document's URL after the character "?", the document's URI and that URL. HttpSession getSession() HttpSession getSession(boolean create) boolean isRequestedSessionIdFromURL() boolean isRequestedSessionIdValid() Functions. allow practice with such the most important transmission mechanism, like a session.

Sessions are necessary in order to gravitate for the hard-earned data from side to side. For example, koristuvach go to the side (1), deduct data for the side (2), and that saves more speech for the side (3).

In principle, on the side (1) you can send the data of the koristuvachev, then take it off on the side (2), add it, send the koristuvachev... In a similar manner, you can gradually transfer the entire set of data from the client to the server and back, moreover, a lot of times. Besides, what you don’t get overpowered like that, it devours traffic.

You can just work it out otherwise - beat the mechanism of sessions. The mechanism of this work is as follows: data, send a message, save the server in an okremu file - session files. In this file, all work will be carried out to change data. The client can see the "session key" (in the same Session key, in the same Sesseion ID) - a unique indicator for the file, which can revenge itself for this koristuvach. Now, in order to take all the data from any client, the server only needs to know the session key. The prize of this is the sturdiness and speed of his victoriousness.

Axis and all major ways to the HttpServletRequest interface. New list See the Java Servlet API documentation for methods.

Now about the HttpServletRequest interface. The main vіdminnіst klаіv, yakі razdіlyаyat tsey interfes, yоmu, scho vіdіvatsya v_drazu. At the same time, the compilation of all data from HTTP is considered. It will be overpowered only after the completion of the HttpServlet.service() work.

And so, about the methods:

Void addHeader(String name, String value) void addIntHeader(String name, int value) void addDateHeader(String name, long date) Method to add parameters to the HTTP header. The rest method sets the "Date" parameter. void addCookie(Cookie cookie) Method to add a cookie to the header boolean containsHeader(String name) Allows you to know what the header of the value parameter should be. String encodeURL(String url) String encodeRedirectURL(String url) The first method is to encode chars with the help of replacing %NN. Another method to rob the same and click void sendRedirect(String location) void setStatus(int sc) void sendError(int sc) void sendError(int sc, String msg) The first one is to set the turn code, the other two are to send an alert about a pardon. In the interface, it is possible to set the next break for the sc parameter, which matches the HTTP protocol turn codes: (303) SC_NOT_MODIFIED - Status code (401) SC_UN - Status code (404) SC_METHOD_NOT_ALLOWED - Status code (405) SC_NOT_ACCEPTABLE - Status code (406) SC_PROXY_AUTHENTICATION_REQUIRED - Status code (407) SC_REQUEST_TIMEOUT - Status code (408) SC_CONFLICT - Status (409) SC_GONE - Status code (410) SC_LENGTH_REQUIRED - Status code (411) SC_PRECONDITION_FAILED - Status code (412) SC_REQUEST_ENTITY_TOO_LARGE - Status code (413) SC_REQUEST_URI_TOO_LONG - Status code (414) SC_UNSUPPORTED_MEDIA_TYPE - Status code (415) SC_REQUESTED_RANGE_NOT_SATISFIABLE - Status code ( 416) SC_EXPECTATION_FAILED - Status code (417) SC_INTERNAL_SERVER_ERROR - Status code (500) SC_NOT_IMPLEMENTED - Status c ode (501) SC_BAD_GATEWAY - Status code (502) SC_SERVICE_UNAVAILABLE - Status code (503) SC_GATEWAY_TIMEOUT - Status code (504) SC_HTTP_VERSION_NOT_SUPPORTED - Status code (505)

Axis and everything you can tell about HttpServletResponse

Using servlets in WEB add-ons

Now let's talk about using servlets in WEB programs. For whom I will bring two short stocks, which can become useful.

The first example shows the working methods of HttpServlet and the visualization in place of the HTML side at a glance. According to the idea HTML side in the browser window it should be displayed in plain text, but, in order to speed up the data, what is being sent, you can emboss GZIP. Modern browsers(Accept browsers of the 4th generation and more) support this method of transferring textual information and displaying the side in such a way that they didn’t squeeze it.

import java. io.*; import javax. servlet.*; import javax. servlet. http.*; import java. util. zip.*; // servlet with HttpServlet fallback public class ZipServlet extends HttpServlet( // Function to handle the GET method public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ( // set that the side is an HTML document response. setContentType("text/html"); // take the "Accept-Encoding" parameter from the HTTP header String encodings=request. getHeader("Accept Encoding"); // take the parameter "encoding" - before setting the encoding of the document String encodeFlag=request. getParameter("encoding"); // Kudi displaytimemo PrintWriter out; // just like the "Accept-Encoding" field on the request if (encodings != null) ( // This field must also contain the "gzip" value, but the encoding has not yet been set, if ((encodings. indexOf("gzip" ) != - 1 ) &&! encodeFlag. equals("none") )) ( // those where we will enter, will be for one and grab the text for help GZIP out = new PrintWriter(new GZIPOutputStream(response. getOutputStream()) , false); // and set the flag for the browser that the document will be squashed response. setHeader("Content-Encoding", "gzip"); ) else out = response. getWriter(); ) else // Otherwise, we will be able to live without a squeeze out = response. getWriter(); out. println("This is a test!!!"); // write the body of the document out. close(); // that zakryvaemo vysnovok. //Everything, once the work is completed, the document will be sent } }

Another example shows how a servlet can be used without interruption to see the side. This type of view of the sides can be played, for example, in chats: to read new notes, it will not be necessary to update the side, new notes will simply be downloaded for an hour. It is necessary to swear, such proxy servers do not support this kind of re-enforcing data, ale z cym - sorry - nothing can be done.

import java. io.*; import javax. servlet.*; // The program implements the Servlet interface class DoloadServlet implements Servlet ( ServletConfig config; // ServletConfig object public DoloadServlet() () // do nothing // save config on initialization public void init(ServletConfig config) throws ServletException ( this.config = config;) // see savings config public ServletConfig getServletConfig() ( return config;) // information about the servlet public String getServletInfo() ( return "DoloadServlet" ;) public void destroy() () // do nothing // request request public void service(ServletRequest request, ServletResponse response) throws ServletException, java. io. IOException( // We will not ask for help, just right away // create HTTP header: String head = "HTTP/1.0 200 OK\n" + + "Server: DoloadServlet\n" + "Content-Type: text/html; charset=UTF-8\n"+ "Connection: Keep Alive\n" + "Content-Encoding: multipart/mixed\n"+ "Transfer-Encoding: chunked" + "Pragma: no-cache\n\n" ; // now add post data // for this butt - 20 tags "
from the transferred row
for (int i = 0; i< 20 ; i++ ) head = head + "
\n" ; // take a baby ServletOutputStream os=response. getOutputStream(); // write there header and post data os. print(head); // overpower everything written to the buffer before the client response. flushBuffer(); // start adding new rows: // qi rows will look like this: row number, then "
\n"
// leather new row appears every 3 seconds int i = 0; while (true)( // lichnik's increment i++; // write the row os. print("" + i+ "
\n"); // flush buffer response. flushBuffer(); // Freeze potik for 3 seconds try ( sleep(3000 );) catch (Exception e)() ) )

It is lost to say that the servlet mechanism is more plastic and allows you to create such speeches, as they could use the writing of an external WEB server (like, for example, in the case of a resume servlet). The downside of the robotic servlet is the low speed of the first launch (the servlet is simply compiled by a JIT machine), the high memory loss and the failure of all programs in Java - the low speed of the work with rows. The rest of the environment becomes obsolete with robotic servlets that accept text data in POST request Oh. POST is requested from HttpServlet with a size of 50 kb when parsing for the help of HttpServletRequest.getReader() can paralyze the server robot for a couple of hvilins. The same applies to other java programs.

I'll give you two small examples:

// given row String text // Butt 1 // find the robot in a row for the additional "+" operation for String String test1 = ""; for (int i = 0; i< text. length(); i++ ) test1 += text. charAt(i); // Butt 2 // find the robot in a row for an additional buffer char buf = new char [text. length()]; for (int i = 0; i< text. length(); i++ ) buf[ i] = text. charAt(i); String sample2 = new String(buf);

If you take small rows - up to 2-3 kb, then the data in the robot application is not significant, if you take a text row with a size of 10 kb, then in the first step the program will work with the row significantly more. This is the peculiarity of java and є the problem of the implementation of the functions of the String class. So if you want to write a swedish servlet, be unique long rows to help the String class, for example, tag the StringBuffer class. This advancement should be carried out before us until the removal of great texts from the margins and processing of local files (for example, in the case of a text database for a guest book with a large number of references).

Another problem is the multitasking of the WEB system. Don't forget that your servlets can request an hourly sprat of koristuvachiv. Often the problems of data synchronization, exchange of data between different counting threads of the same servlet are blamed, and the most widespread problem is the problem of synchronous access to files and other naming resources of the system. For example, one program opened a file for reading, and sometimes it tries to write there. As a result, the other program either removes the blame, or checks while the file is called for recording. At the link with zim I want to turn back your respect: do not flood behind you unscreamed streams and close the streams, as only they were needed. Potik, obviously, closes automatically later, but it will only happen once, if the "smіttyar" gets to the new one, and at the same time, the other program does not have access to the file for recording.

In addition to multitasking, I want to note that for the additional methods "Object getAttribute(String name)" and "void setAttribute(String name, Object object)" to the ServletContext interface, you can exchange between servlets and data, including those that are synchronized.

Servlets (Servlets) - tse java-programs, yakі vykonuyutsya on the server side of the Web-programs. Just as applets dynamically expand the functionality of a Web browser, servlets dynamically expand the functionality of a Web server. If servlets can serve a call, stinks will be called to expand web servers. For such programs, the Java Servlet technology defines an HTTP-specific servlet class. The javax.servlet and javax.servlet.http packages provide interfaces and classes for creating servlets.

  • What is the structure of a web project?

  • What is a servlet container? Servlet lifecycle.

A servlet container is a program that manages the life cycle of servlets.
The life cycle of a servlet: it is controlled by a servlet container, the first time we go to the servlet, it gets hooked on the riddle and the init() method is called. By the way, the robotic program calls the service() method calls to process the client's requests. When the program is finished, the destroy() method is called, and the servlet is taken out of memory.

  • What is the definition, functionality of a servlet container?

A servlet container can be used as a full standalone web server, be a third party host of another web server, such as Apache, or integrate into a Java EE add-on server. Safe exchange of data between servlet and clients, taking on such functions as the creation of a software environment for the servlet that functions, identification and authorization of clients, organization of a session for the skin of them.

  • What is the difference between sendRedirect() and forward()?

For a JSP wiki, the forward() method is the most expensive way, for a JSP call, the sendRedirect() method is an absolute way. Vіdminnіst tsikh methodіv vіd scho z method forward() is already passed the main object request request, and the call to the sendRedirect() method forms a new request. Information in the remainder of the period should be transmitted with other objects. Until then, the forward() method is smarter.

  • What do you know about the filter servlet?

The implementation of the Filter interface allows you to create an object that can be used to change the request, you can transform the header and instead of the request of the client. Filters do not create a request, otherwise they change, it is less to modify them. The filter is passed in front of the request, the first one is used in the servlet, with the further (as necessary) processing of the input that comes out of the servlet. The filter can be interchanged with different types resources, zocrema and servlets, and JSP-sides. Servlet filters can:

  • override servlet initiation, first servlet will be initialized.
  • assign a change to the request, the first lower servlet will be initiated.
  • modify the headers and data to the request, in the way the request is packed, what to find.
  • modify the headings and data in the form, in which case the type is packed, which is accepted.
  • revert the servlet initiation after the transition to the servlet.

The servlet filter can be customized so that you can work with a single servlet or a group of servlets. The basis for forming filters is the javax.servlet.Filter interface, which implements three methods:

  • void init(FilterConfig config) throws ServletException;
  • void destroy();
  • void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;

The init() method is called, the first lower filter is repaired, and the new configuration filter object is updated. The doFilter method directly overrides the filter's work. In this way, the server calls init() once to run the filter in the robot, and then calls doFilter() a number of times, how many requests will be broken down without interruption until this filter. After the filter finishes its work, the destroy() method is called.

  • What is the need for hearing aids in servlets?

Listening to the context of that session - ce class, yakі can follow it, if the context of either the session was initialized, or if it was an hour, if the stench may be stupefied, and if the attributes were added and seen from the context of the session. Servlet 2.4 extends the listener query model to allow you to specify how queries are created and suppressed, and how attributes are added and removed from a servlet. Servlet 2.4 adds this class:

  • ServletRequestListener
  • ServletRequestEvent
  • ServletRequestAttributeListener
  • ServletRequestAttributeEvent

  • How to get the blame, win with another servlet from the addendum?

If the browser only knows more than HTML, then if the servlet container wiki program blazes and creates an HTML response. This is similar to what is used with pardon codes for kshtalt 404, 403 and so on. The Servlet API gives a hint to the master servlets for the processing of citations and pardons, which we can put at the descriptor of the slurring. The main task of such servlets is to get a pardon or blame and send an understanding of HTML to coristuvachev. For example, you can give strength to head side, as well as a description of some details about the pardon.

  • What is the descriptor of larynx?

The goroutine descriptor is the configuration file for the artifact that will be gorouted by the servlet container. At the specification Java Platform, Enterprise Edition descriptor describes whether a component, a module or a program (such as a web add-on or an enterprise program) can be opened.

This configuration file specifies the parameters of the layout for the module or the program with basic settings, the security parameters that describe specific options for the configuration. For the syntax of the file descriptor, the language is written XML.

  • How to implement the launch of a servlet by launching a program?

The servlet container should start the servlet on the first request of the client, otherwise it is necessary to start the servlet right at the start of the program (for example, as a bulk servlet, it will take a long time to start). For which it is necessary to select the load-on-startup element on the descriptor (or the loadOnStartup annotation), which would require the servlet to be engaged at startup.

The value can be int. If the value is negative, then the servlet will be occupied when the client is requested, and if it is 0 and further, then it will be occupied at the start of the program. The lower the number, the sooner the Cherz will have a servlet on hand.

  • What is a ServletConfig object?

The javax.servlet.ServletConfig interface is designed to pass configuration information to the servlet. The servlet skin can host a ServletConfig object, creating an instance of some sort of servlet container. To set the parameters in the configuration, the init parameters in web.xml (or WebInitParam annotations) are selected. To retrieve the ServletConfig object of that servlet, the getServletConfig() method is retrieved.

  • What is a ServletContext object?

The javax.servlet.ServletContext interface defines a number of methods, like cheating a servlet, to communicate with a servlet container, for example, change the MIME type of a file, dispatch a request, or write to a log file. The ServletContext object is unique and accessible to all web servers of the program. We can win the ServletContext object if we need to give access to one or more servlets to initialize parameters in the web program. For which victorious element at web.xml. The ServletContext object can be looked up by the getServletContext() helper method in the ServletConfig interface.

Servlet containers can supply context objects that are unique to a group of servlets. The skin of the group will be associated with its own set of host URL paths.

ServletContext extensions to the Servlet 3 specification and let the program add hearing and filtering to the program. Also, this interface has anonymous methods for example getMimeType(), getResourceAsStream() and so on.

  • Why does ServletContext and ServletConfig matter?

Below is the deed of authority:

  • ServletConfig is unique to a skin servlet, while ServletContext is unique to all programs.
  • ServletConfig is selected for the given parameters in the initialization of the servlet, and ServletContext for the given parameters in the initialization of the program for all servlets.
  • We don't have the ability to set attributes in the ServletConfig object, but we can set attributes in the ServletContext object to be available to other servlets.

  • ServletResponse interface.

The ServletResponse interface is the ultimate tool for enforcing data for the client. Use the method of this tool to use the same method.

  • ServletRequest interface.

The ServletRequest interface is a tool for retrieving parameters from an HTTP request. This interface may have methods that are identical to the name given to the ServletContext.

  • What is a Request Dispatcher?

The RequestDispatcher interface is designed to pass a request to another resource (either HTML, JSP, or another servlet with the same addendum). We can win the challenge to add another resource to the top. This interface is designed for internal communication between servlets in the same context. Two methods are implemented in the interface:

  • void forward(ServletRequest var1, ServletResponse var2) - forward the request from the servlet to another resource (servlet, JSP or HTML file) on the server.
  • void include(ServletRequest var1, ServletResponse var2) - includes the content of the resource (servlet, JSP or HTML side) in the view.

Access to the interface can be done with the help of ServletContext getRequestDispatcher(String s). The path is guilty of starting with / , which is to be interpreted in a way that the current root path is interpreted in the context.

  • How can you create a deadlock on a servlet?

Deadlock can be removed by implementing loops on the call-click method, for example, calling the doPost() method from the doGet() method and calling the doGet() method from the doPost() method.

  • How to take the address of the servlet on the server?

To retrieve the actual server path on the server, you can twist the following construction: getServletContext().getRealPath(request.getServletPath()).

  • How to extract information about the server from a servlet?

Information about the server can be retrieved from the ServletContext helper from the getServerInfo() helper method. Tobto. getServletContext().getServerInfo().

  • How to take the client's ip-address on the server?

Tweak request.getRemoteAddr() to retrieve the client's ip in the servlet.

  • What do you know about wrapper classes for servlets?

The Servlet HTTP API hopes to have two wrappers - HttpServletRequestWrapper and HttpServletResponseWrapper. They help retailers to sell their own sale of request and response types of the servlet. We can expand the class and redefine the unnecessary methods for the implementation of power types of objects of drinking and drinking. These classes do not win over standard servlet programming.

Servlet- the whole java-program, as it appears on the server side of the Web-program. Just as applets dynamically expand the functionality of a Web browser, servlets dynamically expand the functionality of a Web server.

Robot servlet"and it can be described as an approach: when you need to request a client, the Web server, with the help of a special configuration file, you can determine which servlet you need to select. -server (possibly in view of the HTML side)

WEB-server is essentially a song container, which is interesting servlet"and, vykonuє їх, і, having taken into account the result, overpowered the client.

Servlet in web application architecture

Through your tightness and gnuchkist, servlet You can play a significant role in the architecture of the system. They can improve the application process, recognized for the industrial level, work as a proxy server for the client and improve the functionality of the intermediate level, adding new protocols and other functions. Intermediate riven vikonu server functions dodatkіv so-called three-river system client-server and exchanges between "lightweight" client, such as Web-browser, that dzherelom danich.

Servlet as a proxy server

To support applets, servlets can override the functions of proxy servers. Might as well be important, but the Java security system only allows applets to connect to the server, no matter how stinky it is. This applet will need to be signed up with a database server that is deployed on another machine, servlet You can create an applet.

Timchasovo and fast servlet"and

Servlets can be started and run for skin client requests. Also, the stench can be started at the start of the Web server and down to the last tooth. Timchasovo servlet"and they are trying to help and promote a good way to save server resources for functions that are rarely victorious. stinks are guilty of acknowledging the request of the client yaknaishvidshe. servlet but fast abo Timchasov; This is the function of setting up the Web server.

Servlet life cycle, javax.servlet.Servlet

Servlets are built on the platform of the Web server as part of that process, as well as the Web server itself. The Web server replies for the initialization, recall, and deprecation of the servlet skin instance. Web server interacts with a servlet through a simple interface: javax.servlet.Servlet.

The javax.servlet.Servlet interface includes three main methods:

  • init()
  • service()
  • destroy()

and two additional methods:

  • getServletConfig()
  • getServletInfo()

Similarity between interfaces servlet"And Java applets are obvious. That's how it was designed! Java servlets are for Web servers, like applets for Web browsers. itself, running on a Web server.

Servlet initialization, init() method

When the servlet is first hit, the init() method is called. This allows the Viconate servlet to be a robot to install, for example, open files or install a connection to servers. As the server is installed on the server, it will be installed automatically when the server is started. Otherwise, the server activates the servlet while removing the first request from the client to serve, which is provided by the servlet.

It is guaranteed that the method init() end before any other steps to the servlet - such as, for example, a quick call to the method service(). To return respect, scho init() there will be more than one call; win will not be called until the servlet has not been retrieved, and then the server will retrieve the queries.

Method init() accepts one argument - send to the object ServletConfig what to pass arguments to initialize the servlet. Tsey object maє method getServletContext(), which rotates the object ServletContext, which is to retrieve information about the sharpening of the servlet.

Servlet core, service() method

Method service()є the heart of the servlet. Request a client type to generate up to one wicket method service(). This method reads and asks for the form of an alert for the help of its two arguments ServletRequest and ServletResponse:

In this manner, there are two ways to pass a client's identity to a servlet. The first one is through the strength of the value of the parameters of the power supply. Parameter values ​​can be inserted into the URL. Another way to pass the client's input to the servlet is via an InputStream (or a Reader).

Robot method service() day-to-day is simple - I create a client's request, transfers to you from the server. However, it is necessary to remember that you can use a small amount of parallel drinks, which are completed at the same time. What method service() It is necessary to ensure that access to resources is stream-protected, such as files, databases of data.

Servlet vivantage, destroy() method

Method destroy() calls for the call of all resources (for example, open files that database entry) before the servlet's vivantage. This method can be empty, as it is not necessary to complete any final operations. Before wiki method destroy() the server checks either the completion of all service operations, or the end of the song hour. Tse means that the method destroy() maybe buti vyklikaniya pіd hour vykonannya be-any trivial method service().

Be careful with the method destroy() in such a way as to close the necessary resources, while all wikis service() not end.

Servlet config, getServletConfig() method

Method getServletConfig() turn the request to the object that implements the interface ServletConfig. This object is given access to information about the servlet's configuration, that is. access to servlet initialization parameters and servlet context object ServletContext, which gives access to the servlet that is fine.

Servlet info, getServletInfo() method

Method getServletInfo() it is determined by the programmer who creates the servlet, for the rotation of the row, how to retrieve information about the servlet, for example: the author and version of the servlet.

ServletRequest interface

ServletRequest passes client HTTP parameter information to the servlet so that it. Secure data including the name of the parameter, value, attributes, and input flow. What information is passed to the method service().

offensive servlet butt show how to take the information from the parameter request method service():

BufferedReader reader; String param1; String param2; public void service(ServletRequest request, ServletResponse response) ( reader = request.getReader(); param1 = request.getParameter("First"); param2 = request.getParameter("Second"); )

Additional information about the request is available to the servlet through the methods, the main ones in the following table:

getAttribute() Rotate the value of the specified attribute to the request.
getContentLength() Rozmir zapitu, as seen.
getContentType() Change the type to MIME.
getInputStream() Rotate the InputStream to read double data from the body to the request.
GetParameterNames() Rotate the array of rows with the names of all parameters.
getParameterValues() Rotate the array value of the assigned parameter.
getProtocol() Convert the protocol to that version to get it right /..
getReader() Rotate BufferedReader to edit text on request.
getRealPath() Turn the real path for the designated virtual path.
getRemoteAddr() IP-addresses of the client, which was requested by him.
getRemoteHost() Іm'ya host of the client's machine, which nad_slav this request.
getScheme() Rotate the scheme that is included in the URL of this request (for example, https, http, ftp, etc.).
getServerName() Name of the host of the server, which one has accepted the request.
getServerPort() Turn the number to the port, which is victorious for the withdrawal of this request.

ServletResponse interface

interface ServletResponse- Tse іnstrument for nadsilannya given to the client. All methods of this tool serve by itself for the completion of this task:

Public java.lang.String getCharacterEncoding() public void setLocale(java.util.Locale loc) java.util.Locale getLocale()

The first way is to change the MIME encoding type (for example - UTF8), so that you can see the information. The other two methods also work from charset. The stench speaks of language, which is written in documents (for example, Russian).

Public ServletOutputStream getOutputStream() throws java.io.IOException

The getOutputStream method turns the output stream for the servlet. Tsey potіk vykoristovuєtsya, for example, vyvedennya binary files. Text data can be retrieved with the help of java.io.Writer:

Public java.io.PrintWriter getWriter() throws java.io.IOException

The getWriter() method automatically converts rows to the charset specified by the getCharacterEncoding() and getLocale() methods.

public void setContentLength(int len)

The setContentLength method sets the value of the HTTP header field "Content-Length"

public void setContentType(String type)

The setContentType method is tweaked to force a MIME type in place of a document. HTTP header field "Content-Type".

The flow of seeing data is buffered. This means that a portion of the data will be seen by the client after the buffer is filled.

public void setBufferSize(int size) public int getBufferSize() public void flushBuffer() throws java.io.IOException public void resetBuffer()

Hovering over 4 methods allows you, obviously, to install the edit buffer size, remove the edit buffer, initialize the buffer edit to the client, not checking the data buffer, and also clear the data buffer.

Public boolean isCommitted()

Using the isCommitted method, you can remove the ensign, which has already been sent to the client. The flag will be positive, as the HTTP header has already been sent.

public void reset()

If the HTTP header has not been added yet, the reset method "resets" the HTTP header to the value of "locked".

JFreeChart Charts in Servlets

The JFreeChart graphics library can be used in servlets to create charts and display them on the side of the site in order to view the image. Details of the description of the JFreeChart application for servlet views.

Servlet from the Chart.js graphics library

JNI in servlet

For a number of options, you may need the JNI version of the WEB addendum. An example of using JNI for servlet views.

JMS servlet notification

A servlet can have quotations for exchange JMS povіdomlennya mіzh programs. A Servlet Vocational Tool for Powering and Reading JMS Containerized JBoss Views.

One of the most important features of Java is rich nature. Obviously, a creation of traditional desktop and navit mobile supplements- it's wonderful. Also, do you want to go off the beaten track and enter the territory of developing Java web add-ons? There is a good news for you: in the package with my idea there is an advanced Servlet API, which allows you to create custom web programs without special turbos.

Creating Java programs for the help of Servlets

Father, we have already done configuration files programs. However, there is literally nothing to break at the production line. If we want clients to be able to register for an additional HTML form, the next thing we need to do is to create JSP files, as if to visualize the guessed form of that client data after successful completion of the registration. Tsim mi at once and let's get busy.

Pratsiyuemo over zovnіshnіm vglyad

The strange looking program is designated by two JSP files - in the context of MVC they are called manifestations. First notice for the submission of the registration form possible pardons, viklikanі after reverification of the introduction of data. The other will be the primary side of the registration, which will show the data entered by the client, after the successful completion of the registration process.

Axis first JSP file:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> Registration

Registration

$ (violation).

© 2022 androidas.ru - All about Android