💂 personal home page :Java program fish 🤟 the entire Java system of interview questions I will share, we can continue to pay attention to 💬 if the article is helpful to you, welcome to follow, like, favorites (one button three links) and subscribe to the column oh. 💅 have any question welcome private letter, see will reply in time!
1. What is the difference between servlets and CGI?
A: In general, servlets can perform the same functions as CGI.
CGI application development is difficult because it requires programmers to have knowledge of dealing with parameter passing, which is not a universal skill. CGI is not portable, and CGI applications written for a particular platform can only run in that environment. Each CGI application exists in a process that is activated by a client request and is unloaded after the request is serviced. This pattern causes high memory, CPU overhead, and cannot serve more than one client in the same process.
Servlets offer all the benefits of Java applications: portability, robustness, and ease of development. Using Servlet Tag technology, servlets can generate dynamic content embedded in static HTML pages.
The main advantage servlets have over CGI is that a Servlet is activated by the first request a client sends, and then it continues to run in the background, waiting for future requests. Each request generates a new thread instead of a full process. Multiple customers can be served simultaneously in the same process. Generally, Servlet processes are simply uninstalled when the Web Server is uninstalled.
Java Servlets compare with Common Gateway Interface (CGI)
- Compared to traditional CGI and many other CGI-like technologies, Java servlets are more efficient, easier to use, more powerful, more portable, and less costly. In the future, servlets may completely replace CGI.
- In traditional CGI, a new process is started for each request, and if the CGI program itself is short in execution time, the cost of starting the process is likely to exceed the actual execution time. In servlets, each request is handled by a lightweight Java thread (rather than a heavyweight operating system process).
- In traditional CGI, if there are N concurrent requests for the same CGI program, the code for that CGI program is loaded in memory N times. With servlets, N threads process requests and only one servlet-class code is required. Servlets also have more options than CGI for performance optimization.
* convenient
Servlets provide a number of utility routines, such as automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking session state, and so on.
* Powerful function
In servlets, many tasks can be easily done that would be difficult to do with traditional CGI programs. For example, servlets can interact directly with Web servers, whereas regular CGI programs cannot. Servlets also have the ability to share data between programs, making features like database connection pooling easy to implement.
* Good portability
Servlets are written in Java, and the Servlet API has a complete standard. Therefore, servlets written for IPlanet Enterprise Server can be ported to Apache, Microsoft IIS, or WebStar without any substantial changes. Almost all major servers support servlets either directly or through plug-ins.
What are the methods in the Servlet interface?
(1) Init method:
init(ServletConfig config)
During the lifetime of the Servlet, the init() method is executed only once, when the server loads the Servlet.
The server can be configured to load servlets when the server is started or when a client accesses them for the first time. No matter how many clients access the Servlet, init() is never repeated.
The default init() method is generally fine, but it can also be overridden with a custom init() method, typically managing server-side resources. For example, you might write a custom init() to load GIF images only once, improving the performance of servlets that return GIF images and contain multiple client requests. Another example is initializing a database connection. The default init() method sets the Servlet’s initialization parameters and starts the configuration with its ServletConfig object parameters, so all servlets overriding the init() method should call super.init() to ensure that these tasks are still performed. Before calling the service() method, make sure that the init() method is complete.
(2) Service method:
service(ServletRequest req, ServletResponse res)
The service() method is at the heart of servlets. Whenever a client requests an HttpServlet object, the object’s service() method is called and a “request” object and a “response” object are passed to the method as parameters. The service() method already exists in the HttpServlet. The default service function is to invoke the do function corresponding to the HTTP request method. For example, if the HTTP request method is GET, doGet() is called by default.
Servlets should override do functionality for HTTP methods supported by servlets. Because the httpservlet.service () method checks whether the request method has called the appropriate handler, it is not necessary to override the service() method, just the corresponding DO method.
Post vs. GET methods: The doPost() method is called when a client makes an HTTP POST request from an HTML form. The parameters associated with the POST request are sent from the browser to the server as a separate HTTP request. The doPost() method should be used when you need to modify data on the server side. The doGet() method is called when a client makes an HTTP GET request through an HTML form or requests a URL directly. The parameters associated with the GET request are added to the URL and sent with the request. The doGet() method should be used when server-side data is not being modified.
The post method is generally used for development and the size is generally limited to 64KB.
(3) Destroy
destroy()
Similar to the init method, the destroy() method is executed only once, when the server stops and the Servlet is unloaded. Typically, servlets are shut down as part of the server process. The default destroy() method is generally acceptable, but you can override it, typically to manage server-side resources. For example, if the Servlet accumulates statistics at run time, you can write a destroy() method that saves the statistics in a file when the Servlet is not loaded. Another example is to close a database connection.
When the server unloads the Servlet, the destroy() method is called either after all service() method calls are complete or after a specified interval. A Servlet may spawn additional threads while running the service() method, so make sure that these threads are terminated or complete when the destroy() method is called.
(4) getServletInfo:
getServletInfo()
The GetServletInfo() method is an optional method that provides information about the servlet, such as author, version, and copyright. When the server calls Sevlet’s Service(), doGet(), and doPost() methods, all require “request” and “response” objects as parameters. The request object provides information about the request, and the response object provides a communication way to return the response information to the browser.
GetServletConfig:
getServletConfig()
The getServletConfig() method returns a ServletConfig object that is used to return initialization parameters and a ServletContext. The ServletContext interface provides environment information about servlets.
3. What is the difference between forward and redirect?
There are two ways to realize page hopping: request forwarding and redirection;
Request forwarding: The client first sends a request to the server, which finds the matching servlet and assigns it to execute it. When the servlet is finished executing, it calls the getRequestDispacther() method. The request is forwarded to the specified student_list.jsp, and the whole process is done on the server side, in the same request, so the servlet and the JSP share the same request, and everything you put in the servlet, Student_list gets the result getAttribute(). After getAttribute() gets it, it returns the result to the client. The whole process is a request, a response.
The redirection: The client sends a request to the server, the server matches the servlet, and the servlet calls sendRedirect(), which immediately returns the response to the client. The response line tells the client that you must send another request to student_list.jsp. The client receives the request and immediately issues a new request for student_list.jsp. The two requests are independent of each other, and nothing setAttribute() in the previous request can be obtained in the later request. As you can see, inside sendRedirect() there are two requests and two responses. (The server sends a 302 status code and a Location header to the browser, which will then request again based on the redirected address.)
Forward requests: request. GetRequestDispatcher (“/test. The JSP “). The forword (request, response);
Redirect: Response.sendreDirect (“/test.jsp”);
The difference between:
- Number of requests: Redirection means that the browser sends a request to the server and then sends a request to a new address after receiving the response. Forwarding means that the server jumps to a new address to complete the response after receiving the request. Redirect the request at least twice and forward the request once;
- Different address bars: The redirection address bar changes, but the forwarding address bar does not.
- Whether to share data: Redirects two requests but does not share data, forwards one request to share data. (If information sharing is used at the request level, an error occurs when redirects is used.)
- Redirect restriction: Redirection can jump to any URL, forwarding can only jump to the local site resources;
- The occurrence behavior is different: redirection is the client behavior, forwarding is the server behavior;
Use:
- You can take advantage of the nature of the Request domain object by storing write data into it from the source component.
- Allows users to access target resources stored in the WEB-INF directory.
- Redirection is slower than forward because the browser has to make a new request, so it is recommended to use forward when neither forward nor redirect matters;
- Because forwarding can only access the current WEB application, access between different WEB applications, especially to resources on another WEB site, is the only way to use redirection.
4. What built-in objects does JSP have? What are the effects?
A: JSP has nine built-in objects:
- Request: a client request that contains parameters from a GET/POST request
- Response: A response from the web page back to the client
- Out: The output used to transmit the response
- Page: JSP page itself
- Config: architecture component of the servlet
- Session: Related to requests
- Application: What the servlet is executing
- PageContext: The properties of the page are managed here
- Exception: An uncaught exception to an error page
Request represents an HttpServletRequest object. It contains information about browser requests and provides several useful methods for retrieving cookie, header, and session data.
Response represents an HttpServletResponse object and provides several methods for setting the response (such as cookies, headers, etc.) to be sent back to the browser
The Out object is an instance of javax.jsp.jspWriter and provides several methods that you can use to send output back to the browser.
PageContext said a javax.mail servlet. JSP. PageContext object. It is an API for easy access to a wide range of namespaces, servlet-related objects, and is wrapped in generic
Methods of servlet-related functionality.
The session said a request javax.mail. Servlet. HTTP. The HttpSession object. A Session can store state information about a user
Applicaton said a javax.mail. Servle. ServletContext object. This helps you find information about the servlet engine and the servlet environment
Config said a javax.mail. Servlet. ServletConfig object. This object is used to access the initialization parameters of the servlet instance.
Page represents a servlet instance generated from the page
JSP has the following six basic actions:
JSP :include: Introduces a file when the page is requested.
- JSP :useBean: Finds or instantiates a JavaBean.
- JSP :setProperty: Sets the properties of the JavaBean.
- JSP :getProperty: Outputs the properties of a JavaBean.
- JSP :forward: Forwards the request to a new page.
- JSP: Plugin: Generates OBJECT or EMBED tags for Java plug-ins, depending on the browser type
5. What is the difference between GET and POST requests?
Summary HTTP packet layer: GET stores the request information in the URL and POST in the packet. Database level: GET complies with idempotency and security, but POST does not. Other layers: GET can be cached and stored, POST can’t
Get is used to obtain data, and POST is used to submit data. The GET parameter has a length limit (limited by the URL length, the specific value depends on the browser and server, the maximum length is 2048 bytes), while POST is unlimited. The data of the GET request is appended to the URL, starting with “? “Split url and transfer data, multiple parameters are concatenated with ampersand, whereas A POST request puts the requested data in the HTTP request body. Get is in plaintext, post is in the body of the request, but the developer can see it through the packet capture tool, and it is also in plaintext. Get requests are saved in the browser history and possibly in the Logs of the Web server
Idempotent idempotent means, in plain English, that executing the same request multiple times is exactly the same as executing it only once. If the connection is lost before the request responds, then the request can be safely reissued if the request is idempotent. Therefore, it can be concluded that when GET request is idempotent, the request can be repeated, while when POST request is not idempotent, repeated request may have unpredictable consequences.
6. What are the common Web servers?
A: The most widely used free HTTP server on Unix and Linux platforms is the Apache server, while Windows platforms typically use IIS as a Web server. Factors to consider when choosing a Web server include performance, security, logging and statistics, virtual hosting, proxy servers, buffering services, and integrated applications. Here is a brief introduction to common servers:
- IIS: Microsoft Web server product, full name is Internet Information Services. IIS is a Web server that allows information to be published on public intranets or the Internet. IIS is one of the most popular Web server products, many famous websites are built on THE IIS platform. IIS provides a graphical management tool, called the Internet Services Manager, that can be used to monitor configuration and control Internet services. IIS is a Web service component, including a Web server, FTP server, NNTP server and SMTP server, respectively for Web browsing, file transfer, news service and mail delivery, it makes it easy to publish information on the network (including the Internet and local area network). It provides ISAPI(Intranet Server API) as a programming interface to extend the functions of Web Server. It also provides an Internet database connector to query and update the database.
- Kangle: Kangle Web server is a cross-platform, powerful, secure, stable, easy to operate high-performance Web server and reverse proxy server software. In addition, Kangle is also a Web server developed specifically for Web hosting. Virtual host independent process, independent identity running. Users are isolated from each other. If one user fails, other users are not affected. Support PHP, ASP, ASP.NET, Java, Ruby and other dynamic development languages.
- WebSphere: WebSphere Application Server is a full-featured, open Web Application Server that is a core part of IBM’s e-business initiative. It is a Java-based Application environment for building, deploying, and managing Internet and Intranet Web applications. Adapt to the needs of a variety of Web application servers.
- WebLogic: WebLogic Server is a multi-functional, standards-based Web application Server, which provides a solid foundation for enterprises to build enterprise applications. Weblogic provides support for application development, mission-critical deployment, integration of various systems and databases, and cross-Internet collaboration. Due to its comprehensive capabilities, open standards compliance, multi-tier architecture, and support for component-based development, many enterprise applications have chosen it as their development and deployment environment. WebLogic Server has been in a leading position in making application Server the foundation of enterprise application architecture, providing a solid foundation for building integrated enterprise applications.
- Apache: Apache is still the most used Web server in the world, with a market share of more than 60% for a long time (currently around 40%). Many famous websites in the world are the product of Apache. Its success mainly lies in its open source code, a strong development team, support for cross-platform applications (can run on almost all Unix, Windows, Linux system platform) and its portability.
- Tomcat: Tomcat is an open source container that runs servlets and JSPS. Tomcat implements the Servlet and JSP specifications. In addition, Tomcat implements the Apache-Jakarta specification and is better than most commercial application servers, so Tomcat is now the choice of many Web servers.
- Nginx: pronounced “Engine X”, is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP proxy server. Nginx was developed by Igor Sysoev for the second most visited Rambler site in Russia, with the first public release of 0.1.0 on October 4, 2004. It distributes source code under a BSD-like license and is known for its stability, rich feature set, sample configuration files, and low consumption of system resources. In the second half of 2014, Nginx’s market share reached 14%.
7. What is the relationship between JSP and Servlet?
A: A Servlet is a special Java program that runs in the server’S JVM and relies on the server’s support to provide display content to the browser. JSP is essentially a simple form of Servlet. JSP will be processed by the server into a Java program similar to Servlet, which can simplify the generation of page content. The main difference between servlets and JSPS is that the application logic of servlets is in Java files and completely separated from HTML in the presentation layer. In the case of JSP, Java and HTML can be combined into a file with a.jsp extension. Some people say that servlets are writing HTML in Java, and JSP is writing Java code in HTML. Of course, this statement is one-sided and inaccurate. JSPS focus on views, while servlets focus more on control logic. In the MVC architecture pattern, JSPS fit as views and servlets fit as controllers.
Explain the four scopes in JSP
A: First of all, “scope” is the “scope of information sharing,” which means the extent to which a piece of information can be effective. The scope of the four JSP built-in objects are: Application, Session, Request, and Page. The JSP built-in object scope table is as follows:
The name of the |
scope |
application |
Valid in all applications |
session |
Valid in the current session |
request |
Valid in the current request |
page |
Valid on the current page |
The most basic unit of Web interaction is HTTP requests. The process of each user entering and leaving a website is called an HTTP session. During the running of a server, multiple users access the website, that is, multiple HTTP sessions. The scope is explained below.
(1) Application scope
If you place a variable in application, it is scoped to application, and its scope is the entire application. The entire application is from the start of the application to the end of the application. We didn’t say “from server up to server down” because it’s possible to deploy multiple applications on a single server, and of course if you shut down the server, you shut down all the applications on it. Variables in the application scope, which have the longest lifetime, are always available unless manually deleted.
Information passing on the application scope is implemented through ServletContext, which provides the following main methods:
Object getAttribute (String name) // Get information from application; Void setAttribute (String name, Object Value) // Sets information to application scope.Copy the code
(2) Session scope
The session scope is easy to understand. It is a manifestation of the session scope that the same browser accesses the server multiple times and transmits information between these visits. If you put a variable in session, then it is scoped to session and its valid scope is the current session. The current session is the process between the time the user opens the browser and the time the user closes the browser. This process may contain multiple request responses. In other words, as long as the user does not open the browser, the server has a way to know that the request was initiated by a person. The whole process is called a session, and variables placed in the session can be used in all requests for the current session. Session is implemented through the HttpSession interface, which provides the following main methods:
Object HttpSession.getAttribute (String name) // Retrieves information from the session. Void httpsession. setAttribute (String name, Object Value) // Saves information to the session. The HttpSession it. GetSessio () / / get the current request in the session object.Copy the code
The start time of a session is relatively easy to determine, as it is considered the start of a session when the browser makes the first HTTP request. However, the end time is difficult to determine, because the browser does not notify the server when closing, so you can only determine this method: If the client does not respond within a certain period of time, the session is considered to be over. The default value for Tomcat is 120 minutes, but this value can also be set using the setMaxInactiveInterval() method of HttpSession:
void setMaxInactiveInterval(int interval)
Copy the code
Void invalidate(); void invalidate(); void invalidate(); void invalidate();
(3) Request scope
The processing of an HTTP request may require the cooperation of multiple servlets, and these servlets may communicate information in a way that is invalid after the request ends. Variables in the request can span two pages before and after the forward. But as soon as the page is refreshed, they recalculate. If you put a variable in request, it is request scoped, and its valid scope is the current request period. The so-called request cycle refers to the entire process from the HTTP request initiation to the end of the server processing and return of the response. You can use this variable in multiple JSP pages using forward in the process.
Information sharing between servlets is achieved through two methods of the HttpServletRequest interface:
Void setAttribute (String name, Object Value) // Saves the Object value as name to the Request scope. Object getAttribute (String name) // Retrieves information from the request scope with the specified name.Copy the code
The first argument to the doGet() and doPost() methods in JSP is the HttpServletRequest object, which uses the setAttribute() method to pass information. So once the information is set up, how do you pass it to other servlets? This is done using the Forward () method of the RequestDispatcher interface, which forwards requests to other servlets.
RequestDispatcher ServletContext. GetRequestDispatcher (String path) / / the Dispatcher to forwarding, the path forward for the purpose of the Servlet.
Void RequestDispatcher. Forward (ServletRequest request, ServletResponse response) / / to forward the request and response
Therefore, you only need to set the corresponding attribute through the setAttribute() method in the current Servlet, then use the forward() method to jump, and finally use the getAttribute() method in the jump to the Servlet to achieve information transfer.
Two points to note:
- Forwarding is not a redirect; forwarding is done inside the Web application.
- Forwarding is transparent to the browser, meaning that no matter how it is forwarded on the server, the browser address bar still displays the address of the original Servlet.
(4) Page scope
The scope of the Page object is limited to the current page requested by the user, and references to the page object will be released after the response is returned to the client or after the request has been forwarded elsewhere. Variables in the page disappear as soon as the page jumps. Putting a variable in pageContext indicates that it is scoped to Page, and its valid scope is only in the current JSP page. You can use this variable from the time you put it in pageContext to the end of your JSP page.
A request and a page are both short-lived. The difference between them is that a request can contain multiple pages (include, forward, and filter).
In order to make it easier for you to understand the scope of application, Session, Request, page 4 objects, we give two programs to explain in detail.
[Procedure 1] page01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<! DOCTYPEhtml PUBLIC "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="pagevar" scope="page" class="java.lang.StringBuffer"/>
<jsp:useBean id="requestvar" scope="request" class="java.lang.StringBuffer"/>
<jsp:useBean id="sessionvar" scope="session" class="java.lang.StringBuffer"/>
<jsp:useBean id="applicationvar" scope="application" class="java.lang.StringBuffer"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP built-in object scope</title>
</head>
<body><% pagevar.append("page01"); requestvar.append("page01"); sessionvar.append("page01"); applicationvar.append("page01"); % ><jsp:forward page="page02.jsp"/>
</body>
</html>
Copy the code
[procedure 2] page02.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<! DOCTYPEhtml PUBLIC "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="pagevar" scope="page" class="java.lang.StringBuffer"/>
<jsp:useBean id="requestvar" scope="request" class="java.lang.StringBuffer"/>
<jsp:useBean id="sessionvar" scope="session" class="java.lang.StringBuffer"/>
<jsp:useBean id="applicationvar" scope="application" class="java.lang.StringBuffer"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP built-in object scope</title>
</head>
<body>
<%
pagevar.append("page02");
requestvar.append("page02");
sessionvar.append("page02");
applicationvar.append("page02");
%>
page = <%=pagevar.toString()%><br/>
request = <%=requestvar.toString()%><br/>
session = <%=sessionvar.toString()%><br/>
application = <%=applicationvar.toString()%><br/>
</body>
</html>
Copy the code
Test steps and result analysis:
The result of running program 1 directly is :(figure 1)
Page02 = page02; page2 = page02; page2 = page02; page2 = page02; page2 = page02; page2 = page02; The scope of request is valid in the current request, so its value is the sum of program 1 and jump to program 2; The scope of session is the current session, so its value is also the sum of program 1 and jump to program 2. Application is valid for all applications, that is, as long as they are in application, they must be superimposed, that is, the values in program 1 and the values in program 2 are superimposed;
Without closing the browser where program 1 is running, run program 2 directly, resulting in :(figure 2)
Comparing the results in Figure 1, we see that the page scope has not changed, and its value is just the value in program 2; Request scope only applies to the current request, so the value of program 2 is subject to change to page02; The scope of session is the current session, because the browser running program 1 is still in the same session, so superimpose a page02 on the basis of the previous; And application is valid for all applications, that is, as long as the application, it should be superimposed, that is, superimpose a page02 of program 2 on the basis of the previous;
Close the browser that ran programs 1 and 2 in the previous two steps, but do not close the server, and rerun program 2. The result is as follows:
The page scope remains the same, and its value is just the value of the page in which the program 2 is located. Request scope only applies to the current request, so the value of program 2 is subject to change to page02; The scope of session is the current session, because the browser running the previous two steps is closed, indicating that the previous session is over, so its value is restored to the value of page02 in the current program 2. Application is valid for all applications, that is, as long as the application, i.e. the server has not been restarted and emptied, it should be superimposed, that is, on the basis of the previous superimposed a page02 of program 2;
9, how to implement JSP or Servlet single thread mode?
A: For JSP pages, you can set them using the Page directive.
The < % @ page isThreadSafe = "false" % >Copy the code
The default is true and is multithreaded
For servlets, a custom servlet implements the SingleThreadModel interface
** Note: ** Setting JSPS or servlets to work in single-threaded mode would result in the creation of one Servlet instance per request, a practice that would cause serious performance problems (memory stress on the server and frequent garbage collection), so this is not usually done.
10. What are the techniques for implementing session tracing?
Session tracing is a flexible, lightweight mechanism that enables state programming on the Web. HTTP is a stateless protocol. Whenever a user makes a request, the server will respond. The connection between the client and the server is discrete and discontinuous. When users switch between multiple pages on the same site, there is no way to determine if it is the same customer, and session tracking technology can solve this problem. When a customer switches between pages, the server saves information about that user. There are four ways to implement Session tracking technology: URL rewriting, hidden form fields, cookies, and sessions.
1) Hidden form fields: ideal for session applications that require a lot of data storage. 2) URL rewriting: THE URL can be appended with parameters, which are name/value pairs, and sent with the server’s request. 3) Cookie: A Cookie is a small, named data element. The server uses the set-cookie header to send it to the client as part of the HTTP response, and the client is asked to save the Cookie value and return it to the server using a Cookie header on subsequent requests to the same server. One advantage of cookies over other technologies is that they can retain their values after the browser session ends, even after the client computer is restarted. 4) Session: Use the setAttribute(String STR,Object obj) method to bind objects to a Session
Implement URL rewriting
URL rewriting is used when the client browser does not support cookies (introduced in the next chapter). When the client browser requests the server, the URL address is followed by a parameter similar to “SESSIONID=***”. The server obtains the session value by obtaining the SESSIONID keyword.
The first time a program accesses the server, the server cannot confirm whether the client browser supports cookies. Therefore, when the server makes the first request, the server defaults to URL rewriting, that is, passing the SESSIONID to the URL address.
The core code: String SessionId = request. GetRequestedSessionId ();
When the client sends a request, the server automatically checks whether Cookie is enabled on the client based on the information submitted to the client browser. If Cookie is enabled, the URL rewriting will not be performed. If not, continue with URL rewriting.
Url rewriting can be done through the encodeURL(String URL) method of the Response object.
public String encodeURL(String url); Encode the URL that contains the SessionID. If no encoding is required, the URL is returned directly. The Servlet engine must provide URL encoding because in some cases we will have to rewrite the URL. For example, the response contains a valid Session in the request, but this Session cannot be maintained by non-URL means (such as cookies). So all urls provided to servlets should run through this method to ensure that session tracing works in all browsers.
Hidden fields and URL rewriting have a common advantage: they work even when cookies are disabled or not supported at all. Cons: All pages must be the result of a form submission, and there is a lot of tedious processing involved.
11. What are the functions and uses of filters?
A: For web applications, a filter is a web component that resides on the server side and intercepts the request and response information between the client and the server, and processes the information. When the Web container receives a request for a resource, it determines whether there is a filter associated with the resource, and if so, the container passes the request to the filter for processing. In the filter, you can change the content of the request or reset the request header before sending the request to the target resource. When the target resource responds to the request, the container also forwards the response to the filter, where you can transform the content of the response before sending it to the client.
Common filter USES are: user requests for unified authentication, access to the user request for review and record, for users to send data to filter or replace, transform, image formats and compression to reduce the content of the response of transmission quantity, to encrypt the request or response, trigger access to resources, such as XSLT for XML output applications.
The difference between filters and interceptors:
- Interceptors are based on Java’s reflection mechanism, while filters are based on function callbacks;
- Interceptors do not rely on the servlet container, while filters do;
- Interceptors only work on action requests, filters work on almost all requests;
- Interceptors can access the action context, objects in the value stack, but filters cannot.
- Interceptors can be called multiple times during the life of an action, while filters can only be called once when the container is initialized.
- The interceptor can fetch individual beans from the IOC container, but the filter can’t. Inject a service into the interceptor to invoke business logic.
- Interceptors need to be configured in the Spring configuration file, and filters only need to be configured in web.xml.
12. What are the functions and uses of the listener?
A listener is a common Java program that implements a specific interface. This program is specifically used to listen for method calls or property changes on another Java object. When the listener has the above event, a listener method will be executed immediately.
Listening to the principle of
- Event source exists
- Providing listeners
- Register listeners for event sources
- Manipulate the event source, generate the event object, pass the event object to the listener, and execute the corresponding listener listener method
For example, Swing development first makes a Frame window, which is itself a display space, and provides a listener for the window to listen for method calls or property changes: * When a window is closed, the windowListener’s WindowClosing () is called, passing the windowEvent argument to indicate that the window closes the event object. * The event object manipulates the event source to obtain the state of the event source
Custom listeners
The above can be explained by the following figure:
Make a connection between the event source and the listener through person.addPersonListener(new PersonListener(){}).
Event source (create event object in event source method) :
/** * event source object, being listened on ** /
public class Person{
private String name;
private int weight;
private PersonListener listener;
// Register the listener
public void addPersonListener(Personlistener listener){
this.listener = listener;
}
/ / how to eat
public void eat(a){
// Weight gain
weight+=5;
// Call the listener method in the method
if(listener ! =null) {// The listener exists
----- You can obtain the event source from the event object
PersonEvent event = new PersonEvent(this); listener.personeating(event); }}public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight(a) {
return weight;
}
public void setWeight(int weight) {
this.weight = weight; }}Copy the code
Listener (parameter is event object)
/** * listener interface, which provides the corresponding method ** / for listening
public interface PersonListener{
public void personeating(PersonEvent euent);// Listen on events
}
Copy the code
Event objects (from which event sources can be obtained)
/** * event object, which is generated when the action of the event source changes and is passed to the listener specified method ** /
public class PersonEvent{
public Object source;/ / the event source
public Object getSource(a){
return source;
}
public void setSource(Object source){
this.source = source;
}
When an event object is constructed, the event source is received
public PersonEvebt(Person person){
this.source = person; }}Copy the code
The test method
public class PersonTest(a){
public static void main(a){
// Step 1: Create an event source
Person person = new Person();
person.setName("Megustas");
person.setWeight(100);
// Step 2 create listener, register and write together
person.addPersonListener(new PersonListener(){
@Override
public void personeating(PersonEvent event) {
System.out.println("I've got it. People are eating!");
// Can be used in the listener method to obtain the state of the event sourcePerson person = (Person) event.getSource(); System.out.println(person.getName()); System.out.println(person.getWeight()); }});// Step 3 Operate the event source
person.eat();// As a result, the listener method is called}}Copy the code
The anonymous inner class is used to create an anonymous class object that implements the interface, which means to create an object that inherits from the anonymous class of PersonListener. References returned by a new expression are automatically cast upward to a reference to PersonListener
The Servlet listener
(No configuration is required, but listeners still need to be registered.) There are several types of listeners defined in the Servlet specification that listen for three domain objects: ServletContext, HttpSession, and ServletRequest.
Servlet listeners fall into three broad categories
- Data domain object creation and destruction listeners
- Data domain object and property change listener
- An event listener bound to the state of an object in the HttpSession domain
(1) Data domain object creation and destruction listener – listen for three and object (three listeners)
(1) ServletContextListener: Initialized(ServletContextEvent sCE) to create contextDestroyed(ServletContextEvent sce) The ServletContext object represents a globally unique object. Each Web project generates a ServletContext that the server starts creation and the server closes destruction
Write listeners step 1: Write classes to implement specific listener interfaces Step 2: Register listeners, not through the event source, but in web.xml configuration (listeners, unlike servlets and filters, do not require URL configuration, listener execution is not accessed by the user, listeners are automatically invoked by the event source)
<listener>
<listener-class>
cn.megustas.listener.MyServletContextListener
</listener-class>
</listener>
Copy the code
When servletContext domain objects are created and destroyed:
- Create: The server starts to create a ServletContext for each Web application
- Destruction: The servletContext representing each Web application is closed before the server is shut down
ServletContextListener mainstream use: First: when the server is started, some objects are initialized and stored in the scope of the ServletContext data (because the event source object is available in the listener) – global data
- For example, create a database connection pool
For example, the Spring framework is initialized via ServletContextListener (because the listener code is executed when the server starts).
- The Spring framework (with the server to start loading configuration file) org. Springframework. Web. Context. The ContextLoaderListener
The third: to achieve task scheduling, start the timing program (Timer, TimerTask) so that a program, timing execution
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("The listening ServletContext object has been destroyed...");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Listening for the ServletContext object to create...");
// Get the event source (essentially a call to getSource ())
ServletContext servletContext = sce.getServletContext();//servletContext is a global object
// Save data to the ServletContext
// Start timer
final Timer timer = new Timer();
// Start a scheduled task
timer.schedule(new TimerTask() {
@Override
// This is a thread
public void run(a) {
System.out.println("The timer went off..."); }},0.3000); // Start immediately and repeat every 3 seconds
// Start the timer at the specified time
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date first = dateFormat.parse("The 2016-12-28 10:42:00");
timer.schedule(new TimerTask() {
int i;
@Override
public void run(a) {
i++;
System.out.println("Start the program at 10:40 and repeat every three seconds.");
// Execute 10 times
if (i == 10) {
timer.cancel();// Cancel the timer task
}
}
}, first, 3000);
} catch(ParseException e) { e.printStackTrace(); }}}Copy the code
For example, at twelve o ‘clock in the evening, China Mobile sends birthday wishes to people who have birthdays. For account synchronization, China Mobile will start a program to synchronize accounts at less used time of the server, such as early morning
Java.util. Timer A threading facility used to schedule tasks to be executed later in a background thread. Tasks can be scheduled to be executed once or repeated periodically. Schedule * schedule(TimerTask task, Date firstTime, long period) is used to start the Timer at a specified time. Schedule (TimerTask task, long delay, long period) Specifies the number of milliseconds after the current delay to start the timer stop the timer, timer.cancel cancel the task
(2) HttpSession data object creation and destruction listener — HttpSessionListener
SessionCreated (HttpSessionEvent SE) monitors the creation of a Session object. SessionDestroyed (HttpSessionEvent SE) monitors the destruction of a Session object
Request.getsession () when the Session is destroyed: Disable the server, Session expires, session.invalidate * The Session expiration time is specified in the web. XML (Tomcat configuration file), and the default time is 30 minutes
Configuration:
<listener>
<listener-class>
cn.megustas.listener.MyHttpSessionListener
</listener-class>
</listener>
Copy the code
The HttpSession listeners
public class MyHttpSessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent se){
// Get the session ID, via the event object
System.out.println("Session object created");
HttpSession session = request.getSession();
System.out.println("id"+ session.getId()); }}Copy the code
The following JSP pages are available:
1.jsp
</h1> <a href="/megustas/demo1/2.jsp"> Destroy Session</a> </body>Copy the code
2.jsp
<% session.invalidate(); % >Copy the code
** Because if you look at the source of the JSP, the JSP will be preprocessed into.java code (in the Work folder of Tomcat), we open this.
try (
response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null.true.8192.true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSessirn(); out = pageContext.getOut() ; _jspx_out = out;Copy the code
The implementation of getSession is actually request.getSession()
(3) HttpServletRequest object creation and destruction listener — ServletRequestListener
RequestInitialized (ServletRequestEvent sRE) — Create requestDestroyed(ServletRequestEvent sRE) to monitor the Request object destruction
Request creation: Created when the Request is initiated. Request destruction: Destroyed when the response ends
For example, create and destroy a screen every time you refresh it
Note (the number of requests is determined by the number of requests) : Use forward — request to create and destroy several times — one use sendRedirect — request to create and destroy two times (two requests)
(2) the ServletContext/save the data in the HttpSession/ServletRequest create, modify, remove the listener
ServletContextAttributeListener listening ServletContext change HttpSessionAttributeListener to monitor an HttpSession attribute changes ServletRequestAttributeListener listening ServletRequest attribute changes
AttributeAdded Listens for attributes to be added — setAttribute(name,value) is added the first time a data scope object does not have this attribute; — Remove an existing attribute removeAttribute(name) from a data scope object; Perform attributeReplaced to listen for attribute substitution — add setAttribute(name,value) to a data range with the same name when an attribute already exists; Trigger replacement method
For example, here we use HttpSessionAttributeListener example (ServletContextListener and ServletRequestListener similarly) :
The JSP page
<% // attributeAdded session.setAttribute("name"," attributeAdded session.setAttribute "); Session.setattribute ("name", session.setAttribute("name", session.setAttribute); // Triggers attributeReplaced // Removes the name attribute session.removeAttribute("name"); // Trigger attributeReplaced %>Copy the code
The listener
public class MyHttpSessionAttributeListener implements
HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
// Add attributes
System.out.println("Added an attribute to session...");
// Know to add attribute names and values
HttpSession session = se.getSession();
// se.getValue But this method does not return the current value
System.out.println("Attribute Name:" + se.getName());
System.out.println("Attribute value:" + session.getAttribute(se.getName()));
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
// Attribute removed
System.out.println("Remove an attribute from session....");
System.out.println("Attribute Name:" + se.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
// Attribute substitution
System.out.println("Replace a session attribute value with another value...");
HttpSession session = se.getSession();
System.out.println("Attribute Name:" + se.getName());
System.out.println("Attribute value:"+ session.getAttribute(se.getName())); }}Copy the code
registered
<listener>
<listener-class>
cn.megustas.servlet.listener.MyHttpSessionAttributeListener
<listener-class>
</listener>
Copy the code
Note: Get the return value via session.getAttribute(se.getName())
(3) Bound Session object, self state aware listener
Objects stored in the Session domain can have multiple states: bound to the Session; Unbind from the Session domain; Persisting the Session object to a storage device (passivation) Recovering from a storage device with the Session object (activation)
A Java object stored in a Session senses four state changes of its own
- Be bound
- Unbound
- Passivated – Serialize data from memory to hard disk
- Activated — Data is reloaded from the hard disk back into memory
HttpSessionBindingListener interface implementation Java objects, perceived that they were bound to the Session or unbound from the Session HttpSessionActivationListener interface implementation Java objects, Classes that realize these two interfaces do not need to be registered in the web.xml file. They are all done by the Session itself. For example, binding is automatically invoked when storing objects
HttpSessionBindingListener * valueBound (HttpSessionBindingEvent event) binding Object method – – session. SetAttribute (name, Object); * valueUnbound(HttpSessionBindingEvent Event) Unbinding method — session.removeAttribute(). When the session object is destroyed, all bound objects are unbound
The JSP page:
<body> <% Bean1 bean1 = new Bean1(); bean1.setId(100); bean1.setName("Megustas"); SetAttribute ("bean1",bean1); setAttribute("bean1",bean1); setAttribute("bean1",bean1); Bean1 bean2 = new Bean1(); bean2.setId(200); Bean2. Elegantly-named setName (" Mary "); Session.setattribute ("bean1",bean2); // unbind session.removeAttribute("bean1"); %> ${bean1.name } </body>Copy the code
/** * make Bean1 feel that it is bound to the Session, and feel that it is unbound by the Session ** /
public class Bean1 implements HttpSessionBindingListener {
private int id;
private String name;
public int getId(a) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("The Bean1 object is bound...");
// Current object, operation object
System.out.println("Binding object name:" + this.name);
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("The Bean1 object is unbound...");
System.out.println("Unbind object name:" + this.name); }}Copy the code
HttpSessionActivationListener * sessionDidActivate HttpSessionEvent (se) perception object is activated * sessionWillPassivate (HttpSessionEvent Se) Use scenario: Session stores data, which is not used for a long time, but cannot destroy the Session object, and does not want to occupy server memory resources — passivation (serialize the data in server memory to disk)
/ perception passivation and activation of * * * * * / public class Bean2 implements HttpSessionActivationListener, Serializable {private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @override public void sessionDidActivate(HttpSessionEvent se) {system.out.println ("bean2 object is activated... ); } @override public void sessionWillPassivate(HttpSessionEvent se) {system.out.println ("bean2 object passivated... ); }}Copy the code
JSP interface
<body> <! <% Bean2 Bean2 = new Bean2(); Bean2.setname (" lenovo notebook "); bean2.setName(" Lenovo notebook "); bean2.setPrice(5000); session.setAttribute("bean2",bean2); %> </body>Copy the code
Read the data
<body> <! ${bean2.name}, ${bean2.price} </body>Copy the code
Pay attention to
Passivation and activation should be done automatically by the Tomcat server — configure Tomcat
< Context > / / file after 1 minute to perform passivation < Manager className = "org. Apache. Catalina. Session. PersistentManager" maxIdleSwap = "1" > / / file passivation to it315 folder < Store className = "org. Apache. Catalina. Session. FileStore" directory = "it315" / > < / Manager > < / Context >Copy the code
How many places are there to configure the context? 1, tomcat/conf/context. The XML for all virtual host all effective web project 2, tomcat/conf/Catalina/localhost/context. The XML for the current virtual host all web project into effect The current project/meta-INF /context. XML is valid for the current project
Where is the IT315 catalog after passivation? In the tomcat/work/Catalina/localhost/project name “directory
If you want to serialize a Java object, you need to implement the Serializable interface (so Bean2 implements the Serializable interface, which can be passivated and then activated and read)
What can be configured in the web.xml file?
A: Web. XML is used to configure information about Web applications, such as listeners, filters, servlets, related parameters, session timeout duration, security authentication mode, and error pages. The following are common configurations during development:
Load the Spring configuration file and create an IoC container:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Copy the code
Spring OpenSessionInView filter to resolve lazy loading and Hibernate session closing:
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Copy the code
③ Set the session timeout period to 10 minutes.
<session-config>
<session-timeout>10</session-timeout>
</session-config>
Copy the code
Error page 404 and Exception:
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
Copy the code
⑤ Configure the security authentication mode:
<security-constraint>
<web-resource-collection>
<web-resource-name>ProtectedArea</web-resource-name>
<url-pattern>/admin/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<security-role>
<role-name>admin</role-name>
</security-role>
Copy the code
* * note: ** The Servlet 3 specification provides an annotation-based configuration approach for Web components such as servlets, listeners, and filters. You can configure it using the @webServlet, @WebListener, and @webFilter annotations, respectively.
If the Web provides valuable business information or sensitive data, then the security of your site is a concern. Security certification is an important means to achieve security, certification is to solve the “Are you who you say you Are? The problem. There are many ways of certification, which can be briefly divided into three categories: A. What you know? — Password B. What do you have? — Digital certificate (U shield, secret protection card) C. – Fingerprint identification and iris identification Tomcat supports security by establishing Secure Socket Layer (SSL) and basic authentication or form authentication.
14. Which JSTL tags have you used in your projects?
A: JSTL’s core tag library is mainly used in the project, including < C :if>, < C: Choose >, < C: when>, < C: otherwise>, < C :forEach>, etc., which is mainly used to construct loop and branch structures to control the display logic.
Note: * * * * although JSTL tag library provides core, such as SQL, FMT, XML tag library, but in the actual development suggest only use the core tag library (core), and only use the best branch and loop tag along with expression language (EL), in this way can we truly data display and the separation of business logic, this is the best practice.
15. What are the benefits of using a tag library? How do I customize JSP tags?
A: The benefits of using a tag library include the following:
- Separating the content and logic of JSP pages simplifies Web development;
- Developers can create custom tags to encapsulate business logic and display logic;
- Tags have good portability, maintainability and reuse.
- Eliminates the use of scriptlets (many corporate projects do not allow scriptlets in JSPS)
Customizing JSP tags involves the following steps:
- Write a Java class implementations of the Tag/BodyTag IterationTag interface (developing but usually do not directly implement the interface inheritance TagSupport BodyTagSupport/SimpleTagSupport class, this is the application of adaptation mode by default). Rewrite methods like doStartTag() and doEndTag() to define what the tag is supposed to do
- Write a tag description file with the TLD extension to deploy custom tags. The TLD file is usually placed in the Web-INF folder or subdirectory
- Use the taglib directive to reference the tag library in a JSP page
Here is an example of a custom tag library.
Step 1 – Tag class source code timetag.java:
package com.hzy.tags;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class TimeTag extends TagSupport {
private static final long serialVersionUID = 1L;
private String format = "yyyy-MM-dd hh:mm:ss";
private String foreColor = "black";
private String backColor = "white";
public int doStartTag(a) throws JspException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
JspWriter writer = pageContext.getOut();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s",
foreColor, backColor, sdf.format(new Date())));
try {
writer.print(sb.toString());
} catch(IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
public void setFormat(String format) {
this.format = format;
}
public void setForeColor(String foreColor) {
this.foreColor = foreColor;
}
public void setBackColor(String backColor) {
this.backColor = backColor; }}Copy the code
Step 2 – Write the tag library description file my.tld:
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>Define the tag library</description>
<tlib-version>1.0</tlib-version>
<short-name>MyTag</short-name>
<tag>
<name>time</name>
<tag-class>com.jackfrued.tags.TimeTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>format</name>
<required>false</required>
</attribute>
<attribute>
<name>foreColor</name>
</attribute>
<attribute>
<name>backColor</name>
</attribute>
</tag>
</taglib>
Copy the code
Step 3 – Use custom tags in JSP pages:
<%@ page pageEncoding="UTF-8"%> <%@ taglib prefix="my" uri="/WEB-INF/tld/my.tld" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; % ><! DOCTYPEhtml>
<html>
<head>
<base href="<%=basePath%>">
<title>Home page</title>
<style type="text/css">
* { font-family: "Arial"; font-size:72px; }
</style>
</head>
<body>
<my:time format="yyyy-MM-dd" backColor="blue" foreColor="yellow"/>
</body>
</html>
Copy the code
** If you want to publish a customized tag library as a JAR file, you need to put the tag library description file (TLD file) in the META-INF directory of the JAR file. You can use the JAR tool in JDK to generate the JAR file.
16. Let’s talk about implicit objects in the Expression language (EL) and what they do.
A: Implicit objects for EL include: PageContext, initParam (access context parameters), PARAM (access request parameters), paramValues, Header (access request headers), headerValues, cookie (access cookies), applicationScope (access Application scope, sessionScope, requestScope, pageScope, page scope.
The usage is as follows:
${pageContext.request.method}
${pageContext["request"]["method"]}
${pageContext.request["method"]}
${pageContext["request"].method}
${initParam.defaultEncoding}
${header["accept-language"]}
${headerValues["accept-language"][0]}
${cookie.jsessionid.value}
${sessionScope.loginUser.username}
Copy the code
** Addendum: ** expression language. This is the same as the [] operator, except that if the attribute name is not a Java identifier, for example, accept-language is not a valid Java identifier, then the [] operator is used instead. The operator gets its value
17. What operators does the expression language (EL) support?
Answer: In addition to the. And [] operators, EL also provides:
- Arithmetic operators: +, -, *, / or div, %, or mod
- Relational operators: == or eq,! = or NE, > or gt, >= or GE, < or lt, <= or LE
- Logical operators && or the and, | | or or,! Or not
- Conditional operator: ${statement? A: B} (similar to Java conditional operators)
- Empty operator: checks whether a value is null or empty (returns true if array length is 0 or if there are no elements in the collection)
18. What are Model 1 and Model 2 for Java Web development?
A: Model 1 is a page-centric Java Web development, using JSP+JavaBean technology to separate the page display logic and business logic processing, JSP page display, JavaBean objects used to save data and business logic. Model 2 is a development Model based on MVC (Model-View-controller, Model-View-Controller) architecture pattern, which achieves the complete separation of Model and View, facilitating team development and code reuse, as shown in the figure below.
19. What is asynchronous processing in Servlet 3? 六四事件
A: A new technique introduced in Servlet 3 enables servlets to process requests asynchronously. One might wonder, given that we have multiple threads, why do we need to process requests asynchronously? The answer is yes, because if a task processing time is quite long, so the Servlet or Filter will always occupy a request processing threads until the end of the mission, with the increase of concurrent users, the container will be thread beyond the risk, that this case many requests will be piled up and subsequent requests may be at risk from denial of service, Until there are resources available to process the request. Asynchronous features help applications save threads in the container, especially for tasks that take a long time to execute and require the user to get a result. If the user does not need a result, simply hand a Runnable object to the Executor and return it immediately.
** Multithreading is undoubtedly a bright spot in the early days of the birth of Java, and the working way of Servlet single-instance multithreading has also won a good reputation for it. However, the development of technology will often overturn many of our cognition, just as Einstein’s theory of relativity overturned Newton’s classical mechanics. In fact, asynchronous processing was by no means a Serlvet 3 initiative, and this important improvement to Servlet 3 is not surprising if you know Node.js.
Here is an example of a Servlet that supports asynchronous processing of requests.
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/async"}, asyncSupported = true)
public class AsyncServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Enable Tomcat asynchronous Servlet support
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED".true);
final AsyncContext ctx = req.startAsync(); // Start the context for asynchronous processing
// ctx.setTimeout(30000);
ctx.start(new Runnable() {
@Override
public void run(a) {
// Add asynchronous processing code herectx.complete(); }}); }}Copy the code
20, How to implement file upload and download in Java-based Web projects?
A: Prior to Sevlet 3, there was no API in the Servlet API that supported uploads, so uploading required the introduction of third-party tools to retrieve uploaded attachments from POST requests or to process the input stream themselves to retrieve uploaded files. We recommend using Apache’s Commons – Fileupload. Starting with Servlet 3, file uploads are incredibly easy, and the following example should make that clear.
Upload page index.jsp:
<%@ page pageEncoding="utf-8"%>
<! DOCTYPEhtml>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Photo Upload</title>
</head>
<body>
<h1>Select your photo and upload</h1>
<hr/>
<div style="color:red; font-size:14px;">${hint}</div>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
Photo file: <input type="file" name="photo" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
Copy the code
Uploadable servlets:
package com.hzy.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// The upload attachment named photo can be obtained using the request.getPart() method
// You can also use request.getParts() to get all upload attachments.
// Then process each uploaded file separately through a loop
Part part = request.getPart("photo");
if(part ! =null && part.getSubmittedFileName().length() > 0) {
// Use the getRealPath() method of the ServletContext object to get the absolute path to the uploaded folder
String savePath = request.getServletContext().getRealPath("/upload");
// The Servlet 3.1 specification can use the getSubmittedFileName() method of the Part object to get the name of the uploaded file
// It is better to rename uploaded files (to avoid overwriting files with the same name)
part.write(savePath + "/" + part.getSubmittedFileName());
request.setAttribute("hint"."Upload Successfully!");
} else {
request.setAttribute("hint"."Upload failed!");
}
// Jump back to the upload page
request.getRequestDispatcher("index.jsp").forward(request, response); }}Copy the code
When the server receives form data submitted by the user, does it call doGet() or doPost() of the Servlet?
Answer: the HTML
What is the difference between static and dynamic inclusion in JSP?
A: Static includes include pages through JSP’s include directive, and dynamic includes pages through the JSP standard action JSP: Forward. Static inclusion is compile-time inclusion, and a compilation error occurs if the included page does not exist, and the “contentType” property of the two pages should remain the same, because the two pages are merged into one, producing only one class file, so changes to the included page are not updated until the included page is updated. Dynamic include is run time include, you can pass parameters to the included page, the included page and the included page are independent, will compile two class files, if the included page does not exist, will not generate compilation errors, does not affect the execution of the rest of the page. The code looks like this:
<%-- static include --%> <% @include file="..." %> <%-- dynamic include --%> < JSP :include page="... > <jsp:param name="..." value="..." /> </jsp:include>Copy the code
23. How do I get user-submitted query parameters or form data in a Servlet?
A: You can get the parameter value from the parameter name through the getParameter() method of the request object (HttpServletRequest). If you have parameters that contain multiple values (such as check boxes), you can get them from the getParameterValues() method of the request object. You can also get a Map of parameter names and parameter values by requesting getParameterMap() of the object.
24. How do I get user-configured initialization parameters and server context parameters in the Servlet?
A: You can get the initialization parameters of the Servlet by overriding the init(ServletConfig) method of the Servlet interface and using the getInitParameter() method of the ServletConfig object. The ServletContext object can be obtained through the getServletContext() method of the ServletConfig object, and the server context parameters can be obtained through the getInitParameter() method of the object. Of course, the ServletContext object is also obtained from the request object’s getServletContext() method in methods that handle user requests, such as the doGet() method.
25, how to set the request encoding and response content type?
A: The setCharacterEncoding(String) method of the ServletRequest (ServletRequest) can be used to set the encoding of the request. In order to completely solve the problem of garble, the page, server, request and response, and Java programs should use the same encoding. The best choice is of course UTF-8. The setContentType(String) method of the response object sets the type of the response content, This can also be set through the setHeader(String, String) method of the HttpServletResponsed object.
26. Explain the patterns and characteristics of network applications
A: There are three typical network application modes: B/S, C/S and P2P. B represents the Browser, C represents the Client, and S represents the Server. P2P is a peer-to-peer mode that does not distinguish between clients and servers. The B/S application mode can be regarded as the special C/S application mode, but the special client in THE C/S application mode is replaced by the browser. Because almost all systems have browsers, you can use the application as long as you open the browser, and there is no cost caused by installing, configuring, and upgrading the client. In P2P applications, thousands of interconnected computers are in a peer-to-peer position, and the entire network generally does not rely on dedicated centralized servers. Each computer in the network can act as a requester of network services and provide resources and services in response to the requests of other computers. Usually these resources and services include: information sharing and exchange, computing resources (such as CPU sharing), storage, sharing, such as the use of the cache and disk space), etc., this application mode maximum resistance problem such as security, version, there are many applications are a mixture of a variety of application models, the most common network video applications, the three modes are almost use it.
27. What is a Web Service?
A: On the surface, a Web Service is an application that exposes an API that can be invoked through the Web. This means that you can programmatically invoke the application transparently, without knowing any of its details, and regardless of the programming language you use. For example, you can create a Web Service that provides a weather forecast, so whatever programming language you’re developing in can call its API and pass in city information to get a weather forecast for that city. A Web Service is called a Web Service because it transfers data over the HTTP protocol, enabling different applications running on different machines to exchange data or integrate with each other without additional, specialized third-party software or hardware.
* * added: ** One concept that must be mentioned here is service-oriented Architecture (SOA), the idea of linking different functional units of an application through a neutral contract, independent of hardware platform, operating system, and programming language, Make various forms of functional units can be better integrated. Clearly, Web Services are a better solution to SOA and are more of a standard than a concrete technology.
28. Concept explanation: SOAP, WSDL, UDDI
A:
- SOAP: Simple Object Access Protocol (SOAP) is a Protocol specification for exchanging data in Web Services.
- WSDL: Web Service Description Language, which describes the common interface of Web services. This is an XML-based service description of how to communicate with and use Web services; That is, describe the protocols and information formats that need to be bound when interacting with the Web services listed in the catalog. Abstract language is usually used to describe the operations and information supported by the service, and then the actual network protocol and information format are bound to the service.
- UDDI: Universal Description, Discovery and Integration (UDDI) is an XML-based cross-platform Description specification that enables businesses worldwide to publish their services on the Internet. Simply put, UDDI is a facade for accessing various WSDLS (see facade schema in Design patterns).
** The concepts and knowledge about Web Service can be found on W3CSchool.
29, What are the Java specifications related to Web Services?
A: The Java specification has three references to Web services:
- Jax-ws (JSR 224) : This specification is a replacement version of JAX-RPC, the earlier SOAP-based Web Service specification, and does not provide downward compatibility because RPC-style WSDL and associated apis have been removed in Java EE5. Ws-metadata is a JAX-WS dependency specification that provides apis for configuring Web services and SOAP messages based on annotations.
- JAXM(JSR 67) : Defines the apis needed to send and receive messages, equivalent to the server side of a Web Service.
- Jax-rs (JSR 311 & JSR 339 & JSR 370) : Is a set of Web Service specifications developed by Java for the Representation State Transfer (REST) architecture style. REST is a software architecture pattern, a style that does not carry a messaging protocol as SOAP does. (Both styles of Web services use HTTP as a transport protocol because HTTP can traverse firewalls. Java’s remote method Invocation (RMI) is a heavyweight protocol. You can think of REST as a software architecture based on the HTTP protocol. The two most important concepts in REST are resource location and resource manipulation, and HTTP provides both. HTTP urIs can locate resources, while GET, POST, OPTION, and DELETE methods can operate resources. Therefore, REST can completely rely on HTTP to complete Web services, unlike SOAP, which only uses HTTP transport features, positioning and operations are completed by SOAP itself. It is the existence of SOAP messages that makes SOAP-based Web services cumbersome and obsolete.
30. Introduce Web Service frameworks that you know about in the Java domain
A: There are many Web Service frameworks in the Java space, including Axis2 (an upgraded version of Axis), Jersey (RESTful Web Service framework), CXF (a continuation of XFire), Hessian, Turmeric, JBoss SOA, etc. Most of these are open source frameworks.