Complete Works of Java Interview Questions(11)

Complete Works of Java Interview Questions(11)

Baiyu IT haha

101. What are the commonly used Web servers?

Answer: The most widely used free HTTP server under Unix and Linux platforms is the Apache server, while the Windows platform server usually uses IIS as the web server. The factors that should be considered when choosing a Web server are: performance, security, logs and statistics, virtual hosts, proxy servers, buffering services, and integrated applications. The following is an introduction to common servers:

  • IIS: Microsoft's Web server product, the full name is Internet Information Services. IIS is a Web server that allows information to be published on the public Intranet or the Internet. IIS is currently one of the most popular web server products, and many well-known websites are built on the IIS platform. IIS provides a graphical interface management tool called Internet Service Manager, which can be used to monitor, configure and control Internet services. IIS is a Web service component, including Web server, FTP server, NNTP server and SMTP server, respectively used for web browsing, file transfer, news service and mail sending, etc., it enables the network (including Internet and LAN) Publishing information has become a very easy task. It provides ISAPI (Intranet Server API) as a programming interface for extending the functions of the Web server; at the same time, it also provides an Internet database connector that can query and update the database.
  • Kangle: Kangle Web server is a cross-platform, powerful, safe, stable, and easy-to-operate high-performance Web server and reverse proxy server software. In addition, Kangle is also a web server developed specifically for virtual hosting. Realize virtual host independent process and independent identity operation. Security isolation between users, one user will not affect other users. Support multiple dynamic development languages ​​such as PHP, ASP, ASP.NET, Java, Ruby, etc.
  • WebSphere: WebSphere Application Server is a fully functional and open Web application server. It is the core part of IBM's e-commerce plan. It is a Java-based application environment for establishing, deploying and managing Internet and Intranet Web applications, adapting to various The need for a web application server.
  • WebLogic: WebLogic Server is a multi-functional, standards-based Web application server that provides a solid foundation for enterprises to build enterprise applications. Weblogic provides corresponding support for various application development, deployment of key tasks, integration of various systems and databases, and cross-Internet collaboration. Because of its comprehensive functions, compliance with open standards, multi-layer architecture, and support for component-based development, many companies’ enterprise-level applications choose it as the development and deployment environment. WebLogic Server has been in a leading position in making application servers the foundation of enterprise application architecture, providing a solid foundation for building integrated enterprise-level applications.
  • Apache: At present, Apache is still the most used web server in the world, and its market share has remained above 60% for a long time (the current market share is about 40%). Many famous websites in the world are products of Apache. Its success lies in its open source code, a strong development team, and support for cross-platform applications (it can run on almost all Unix, Windows, Linux systems) Platform) and its portability.
  • Tomcat: Tomcat is an open source, running Servlet and JSP container. Tomcat implements Servlet and JSP specifications. In addition, Tomcat also implements the Apache-Jakarta specification and is better than most commercial application software servers, so many Web servers currently choose Tomcat.
  • Nginx: pronounced "engine x", it 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. The first public version 0.1.0 was released on October 4, 2004. It releases its source code in the form of a BSD-like license, and is known for its stability, rich feature set, sample configuration files and low system resource consumption. In the second half of 2014, Nginx's market share reached 14%.

    102. What is the relationship between JSP and Servlet?

    Answer: In fact, this issue has already been explained above. Servlet is a special Java program that runs in the JVM of the server and can rely on the support of the server 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 Servlet and JSP is that the application logic of Servlet is in Java files and is completely separated from the 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 Servlet is to write HTML in Java, and JSP is to write Java code in HTML. Of course, this statement is very one-sided and not accurate enough. JSP focuses on the view, Servlet focuses more on the control logic, in the MVC architecture pattern, JSP is suitable for the view (view) and Servlet is suitable for the controller (controller).

    103. Explain the four scopes in JSP.

    Answer: The four scopes in JSP include page, request, session, and application. Specifically:

  • page represents objects and attributes related to a page.
  • request represents objects and attributes related to a request issued by a Web client. A request may span multiple pages and involve multiple Web components; temporary data that needs to be displayed on the page can be placed in this scope.
  • Session represents objects and attributes related to a session established by a certain user with the server. Data related to a user should be placed in the user's own session.
  • Application represents objects and attributes related to the entire Web application. It is essentially a global scope spanning the entire Web application, including multiple pages, requests, and sessions.

    104. How to realize the single thread mode of JSP or Servlet?

    Answer:
    For JSP pages, it can be set through the page command.
    <%@page isThreadSafe=”false”%>
    For Servlet, you can make a custom Servlet implement the SingleThreadModel identification interface.

