Äú¿ÉÒÔ¾èÖú£¬Ö§³ÖÎÒÃǵĹ«ÒæÊÂÒµ¡£

1Ôª 10Ôª 50Ôª





ÈÏÖ¤Â룺  ÑéÖ¤Âë,¿´²»Çå³þ?Çëµã»÷Ë¢ÐÂÑéÖ¤Âë ±ØÌî



  ÇóÖª ÎÄÕ ÎÄ¿â Lib ÊÓÆµ iPerson ¿Î³Ì ÈÏÖ¤ ×Éѯ ¹¤¾ß ½²×ù Model Center   Code  
»áÔ±   
   
 
     
   
 ¶©ÔÄ
  ¾èÖú
¼òµ¥Àí½âSpringMvcÄ£¿é×é¼þ
 
×÷Õߣº NealLemon
  2211  次浏览      28
 2019-11-28
 
±à¼­ÍƼö:
ÎÄÕÂÖ÷Òª½éÉÜÁËʹÓ÷Ç×ÊÔ´ÅäÖÃ(²»Ê¹ÓÃXMLÎļþ)´î½¨Ò»¸öSpringÏîÄ¿¡£²¢Ã»ÓÐ˵Ã÷SpringMVCÊÇÈçºÎ¼ÓÔØ¸÷¸ö×é¼þµÄ£¬Ï£Íû¶ÔÄúµÄѧϰÓÐËù°ïÖú¡£
±¾ÎÄÀ´×ÔÓÚ¼òÊ飬ÓÉ»ðÁú¹ûÈí¼þAlice±à¼­¡¢ÍƼö¡£

@EnableWebMvc ×¢½â

֮ǰ½éÉܹýSpringµÄģʽע½â£¬Æäʵ@EnableWebMvc¾ÍÊÇÒ»¸öģʽע½â£¬ÎÒÃÇÀ´¿´Ò»ÏÂÕâ¸ö×¢½â

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

ÎÒÃÇ¿ÉÒÔ¿´µ½Õâ¸ö×¢½âʹÓÃÁËÇý¶¯×¢½â±à³Ì,ͨ¹ýÒýÓà DelegatingWebMvcConfiguration Õâ¸öÀàÀ´ÊµÏÖ×°Å䣬µ«ÊÇÎÒÃǽøÒ»²½¿´Ò»Ï DelegatingWebMvcConfiguration Õâ¸öÀ࣬·¢ÏÖÕâ¸öÀàÖÐûÓÐÈκÎÒ»¸öBean¶¨Òå¡£

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer>
configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}

@Override
protected void configurePathMatch(PathMatchConfigurer
configurer) {
this.configurers.configurePathMatch(configurer);
}
@Override
protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
this.configurers.configureContentNegotiation(configurer);
}
......
}

Ö»ÊǼòµ¥µÄ¸²¸Ç¸¸ÀàµÄ·½·¨£¬ÄÇôÎÒÃÇÔÚ½øÈ븸Àà WebMvcConfigurationSupport ¿´Ò»Ï¡£

ÔÚ WebMvcConfigurationSupportÖÐÎÒÃÇ·¢ÏÖÁ˺ܶàĬÈϵÄ@Bean¶¨Ò壬½áºÏ֮ǰһƪÎÄÕ£¬DebuggerµÄʱºò·¢ÏÖÔÚ org.springframework.web.servlet . DispatcherServlet#getHandler ·½·¨ÖÐÓÐÁ½¸ö HandlerMapping ¾ßÌåµÄʵÏÖÀà¡£

Ò»¸öÊÇRequestMappingHandlerMapping,ÁíÒ»¸öÊÇ BeanNameUrlHandlerMapping ÕâÁ½¸öBean¶¨ÒåÎÒÃǶ¼¿ÉÒÔÔÚWebMvcConfigurationSupportÖÐÕÒµ½³õʼ»¯µÄBean¡£

/**
* Return a {@link BeanNameUrlHandlerMapping} ordered
at 2 to map URL
* paths to controller bean names.
*/
@Bean
public BeanNameUrlHandlerMapping beanNameHandle
rMapping() {
BeanNameUrlHandlerMapping mapping = new BeanNameUrlHandlerMapping();
mapping.setOrder(2);
mapping.setInterceptors(getInterceptors());
mapping.setCorsConfigurations(getCorsConfigurations());
return mapping;
}

