Spring MVC Interceptor

What is an interceptor

The interceptor is SpringMvc Functions provided by the framework

It can be before or after the controller method runs ( There are other special occasions ) A specific interface for processing or processing requests

Frequently asked questions : The difference between filters and interceptors

Both filters and interceptors can add additional code before and after the controller method runs , Realization aop effect

  • Different providers

    • The filter is made of javaEE Provided
    • The interceptor is SpringMvc Provided
  • Different goals

    • The filter has a broader purpose : It can be used in all processes that request the current server resources
    • The interceptor has a single target : It can only be used in the process where the request target is the current server controller

  • Different functional strength

    • The filter is native JavaEE The function of , Weak function , Can't handle it directly Spring Contents and objects in the container
    • The interceptor is SpringMvc Framework provided , So born with Spring Containers have better compatibility , Can be operated directly Spring Objects in the container , And the interceptor has better processing of parameter return value than the filter , There are also more opportunities to run
  • Conclusion

    If the target of the request can be determined to be a controller method , Give priority to interceptors

    If the target of the request may be other static resources , Then you need to use filters

Detailed operation , See teacher Cheng's notes

Mybatis Interceptor

brief introduction :

Mybatis A function provided by the framework

In the Mapper The ability to add additional code before or after the interface method runs

Before, we set , Implement the sql Statement output to the console , It is implemented by interceptors

We can also simply do a similar demonstration

First , To successfully intercept Mybatis in mapper Running sql sentence

You need to be in Spring Set relevant codes in

step 1: Write interceptors

// Mybatis Interceptor test class 
@Slf4j
// Mybatis Annotations for interceptor configuration declaration
// You can configure to intercept multiple jdbc Objects in the
@Intercepts({@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class,Integer.class}
)})
public class MyInterceptor implements Interceptor {
// Mybatis Interceptor method
// invocation It is the goal to run ( Here is the sql sentence )
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info(" Enter the interceptor , Ready to intercept sql sentence ");
// From parameter invocation Get the to run sql Statement object BoundSql
BoundSql boundSql=((StatementHandler)invocation.getTarget())
.getBoundSql();
// from boundSql In order to get sql sentence
String sql=boundSql.getSql();
log.info(" The original to run sql Statement for :{}",sql);
// Next, you can sql Statement changes
sql=sql+" and 1=1";
log.info(" After the change sql sentence :{}",sql);
// Forced assignment with reflection , take boundSql Medium sql Property changes
reflectUpdateSql(boundSql,"sql",sql); return invocation.proceed();
} // You need to define a method , To be able to sql Statement to rewrite
// however sql The statement is already in invocation We need to use reflection , Rewrite the attributes
private void reflectUpdateSql(BoundSql boundSql,
String attrName,String attrValue)
throws NoSuchFieldException, IllegalAccessException {
// The goal of this method is to boundSql Object's sql Forced assignment assignment
// Attribute class of reflection
Field field=boundSql.getClass().getDeclaredField(attrName);
// Setting properties forces assignment After setting, it is not a private property
field.setAccessible(true);
// Assign the prepared value to this attribute
field.set(boundSql,attrValue);
}
// User class User Class has a private attribute password No, getset Method
// Reflection can be forced to password Property assignment
// BoundSql amount to User object
// attrName amount to password attribute
// attrValue Equivalent to the value of the attribute we want to force payment }

step 2:

Set the Interceptor at SpringBoot Make it effective under the framework

config In bag

// This class is configuration Mybatis Interceptor effective configuration class 
@Configuration
// To configure Mybatis Fixed code for interceptors to take effect
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class InterceptorConfig {
// get Mybatis Session manager for
// Mybatis Session manager is the core class that performs connection operations to the database
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList; // The following method is to Mybatis All connections in the session manager are associated with the interceptors we wrote , Make the interceptor work
@PostConstruct
public void addInterceptors(){
// Instantiate the interceptor we wrote
Interceptor interceptor=new MyInterceptor();
for (SqlSessionFactory factory:sqlSessionFactoryList){
factory.getConfiguration().addInterceptor(interceptor);
}
}
}

