Summary of interview questions (4) Reflection, Web

reflection

 

57. What is reflection?

 

Reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior

Java reflection:

 

In the Java runtime environment, for any class, can I know what properties and methods this class has? For any object, can it call any of its methods

The Java reflection mechanism mainly provides the following functions:

 

  • At run time, determine the class to which any object belongs.

  • Construct an object of any class at runtime.

  • Determine the member variables and methods of any class at runtime.

  • Call any object method at runtime. 

 

58. What is java serialization? When is serialization required?

 

In short, it is to save the state of various objects in memory (that is, instance variables, not methods), and you can read the saved object state again. Although you can use your own various methods to save object states, Java provides you with a mechanism that should be better than your own to save object states, that is, serialization.

When to serialize:

 

a) When you want to save the state of objects in memory to a file or database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI ;

 

59. What is a dynamic agent? What are the applications?

 

Dynamic proxy:

 

When you want to add some additional processing to a method in a class that implements an interface. For example, add logs, add transactions, etc. You can create a proxy for this class, so the name is to create a new class. This class not only contains the functions of the original class methods, but also adds a new class for additional processing on the original basis. This proxy class is not defined, it is dynamically generated. It has the meaning of decoupling, flexibility and strong expansibility.

 

Application of dynamic proxy:

 

  • Spring的AOP

  • Plus transaction

  • Add permissions

  • Add log

 

60. How to implement dynamic proxy?

 

First, an interface must be defined, and there must also be an InvocationHandler (passing the object of the class that implements the interface to it) processing class. There is another tool class Proxy (habitually called it a proxy class, because calling his newInstance () can generate a proxy object, in fact, he is just a tool class that generates a proxy object). Use InvocationHandler, stitch the source code of the proxy class, compile it to generate the binary code of the proxy class, load it with the loader, and instantiate it to generate the proxy object, and finally return.

 

Object copy

 

61. Why use cloning?

 

If you want to process an object, and you want to keep the original data for the next operation, you need to clone it. In Java, cloning refers to an instance of a class.

 

62. How to achieve object cloning?

 

There are two ways:

 

1). Implement the Cloneable interface and override the clone () method in the Object class;

  

2). Implementing the Serializable interface, cloning through serialization and deserialization of objects, can achieve true deep cloning, the code is as follows:

 

 