@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping mapping = createRequest
MappingHandlerMapping();
mapping.setOrder(0);
mapping.setInterceptors(getInterceptors());
mapping.setContentNegotiationManager(mvcContent
NegotiationManager());
mapping.setCorsConfigurations(getCorsConfigurations());

PathMatchConfigurer configurer = getPathMatchConfigurer();
Boolean useSuffixPatternMatch = configurer.isUse
SuffixPatternMatch();
if (useSuffixPatternMatch != null) {
mapping.setUseSuffixPatternMatch(useSuffixPatternMatch);
}
Boolean useRegisteredSuffixPatternMatch = configurer.isUseRegisteredSuffixPatternMatch();
if (useRegisteredSuffixPatternMatch != null) {
mapping.setUseRegisteredSuffixPatternMatch
(useRegisteredSuffixPatternMatch);
}
Boolean useTrailingSlashMatch = configurer.
isUseTrailingSlashMatch();
if (useTrailingSlashMatch != null) {
mapping.setUseTrailingSlashMatch(useTrailingSlashMatch);
}
UrlPathHelper pathHelper = configurer.getUrlPathHelper();
if (pathHelper != null) {
mapping.setUrlPathHelper(pathHelper);
}
PathMatcher pathMatcher = configurer.getPathMatcher();
if (pathMatcher != null) {
mapping.setPathMatcher(pathMatcher);
}
return mapping;
}

ͬÀí£¬ÊµÏÖĬÈϵÄHandlerAdapter½Ó¿ÚµÄÀàÒ²ÊÇÔÚÕâÀﶨÒåµÄ¡£ÕâÀï¾Í²»¶à×ö²ûÊö£¬¸ÐÐËȤµÄС»ï°é¿ÉÒÔ×Ô¼ºÈ¥¿´Ò»ÏÂÔ´Âë¡£

ÆäʵSpringMvcĬÈϵÄ×é¼þ¼ÓÔØ¾ÍÊÇÔÚ@EnableWebMvcÕâ¸ö×¢½â±ê×¢ÔÚij¸ö@Configuration ÀàÉÏʱ£¬Í¨¹ý DelegatingWebMvcConfiguration Õâ¸öÀàÀ´¼ÓÔØµÄ£¬È»ºóÔÚServletÖÐ×é×°

×¢Èë×é¼þ

Á˽âÁËÈçºÎ¼ÓÔØ£¬ÄÇôÕâЩ×é¼þÊǺÎʱעÈëµÄÄØ? ÆäʵÊÇÔÚË¢ÐÂÉÏÏÂÎijɹ¦ºó×¢ÈëµÄ¡£

¾ßÌå·½·¨Á÷³ÌÊÇ

@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}

/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}

ÆäʵעÈëµÄ·½Ê½¶¼ÊÇÒ»ÑùµÄ£¬ÎÒÃǾʹò¿ªÆäÖÐÒ»¸ö×¢Èë·½·¨¿´Ò»ÏÂϸ½Ú #initHandlerMappings()

/**
* Initialize the HandlerMappings used by this class.
* <p>If no HandlerMapping beans are defined in the
BeanFactory for this namespace,
* we default to BeanNameUrlHandlerMapping.
*/
private void initHandlerMappings(ApplicationContext
context) { this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext,
including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.
values()); // We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING
_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by
registering // a default HandlerMapping if no
other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}

ÔÚÕâÀï×îÖ÷ÒªµÄ¾ÍÊÇ

Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);

ÕâÒ»¶Î´úÂ룬Õâ¶Î´úÂë¾ÍÊÇͨ¹ýÓ¦ÓÃÉÏÏÂÎÄÕÒµ½ËùÓÐʵÏÖ HandlerMapping½Ó¿ÚµÄBean²¢×°Ôص½DispatcherServletÖС£

×Ô¶¨Òå×é¼þ-- WebMvcConfigurer

ÔÚÉÏÃæµÄDelegatingWebMvcConfigurationÕâ¸öÀàÖÐÎÒÃÇ·¢ÏÖÓÐÒ»¸ö·½·¨ÄǾÍÊÇ

@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer>
configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}