5-21 Interceptor Interceptor More articles about

  1. struts2 Learning notes -- Interceptor (Interceptor) And login authority verification Demo

    understand Interceptor Interceptors are similar to the filters we've learned , Yes, you can. action Code executed before and after execution . We do web Development is a technology that is often used , Such as permission control , journal . We can also put multiple interceptor together ...

  2. struts2 Interceptor interceptor Three ways to configure

    1.struts2 Interceptor interceptor Three ways to configure Method 1. Common collocation method <struts> <package name="struts2" extend ...

  3. SSM-SpringMVC-33:SpringMVC Middle interceptor Interceptor Explain

     ------------ I have no other , Only hand ripe , Humble as a fool , Eager to learn ------------- Interceptor Interceptor: Two way interception of processing methods , You can log it What I choose is to realize Handler ...

  4. filter (Filter) And interceptors (Interceptor)

    filter (Filter) Servlet Filter in Filter Is to implement the javax.servlet.Filter The server side program of the interface . It depends on servlet Containers , On the implementation , Based on function callbacks , It can respond to almost all requests ...

  5. twenty-five 、 filter Filter, Monitor Listener, Interceptor Interceptor The difference between

    1.Servlet: Run on the server can be generated dynamically web page .servlet From being loaded to web Server memory , End of server shutdown . General startup web It will load when the server is running servelt To load , Then initialize the work ...

  6. Flume Interceptor (interceptor) Detailed explanation

    flume Interceptor (interceptor)1.flume Interceptor introduction interceptors are simple plug-in components , Set in the source and channel Between .source Received events event, In the writing channel Before , Intercept ...

  7. struts2 Interceptor interceptor How to configure and use

    turn : struts2 Interceptor interceptor How to configure and use (2015-11-09 10:22:28) Reprint ▼ label : it 365 classification : Struts2  NormalText Code  ...

  8. Kafka producer Interceptor (interceptor)

    Producer Interceptor (interceptor) It's quite a new feature , It and consumer End interceptor Is in Kafka 0.10 Version was introduced , Mainly used to realize clients Customized control logic at the end . about ...

  9. Flume-NG Read the source code SourceRunner, And selector selector And interceptors interceptor Implementation

    stay AbstractConfigurationProvider Class loadSources Method will put all source To encapsulate into SourceRunner Put it in Map<String, SourceRun ...

  10. JavaWeb— Interceptor Interceptor

    1. Concept java The interceptor in is dynamic interception Action Called object , It provides a mechanism for developers to work in a Action Execute a piece of code before and after execution , You can do it in one Action Prevent its execution before execution , It also provides a way to extract A ...

Random recommendation

  1. 51nod Minimum perimeter

    1283  Minimum perimeter Title source : Codility Base time limit :1  second Space restriction :131072 KB The score is : 5  difficulty :1 Level algorithm problem   Collection   Focus on The area of a rectangle is S, It is known that the sides of the rectangle are integers , Please all ...

  2. nova-compute Deploy instance Detailed explanation - Every day 5 Minutes to play OpenStack(28)

    This section discusses nova-compute, And analyze in detail instance The whole process of deployment . I'd like to apologize first : Today's article is more than ever , I wanted to send it twice , But considering the completeness and systematicness of the article , It's just one time , This time, it's a good time ...

  3. [Liferay6.2]Liferay beginner portlet Development example

    What is? Portlet From Baidu Encyclopedia (http://baike.baidu.com/view/58961.htm) Is defined as follows : portlet Is based on java Of web Components , Handle request And generate dynamic content ...

  4. Ubuntu View in 32 still 64

    install ubuntu stay pc On , Not recommended in 32 position pc install 64 Bit operating system ,64 position pc install 32 Bit operating system Method / step   1 Press ctrl+shift+t Shortcut key , Open the terminal , Input sudo uname --m , Press down ...

  5. svn local obstruction, incoming add upon merge

    http://little418.com/2009/05/svn-local-obstruction-incoming-add-upon-merge.html If you've found this ...

  6. Talking about c# Interface issues , Suitable for novices to understand

    During this time, the project is useful to the interface , At first, I didn't particularly understand the interface , Just know that the interface definition is very simple , I even think this interface is just superfluous ( When it comes to personal development ). Now start team development , I found that the interface is so important and convenient ! Next, let's talk about my paragraph ...

  7. Json Processing of data time format

    Method : using Newtonsoft.Json; using Newtonsoft.Json.Converters;// Need to introduce Newtonsoft.Json.dll public class Co ...

  8. Fish Report a mistake Unsupported use of &#39;||&#39;. In fish, please use &#39;COMMAND; or COMMAND&#39;.

    In use fish Activate virualenv Virtual environment , Use command : source ./venv/bin/activate Report errors ./venv/bin/activate (line 23): Unsupporte ...

  9. There are more ways than difficulties --JMeter Pressure measurement notes

    label : JMeter, Proxy interface Some time ago + The payment interface is slow , Some merchants directly reported that the order loss was serious . At this time , I received the pressure measurement overflow + The task of the payment interface .JMeter I'm not familiar with , The company has not engaged in automated testing QA, In limine team One of my classmates ...

  10. &lt;&lt; operation ,&amp;0xff as well as | The clever use of ( With POJ3523---The Morning after Halloween(UVa 1601) For example )

    << Move left , Such as a<<1 It means that you will a Shift the binary one bit to the left , Add one more 0,&0xff Means to take the last 8 Bytes , Such as a&0xff It means take a Represents the last of the binary 8 Numbers form a new binary number , ...