​​​​​​​

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
public class MyUtil {
    private MyUtil() {        throw new AssertionError();    }
    @SuppressWarnings("unchecked")    public static <T extends Serializable> T clone(T obj)                                   throws Exception {        ByteArrayOutputStream bout = new ByteArrayOutputStream();        ObjectOutputStream oos = new ObjectOutputStream(bout);        oos.writeObject(obj);
        ByteArrayInputStream bin =                     new ByteArrayInputStream(bout.toByteArray());        ObjectInputStream ois = new ObjectInputStream(bin);        return (T) ois.readObject();
        // 说明:调用ByteArrayInputStream        //或ByteArrayOutputStream对象的close方法没有任何意义        // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源,        //这一点不同于对外部资源(如文件流)的释放    }}

 

 

Here is the test code:

 

​​​​​​​​​​​​​​

import java.io.Serializable;
/** * 人类 * @author nnngu * */class Person implements Serializable {    private static final long serialVersionUID                               = -9102017020286042305L;
    private String name;    // 姓名    private int age;        // 年龄    private Car car;        // 座驾
    public Person(String name, int age, Car car) {        this.name = name;        this.age = age;        this.car = car;    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }
    public int getAge() {        return age;    }
    public void setAge(int age) {        this.age = age;    }
    public Car getCar() {        return car;    }
    public void setCar(Car car) {        this.car = car;    }
    @Override    public String toString() {        return "Person [name=" + name + ",                       age=" + age + ", car=" + car + "]";    }
}

​​​​​​​

​​​​​​​

/** * 小汽车类 * @author nnngu * */class Car implements Serializable {    private static final long serialVersionUID                                 = -5713945027627603702L;
    private String brand;       // 品牌    private int maxSpeed;       // 最高时速
    public Car(String brand, int maxSpeed) {        this.brand = brand;        this.maxSpeed = maxSpeed;    }
    public String getBrand() {        return brand;    }
    public void setBrand(String brand) {        this.brand = brand;    }
    public int getMaxSpeed() {        return maxSpeed;    }
    public void setMaxSpeed(int maxSpeed) {        this.maxSpeed = maxSpeed;    }
    @Override    public String toString() {        return "Car [brand=" + brand + ",                       maxSpeed=" + maxSpeed + "]";    }
}

 

​​​​​​​

class CloneTest {
    public static void main(String[] args) {        try {            Person p1 = new Person("郭靖", 33,                               new Car("Benz", 300));            Person p2 = MyUtil.clone(p1);   // 深度克隆            p2.getCar().setBrand("BYD");            // 修改克隆的Person对象p2关联的汽车对象的品牌属性            // 原来的Person对象p1关联的汽车不会受到任何影响            // 因为在克隆Person对象时其关联的汽车对象也被克隆了            System.out.println(p1);        } catch (Exception e) {            e.printStackTrace();        }    }}

 

 

Note: Cloning based on serialization and deserialization is not only deep cloning, but more importantly, through generic qualification, you can check whether the object to be cloned supports serialization. This check is done by the compiler, not in Exceptions are thrown at runtime. This is a solution that is significantly better than cloning objects using the clone method of the Object class. It's always better to expose the problem at compile time than to leave the problem at runtime.

 

63. What is the difference between deep copy and shallow copy?

 

  • Shallow copy only copies the reference address of the object, two objects point to the same memory address, so modify any value in it, and the other value will change accordingly. This is a shallow copy (for example: assign ())

  • Deep copy is to copy the object and value. If two objects modify any of the values, the other value will not change. This is a deep copy (for example: JSON.parse () and JSON.stringify (), but this method cannot copy the function Types of)

 

Java Web

 

64. What is the difference between jsp and servlet?

 

  1. After compiling, jsp becomes a Servlet. (The essence of JSP is Servlet. The JVM can only recognize the java class, but not the JSP code. The web container compiles the JSP code into a java class recognized by the JVM)

  2. jsp is better at displaying pages, and servlets are better at logic control.

  3. There are no built-in objects in Servlet. The built-in objects in Jsp must be obtained through HttpServletRequest object, HttpServletResponse object and HttpServlet object.

  4. Jsp is a simplification of Servlet. Using Jsp only needs to complete the content that programmers need to output to the client. How to inlay Java script in Jsp into a class is done by Jsp container. The Servlet is a complete Java class, the Service method of this class is used to generate a response to the client.

 

65. What built-in objects does jsp have? What is the role?

 

JSP has 9 built-in objects:

 

  • request: encapsulates the client's request, which contains the parameters from the GET or POST request;

  • response: encapsulates the server's response to the client;

  • pageContext: You can get other objects through this object;

  • session: the object that encapsulates the user's session;

  • application: objects that encapsulate the server's operating environment;

  • out: output stream object output by the server response;

  • config: configuration object of web application;

  • page: JSP page itself (equivalent to this in a Java program);

  • exception: Object that encapsulates the exception thrown by the page.


66. Tell me about the 4 scopes of jsp?

 

The four scopes in JSP include page, request, session, and application, specifically:

 

  • Page represents objects and attributes related to a page.

  • request represents the objects and attributes related to a request issued by the 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 between a user and the server. Data related to a user should be placed in the user's own session.

  • application represents the objects and attributes related to the entire Web application. It is essentially a global scope that spans the entire Web application, including multiple pages, requests, and sessions.


67. What is the difference between session and cookie?

 

  • Since the HTTP protocol is a stateless protocol, when the server needs to record the state of the user, it needs to use a mechanism to identify the specific user. This mechanism is the Session. Typical scenarios such as shopping carts, when you click the order button Since the HTTP protocol is stateless, it does not know which user is operating, so the server must create a specific session for a specific user, used to identify this user, and track the user, so that we know how many in the shopping cart The book. This session is stored on the server and has a unique identifier. There are many ways to save Session on the server, including memory, database, and files. When clustering, you should also consider the transfer of Session. On large websites, there will usually be a dedicated Session server cluster to save user sessions. At this time, Session information is stored in memory, and some cache services such as Memcached are used. Come and put Session.

  • Think about how the server identifies specific customers? At this time, Cookie appeared. Each time the HTTP request, the client will send the corresponding Cookie information to the server. In fact, most applications use cookies to implement session tracking. When creating a session for the first time, the server will tell the client in the HTTP protocol that a session ID needs to be recorded in the cookie. The session ID is sent to the server and I know who you are. Someone asks, what if the client's browser disables cookies? Generally, in this case, a technique called URL rewriting is used for session tracking, that is, every HTTP interaction, the URL will be appended with a parameter such as sid = xxxxx, and the server recognizes the user based on this.

  • Cookies can actually be used in some user-friendly scenarios. Imagine that you have logged in to a website once and you do n’t want to enter your account number again the next time you log in. What should you do? This information can be written in a cookie. When you visit the website, the script on the website page can read this information, and it will automatically fill in the user name for you, which can facilitate the user. This is also the origin of the cookie name, a little sweetness to the user. So, to sum up: Session is a data structure saved on the server, used to track the user's state, this data can be saved in the cluster, database, file; Cookie is a mechanism for the client to save user information, used to record Some user information is also a way to implement Session.

 

68. Tell me about how the session works?

 

In fact, the session is a file resembling a hash table stored on the server. It contains the information we need and can be taken out of it when we need it. Similar to a large map, the keys inside store the user's sessionid, and the user will bring this sessionid when sending a request to the server. At this time, the corresponding value can be taken out from it.

 

69. Can the session be used if the client prohibits cookies?

 

Cookie and Session are generally considered to be two separate things. Session adopts the scheme of maintaining state on the server side, while Cookie adopts the scheme of maintaining state on the client side. But why can't you get Session if you disable cookies? Because the Session uses the Session ID to determine the server session corresponding to the current session, and the Session ID is passed through the cookie, disabling the cookie is equivalent to losing the Session ID, and you will not get the Session.

 

Assuming that the user uses the session when the cookie is closed, the implementation methods are as follows:

 

  1. Set "session.use_trans_sid = 1" in the php.ini configuration file, or open the "--enable-trans-sid" option when compiling, and let PHP automatically pass the Session ID across pages.

  2. Manually pass the value through the URL and pass the Session ID on the hidden form.

  3. Save the Session ID in the form of files, databases, etc., and call it manually during the cross-page process.

 

70. What is the difference between spring mvc and struts?

 

  • Different interception mechanisms

 

Struts2 is a class-level interception. Each request creates an Action. When integrating with Spring, the ActionBean injection scope of Struts2 is the prototype mode prototype, and then the request data is injected into the property through the setter and getter. In Struts2, an Action corresponds to a request and response context. When receiving parameters, it can be received through attributes, which means that attribute parameters are shared by multiple methods. A method of Action in Struts2 can correspond to a url, but its class attribute is shared by all methods, which cannot be used to identify its own method using annotations or other methods, and can only be designed as multiple cases.

  

SpringMVC is a method-level interception. A method corresponds to a Request context, so the method is basically independent, with exclusive request and response data. And each method corresponds to which url at the same time, the transfer of parameters is directly injected into the method, which is unique to the method. The processing result is returned to the framework through ModeMap. During Spring integration, Spring MVC's Controller Bean defaults to the singleton mode Singleton, so by default for all requests, only one Controller will be created, and there should be no shared attributes, so it is thread-safe. If you want to change the default scope, Need to add @Scope annotation to modify.

  

Struts2 has its own Interceptor mechanism. SpringMVC uses an independent Aop method, which leads to a larger amount of Struts2 configuration files than SpringMVC.

 

  • The difference between the underlying framework

  

Struts2 is implemented with Filter (StrutsPrepareAndExecuteFilter), and SpringMVC (DispatcherServlet) is implemented with Servlet. The Filter is initialized after the container is started; the service crashes after it stops, later than the Servlet. The Servlet is initialized when it is called, before the Filter call, and destroyed after the service is stopped.

 

  • Performance

 

Struts2 is a class-level interception. Each request corresponds to an instance of a new Action. All attribute value injections need to be loaded. Spring MVC implements zero configuration. Due to Spring MVC's method-based interception, there is a singleton bean injection. Therefore, SpringMVC development efficiency and performance is higher than Struts2.

 

  • Configuration aspect

  

Spring MVC and Spring are seamless. The management and security of this project is also higher than Struts2.

 

71. How to avoid SQL injection?

 

  1. PreparedStatement (simple and effective method)

  2. Use regular expressions to filter incoming parameters

  3. String filtering

  4. Call this function in JSP to check if the packet is an illegal character

  5. JSP page judgment code

 

72. What is XSS attack and how to avoid it?

XSS attack is also known as CSS, the full name of Cross Site Script (cross-site scripting attack), the principle is that the attacker enters malicious HTML code into a website with XSS vulnerability, when the user browses the website, this HTML code will be automatically executed So as to achieve the purpose of attack. XSS attacks are similar to SQL injection attacks. In SQL injection attacks, SQL statements are used as user input to achieve the purpose of querying / modifying / deleting data. In xss attacks, malicious scripts are inserted to control user browsers. Some user information. XSS is a common vulnerability in Web programs. XSS is a passive and client-side attack method.

 

The general idea of ​​XSS prevention is to filter the input (and URL parameters) and encode the output.

 

73. What is a CSRF attack and how to avoid it?

 

CSRF (Cross-site request forgery) is also known as one-click attack or session riding. The full name in Chinese is called cross-site request forgery . Generally speaking, an attacker sends a request to a website that a user has authenticated to visit by forging a user's browser, so that the target website receives and mistakenly believes that it is the user's actual operation and executes the command. Commonly used to steal account numbers, transfer funds, send false messages, etc. The attacker uses the website's verification vulnerability of the request to implement such an attack. The website can confirm that the request originated from the user's browser, but cannot verify whether the request originated from the user's actual behavior.

 

How to avoid:

 

1. Verify the HTTP Referer field

 

The Referer field in the HTTP header records the source address of the HTTP request. Under normal circumstances, a request to access a security-restricted page comes from the same website, and if a hacker wants to implement a CSRF
attack on it, he can generally only construct a request on his own website. Therefore, CSRF attacks can be prevented by verifying the Referer value.

 

2. Use verification code

 

The verification code is added to the key operation page, and the CSRF can be defended by judging the verification code after receiving the request in the background. But this method is not user friendly.

 

3. Add token to the request address and verify

 

The reason why the CSRF attack is successful is because the hacker can completely forge the user's request. All user authentication information in the request is in the cookie, so the hacker can directly use the user's own cookie without knowing the authentication information. To pass security verification. To defend against CSRF, the key is to put in the request information that the hacker cannot forge, and the information does not exist in the cookie. You can add a randomly generated token in the form of parameters to the HTTP request, and establish an interceptor on the server to verify the token. If there is no token in the request or the token content is incorrect, it is considered that it may be a CSRF attack and reject the request. . This method is safer than checking the Referer. The token can be generated after the user logs in and placed in the session, and then the token is taken out of the session at each request and compared with the token in the request, but this The difficulty of this method is how to add the token to the request in the form of parameters.
For GET requests, the token will be appended to the request address, so that the URL becomes http: // url? Csrftoken = tokenvalue.
For POST requests, add <input type = "hidden" name = "csrftoken" value = "tokenvalue" /> at the end of the form, so that the token is added to the request as a parameter.

 

4. Customize attributes in the HTTP header and verify

 

This method also uses a token and performs authentication. Unlike the previous method, this is not to put the token in the HTTP request as a parameter, but to put it in a custom attribute in the HTTP header. Through the XMLHttpRequest class, you can add the csrftoken HTTP header attribute to all requests of this type at once, and put the token value into it. This solves the inconvenience of adding tokens to the request in the previous method. At the same time, the address requested through XMLHttpRequest will not be recorded in the browser's address bar, and there is no need to worry that the token will be leaked to other websites through the Referer.

Published 9 original articles · praised 0 · visits 245

Guess you like

Origin blog.csdn.net/Fabri/article/details/105491930