Õâ¸ö·½·¨¾ÍÊǼÓÔØ×Ô¶¨ÒåÅäÖÃ×é¼þµÄÀà·½·¨¡£´ÓÕâ¸ö·½·¨µÄ²ÎÊýÖÐÎÒÃÇ¿ÉÒÔ¿´³ö£¬ËùÓеÄ×Ô¶¨Òå×é¼þ±ØÐëʵÏÖorg .springframework .web .servlet.config .annotation .WebMvcConfigurer½Ó¿Ú¡£

ÏÂÃæÀ´ÈÃÎÒÃÇʵÏÖÒ»¸ö¼òµ¥µÄ×Ô¶¨Òå×é¼þ¡£ÈÃÎÒÃÇÌí¼ÓÒ»¸öÔÚÖ´ÐÐHandlerAdapter ·½·¨Ö®Ç°µÄÀ¹½ØÆ÷¡£

¼òµ¥µÄ´úÂëÈçÏ£¬¸Ã´úÂëÊÇÔÚÉÏһƪµÄÅäÖÃÀàµÄÐÂÔöµÄ¡£

/**
* Spring Mvc ÅäÖÃ
*/
@Configuration //ÅäÖÃ
@EnableWebMvc //¼¤»î×é¼þ²¢×Ô¶¯×°Åä
@ComponentScan(basePackages = "com.web")
public class WebMvcConfig implements WebMvcConfigurer {

/**
* <bean id="viewResolver" class="org.springframework.web.servlet.view.Internal
ResourceViewResolver">
* <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
* <property name="prefix" value="/WEB-INF/jsp/"/>
* <property name="suffix" value=".jsp"/>
* </bean>
* @return
*/
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}

//Ôö¼Ó×Ô¶¨ÒåÀ¹½ØÆ÷
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws
Exception System.out.println("---------×Ô¶¨ÒåÀ¹½ØÆ÷À¹½Ø
-------");
return true;
}
});
}
}

ͬʱÎÒÃǸÄÒ»ÏÂcontroller´úÂë¡£

@Controller
public class HelloWorldController {
@RequestMapping("/index")
public String index() {
System.out.println("Ö´ÐÐHelloWorldControllerÖеÄindex()·½·¨");
return "index";
}
}

×Ô¶¨ÒåÍê³ÉÖ®ºó½ÓÏÂÀ´Ö»ÐèÒªÅÜһϳÌÐò£¬¾Í¿ÉÒÔ¿´µ½×Ô¶¨ÒåµÄ×é¼þÊÇ·ñ¼ÓÔØµ½ÁËÈÝÆ÷Ö®ÖУ¬²¢³É¹¦À¹½Ø¡£

ÎÒÃÇÒѾ­¼òµ¥µÄʵÏÖÁËÒ»¸ö×Ô¶¨Òå×é¼þ,ÎÒÃÇ¿ÉÒÔͨ¹ý¸ù¾ÝÒµÎñÐèÒª¸²¸ÇWebMvcConfigurer½Ó¿ÚÖеÄĬÈÏ·½·¨À´·á¸»ÎÒÃǵÄÏîÄ¿¡£

 

 
   
2211 ´Îä¯ÀÀ       28
Ïà¹ØÎÄÕÂ

Java΢·þÎñÐÂÉú´úÖ®Nacos
ÉîÈëÀí½âJavaÖеÄÈÝÆ÷
JavaÈÝÆ÷Ïê½â
Java´úÂëÖÊÁ¿¼ì²é¹¤¾ß¼°Ê¹Óð¸Àý
Ïà¹ØÎĵµ

JavaÐÔÄÜÓÅ»¯
Spring¿ò¼Ü
SSM¿ò¼Ü¼òµ¥¼òÉÜ
´ÓÁ㿪ʼѧjava±à³Ì¾­µä
Ïà¹Ø¿Î³Ì

¸ßÐÔÄÜJava±à³ÌÓëϵͳÐÔÄÜÓÅ»¯
JavaEE¼Ü¹¹¡¢ Éè¼ÆÄ£Ê½¼°ÐÔÄܵ÷ÓÅ
Java±à³Ì»ù´¡µ½Ó¦Óÿª·¢
JAVAÐéÄâ»úÔ­ÀíÆÊÎö