Note: If the JSP or Servlet is set to a single-threaded work mode, it will cause each request to create a Servlet instance. This practice will lead to serious performance problems (the server's memory pressure is very large, and it will also cause frequent garbage collection). So it's not usually done.

105. What are the technologies for implementing session tracking?

Answer: Since the HTTP protocol itself is stateless, the server needs to track the user session in order to distinguish between different users. In short, it is to register the user and assign a unique ID to the user. The next time the user includes this in the request ID, the server judges which user it is based on this.
①URL rewriting: add user session information in the URL as a request parameter, or add a unique session ID to the end of the URL to identify a session.
②Set the hidden fields of the form: add fields related to session tracking to the hidden form fields. This information will not be displayed in the browser but will be submitted to the server when the form is submitted.
These two methods are difficult to handle information transfer across multiple pages, because if you have to modify the URL every time or add implicit form fields to the page to store user session-related information, things will become very troublesome.
③Cookie: There are two types of cookies. One is window-based. After the browser window is closed, the cookie is gone; the other is to store information in a temporary file and set the time of existence. When the user establishes a session with the server through the browser, the session ID will be returned with the response information and stored in the window-based cookie, which means that as long as the browser is not closed and the session does not time out, the session ID will be again on the next request. Will be submitted to the server for the server to identify the user. You can save information for the user during the session. The session object is in the server's memory, while the window-based cookie is in the client's memory. If the browser disables cookies, then the following two methods are required for session tracking. Of course, there are several points to pay attention to when using cookies: First, do not store sensitive information in cookies; secondly, the amount of data stored in cookies is limited (4k), so you cannot store too much content in cookies; and browsers usually only allow one site Store up to 20 cookies. Of course, other information related to the user's session (except the session ID) can also contain cookies to facilitate session tracking.
④HttpSession: Among all session tracking technologies, the HttpSession object is the most powerful and the most versatile. When a user visits a website for the first time, an HttpSession is automatically created, and each user can access his own HttpSession. The HttpSession can be obtained through the getSession method of the HttpServletRequest object, and a value can be placed in the HttpSession through the setAttribute method of the HttpSession. The object stored in the HttpSession can be obtained by calling the getAttribute method of the HttpSession object and passing in the attribute name. The difference from the above three methods is that HttpSession is placed in the memory of the server, so do not put too large objects in it, even if the current Servlet container can move the objects in HttpSession to other storage devices when the memory is full , But this is bound to affect performance. The value added to the HttpSession can be any Java object. This object preferably implements the Serializable interface so that the Servlet container can serialize it to the file when necessary, otherwise an exception will occur during serialization.

Supplement: Web Storage technology can be used in HTML5 to save data through JavaScript. For example, localStorage and sessionStorage can be used to save user session information, and session tracking can also be achieved.

106. What are the functions and usages of filters?

Answer: The filter in Java Web development is a function added from the Servlet 2.3 specification and enhanced in the Servlet 2.4 specification. For web applications, a filter is a web component that resides on the server side. It can intercept the request and response information between the client and the server, and filter the information. When the web container receives a request for a resource, it will determine whether there is a filter associated with the resource. If so, the container will pass the request to the filter for processing. In the filter, you can change the content of the request, or reset the header information of the request, and then send the request to the target resource. When the target resource responds to the request, the container will also forward the response to the filter first, where you can transform the content of the response, and then send the response to the client.
Common filter uses mainly include: uniformly authenticating user requests, recording and reviewing user access requests, filtering or replacing data sent by users, converting image formats, compressing response content to reduce transmission, Encrypt and decrypt requests or responses, trigger resource access events, and apply XSLT to XML output.
The interfaces related to filters mainly include: Filter, FilterConfig and FilterChain.
Examples of encoding filters:


import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.annotation.WebFilter;import javax.servlet.annotation.WebInitParam;@WebFilter(urlPatterns = { "*" }, 
        initParams = {@WebInitParam(name="encoding", value="utf-8")})public class CodingFilter implements Filter {
    private String defaultEncoding = "utf-8";    @Override
    public void destroy() {
    }    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding(defaultEncoding);
        resp.setCharacterEncoding(defaultEncoding);
        chain.doFilter(req, resp);
    }    @Override
    public void init(FilterConfig config) throws ServletException {
        String encoding = config.getInitParameter("encoding");        if (encoding != null) {
            defaultEncoding = encoding;
        }
    }
}

Example of download count filter:


import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Properties;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;@WebFilter(urlPatterns = {"/*"})public class DownloadCounterFilter implements Filter {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();    private Properties downloadLog;    private File logFile;    @Override
    public void destroy() {
        executorService.shutdown();
    }    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;        final String uri = request.getRequestURI();
        executorService.execute(new Runnable() {            @Override
            public void run() {
                String value = downloadLog.getProperty(uri);                if(value == null) {
                    downloadLog.setProperty(uri, "1");
                }                else {                    int count = Integer.parseInt(value);
                    downloadLog.setProperty(uri, String.valueOf(++count));
                }                try {
                    downloadLog.store(new FileWriter(logFile), "");
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        chain.doFilter(req, resp);
    }    @Override
    public void init(FilterConfig config) throws ServletException {
        String appPath = config.getServletContext().getRealPath("/");
        logFile = new File(appPath, "downloadLog.txt");        if(!logFile.exists()) {            try {
                logFile.createNewFile();
            } 
            catch(IOException e) {
                e.printStackTrace();
            }
        }
        downloadLog = new Properties();        try {
            downloadLog.load(new FileReader(logFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Note: The annotations in the Servlet 3 specification are used here to deploy filters. Of course, you can also use <filter> and <filter-mapping> tags to deploy filters in web.xml, as shown in Question 108.

107. What are the functions and usages of the listener?

Answer: The listener in Java Web development is a functional component that automatically executes code when the three objects of application, session, and request are created, destroyed, or added to modify and delete attributes, as follows:
①ServletContextListener: creation of Servlet context And destroy for monitoring.
②ServletContextAttributeListener: monitor the addition, deletion and replacement of Servlet context attributes.
③HttpSessionListener: monitor the creation and destruction of Session.

Supplement: There are two situations for session destruction: 1). Session timeout (you can configure the timeout time through the <session-config>/<session-timeout> tag in web.xml); 2). By calling the invalidate( of the session object) ) Method invalidates the session.

④HttpSessionAttributeListener: monitor the addition, deletion and replacement of attributes in the Session object.
⑤ServletRequestListener: monitor the initialization and destruction of the request object.
⑥ServletRequestAttributeListener: monitor the addition, deletion and replacement of request object attributes.
Below is an example of a monitor that counts the most online people on a website.

Note: The @WebListener annotation in the Servlet 3 specification is used to configure the listener. Of course, you can configure the listener with the <listener> tag in the web.xml file, as shown in Question 108.

108. What can be configured in the web.xml file?

Answer: web.xml is used to configure the relevant information of the web application, such as: listener, filter, Servlet, related parameters, session timeout, security verification method, error page, etc. The following are some in development Common configuration:
①Configure the spring context loading listener to load the Spring configuration file and create the 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>

② Configure Spring's OpenSessionInView filter to solve the contradiction between 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>

③Configure the session timeout time to 10 minutes:


  <session-config>
      <session-timeout>10</session-timeout>
  </session-config>

④Configure 404 and Exception error pages:


  <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>

⑤Configure the security authentication method:


  <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>

Note: For the configuration of Web components such as Servlet (small service), Listener (listener) and Filter (filter), the Servlet 3 specification provides an annotation-based configuration method, which can be carried out using @WebServlet, @WebListener, and @WebFilter annotations respectively. Configuration.

Supplement: If the Web provides valuable commercial information or sensitive data, then the security of the site must be considered. Security certification is an important means to achieve security, certification is to solve the "Are you who you say you are?" problem. There are many ways of authentication. In short, they can be divided into three categories:
A. What you know? — password
B. What you have? — digital certificate (U shield, secret security card)
C. Who you are? — fingerprint recognition, iris recognition
in Tomcat via secure sockets layer (secure socket layer, SSL) and security is achieved by supporting the basic form validation or verification.

109. Which JSTL tags have been used in your project?

Answer: The core tag library of JSTL is mainly used in the project, including <c:if>, <c:choose>, <c: when>, <c: otherwise>, <c:forEach>, etc., which are mainly used to construct loops And branch structure to control the display logic.

Note: Although the JSTL tag library provides core, sql, fmt, xml and other tag libraries, it is recommended to use only the core tag library (core) in actual development, and it is best to use only branch and loop tags supplemented by expression language (EL ), so as to truly achieve the separation of data display and business logic, this is the best practice.

110. What are the benefits of using tag libraries? How to customize JSP tags?

Answer: The benefits of using tag libraries include the following:

  • Separate the content and logic of JSP pages, simplifying Web development;
  • Developers can create custom labels to encapsulate business logic and display logic;
  • The label has good portability, maintainability and reusability;
  • Avoid the use of Scriptlets (small scripts) (many companies do not allow small scripts to be written in JSP for project development)
    Customizing JSP tags includes the following steps:
  • Write a Java class to implement the Tag/BodyTag/IterationTag interface (usually not directly implement these interfaces in development but inherit the TagSupport/BodyTagSupport/SimpleTagSupport class, which is the application of the default adaptation mode), and override doStartTag(), doEndTag () and other methods to define the function to be completed by the label
  • Write a label description file with the extension tld to deploy the custom label. The tld file is usually placed in the WEB-INF folder or its subdirectories
  • Use the taglib directive to reference the tag library in the JSP page. The
    following is an example of a custom tag library.
    Step 1-Tag class source code TimeTag.java:

Step 2-Write the label library description file my.tld:


<?xml version="1.0" encoding="UTF-8" ?><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>定义标签库</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>

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 + "/";
%><!DOCTYPE html><html>
  <head>
    <base href="<%=basePath%>">
    <title>首页</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>

Tip: If you want to publish a custom tag library into a JAR file, you need to put the tag library description file (tld file) in the META-INF directory of the JAR file, and you can complete the JAR file generation with the jar tool in the JDK

Guess you like

Origin blog.51cto.com/15061944/2593706