├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── alibaba │ └── spring │ └── web │ ├── context │ └── ExclusiveViewResolverApplicationListener.java │ ├── method │ ├── HandlerMethodAnnotationResolver.java │ ├── HandlerMethodRepository.java │ └── HandlerMethodResolver.java │ ├── servlet │ ├── config │ │ └── annotation │ │ │ └── ConfigurableContentNegotiationManagerWebMvcConfigurer.java │ ├── handler │ │ ├── AbstractPageRenderContextHandlerInterceptor.java │ │ └── AnnotatedHandlerMethodHandlerInterceptorAdapter.java │ └── mvc │ │ └── util │ │ └── WebMvcUtils.java │ └── util │ ├── HandlerMethodUtils.java │ └── WebUtils.java └── test └── java └── com └── alibaba └── spring └── web ├── TestWebMvcConfigurer.java ├── context └── ExclusiveViewResolverApplicationListenerTest.java ├── method ├── HandlerMethodAnnotationResolverTest.java ├── HandlerMethodRepositoryTest.java └── HandlerMethodResolverTest.java ├── servlet ├── config │ └── annotation │ │ └── ConfigurableContentNegotiationManagerWebMvcConfigurerTest.java ├── handler │ ├── AbstractPageRenderContextHandlerInterceptorTest.java │ └── AnnotatedHandlerMethodHandlerInterceptorAdapterTest.java └── mvc │ ├── controller │ └── TestController.java │ └── util │ └── WebMvcUtilsTest.java └── util ├── HandlerMethodUtilsTest.java └── WebUtilsTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 4 | 5 | *.iml 6 | 7 | ## Directory-based project format: 8 | .idea/ 9 | # if you remove the above rule, at least ignore the following: 10 | 11 | # User-specific stuff: 12 | # .idea/workspace.xml 13 | # .idea/tasks.xml 14 | # .idea/dictionaries 15 | 16 | # Sensitive or high-churn files: 17 | # .idea/dataSources.ids 18 | # .idea/dataSources.xml 19 | # .idea/sqlDataSources.xml 20 | # .idea/dynamic.xml 21 | # .idea/uiDesigner.xml 22 | 23 | # Gradle: 24 | # .idea/gradle.xml 25 | # .idea/libraries 26 | 27 | # Mongo Explorer plugin: 28 | # .idea/mongoSettings.xml 29 | 30 | ## File-based project format: 31 | *.ipr 32 | *.iws 33 | 34 | ## Plugin-specific files: 35 | 36 | # IntelliJ 37 | /out/ 38 | 39 | # mpeltonen/sbt-idea plugin 40 | .idea_modules/ 41 | 42 | # JIRA plugin 43 | atlassian-ide-plugin.xml 44 | 45 | # Crashlytics plugin (for Android Studio and IntelliJ) 46 | com_crashlytics_export_strings.xml 47 | crashlytics.properties 48 | crashlytics-build.properties 49 | 50 | 51 | ### Java template 52 | *.class 53 | 54 | # Mobile Tools for Java (J2ME) 55 | .mtj.tmp/ 56 | 57 | # Package Files # 58 | *.jar 59 | *.war 60 | *.ear 61 | 62 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 63 | hs_err_pid* 64 | 65 | #Eclipse files 66 | .classpath 67 | .project 68 | .settings/ 69 | target 70 | 71 | *.iml -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | before_install: 5 | - pip install --user codecov 6 | after_success: 7 | - codecov 8 | branches: 9 | except: 10 | - appveyor -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-webmvc-support 2 | 3 | An support project of Spring Web MVC 4 | 5 | 6 | 7 | ## Dependencies & Compatibility 8 | 9 | | Dependencies | Compatibility | 10 | | -------------- | ------------- | 11 | | Java | 1.6 + | 12 | | Servlet | 2.5 + | 13 | | Spring Web MVC | 3.2 + | 14 | | [Alibaba Spring Context Support](https://github.com/alibaba/spring-context-support) | 1.0.0 + | 15 | 16 | 17 | 18 | ## Downstream Projects 19 | 20 | * [Alibaba Spring Context Support](https://github.com/alibaba/spring-context-support) 21 | 22 | 23 | 24 | 25 | ## Release version 26 | 27 | ````xml 28 | 29 | 30 | ...... 31 | 32 | 33 | 34 | org.springframework 35 | spring-webmvc 36 | ${spring.framework.version} 37 | 38 | 39 | 40 | 41 | com.alibaba.spring 42 | spring-webmvc-support 43 | 1.0.0.RELEASE 44 | 45 | 46 | ...... 47 | 48 | 49 | ```` 50 | 51 | 52 | 53 | If your project failed to resolve the dependency, try to add the following repository: 54 | ```xml 55 | 56 | 57 | sonatype-nexus 58 | https://oss.sonatype.org/content/repositories/releases 59 | 60 | true 61 | 62 | 63 | 64 | ``` -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | org.sonatype.oss 9 | oss-parent 10 | 7 11 | 12 | 13 | com.alibaba.spring 14 | spring-webmvc-support 15 | ${revision} 16 | 17 | 18 | 1.0.0.RELEASE 19 | 1.6 20 | 1.6 21 | 22 | 3.1.0 23 | 24 | 4.3.17.RELEASE 25 | 26 | 27 | git@github.com:alibaba/spring-webmvc-support.git 28 | git@github.com:alibaba/spring-webmvc-support.git 29 | https://github.com/alibaba/spring-webmvc-support 30 | 31 | 32 | 33 | 34 | 35 | mercyblitz 36 | Mercy Ma 37 | mercyblitz@gmail.com 38 | https://github.com/mercyblitz/ 39 | 40 | Developer 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | javax.servlet 52 | javax.servlet-api 53 | ${servlet-api.version} 54 | provided 55 | true 56 | 57 | 58 | 59 | 60 | org.springframework 61 | spring-context-support 62 | ${spring.framework.version} 63 | true 64 | 65 | 66 | 67 | org.springframework 68 | spring-web 69 | ${spring.framework.version} 70 | true 71 | 72 | 73 | 74 | org.springframework 75 | spring-webmvc 76 | ${spring.framework.version} 77 | true 78 | 79 | 80 | 81 | 82 | com.alibaba.spring 83 | spring-context-support 84 | 1.0.0.RELEASE 85 | 86 | 87 | 88 | 89 | junit 90 | junit 91 | 4.12 92 | test 93 | 94 | 95 | 96 | org.springframework 97 | spring-test 98 | ${spring.framework.version} 99 | test 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | release 108 | 109 | 110 | 111 | org.apache.maven.plugins 112 | maven-javadoc-plugin 113 | 114 | 115 | package 116 | 117 | jar 118 | 119 | 120 | 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-gpg-plugin 125 | 126 | 127 | verify 128 | 129 | sign 130 | 131 | 132 | 133 | 134 | 135 | 136 | org.apache.maven.plugins 137 | maven-source-plugin 138 | 139 | 140 | attach-sources 141 | 142 | jar-no-fork 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/context/ExclusiveViewResolverApplicationListener.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.context; 2 | 3 | import org.springframework.beans.factory.BeanFactoryUtils; 4 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ApplicationListener; 7 | import org.springframework.context.event.ContextRefreshedEvent; 8 | import org.springframework.web.servlet.ViewResolver; 9 | import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; 10 | 11 | import java.util.Arrays; 12 | import java.util.Map; 13 | 14 | /** 15 | * Exclusive {@link ViewResolver} {@link ApplicationListener} on {@link ContextRefreshedEvent} 16 | * 17 | * @author Mercy 18 | * @see ViewResolver 19 | * @see ApplicationListener 20 | * @see ContextRefreshedEvent 21 | * @since 2017.03.23 22 | */ 23 | public class ExclusiveViewResolverApplicationListener implements ApplicationListener { 24 | 25 | private static final Class VIEW_RESOLVER_CLASS = ViewResolver.class; 26 | 27 | private final String exclusiveViewResolverBeanName; 28 | 29 | public ExclusiveViewResolverApplicationListener(String exclusiveViewResolverBeanName) { 30 | this.exclusiveViewResolverBeanName = exclusiveViewResolverBeanName; 31 | } 32 | 33 | @Override 34 | public void onApplicationEvent(ContextRefreshedEvent event) { 35 | 36 | ApplicationContext applicationContext = event.getApplicationContext(); 37 | 38 | configureExclusiveViewResolver(applicationContext); 39 | 40 | 41 | } 42 | 43 | /** 44 | * Configure exclusive {@link ViewResolver} 45 | * 46 | * @param applicationContext {@link ApplicationContext} 47 | */ 48 | private void configureExclusiveViewResolver(ApplicationContext applicationContext) { 49 | 50 | Map viewResolversMap = 51 | BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, VIEW_RESOLVER_CLASS); 52 | 53 | int size = viewResolversMap.size(); 54 | 55 | if (size < 2) { 56 | return; 57 | } 58 | 59 | ViewResolver exclusiveViewResolver = viewResolversMap.get(exclusiveViewResolverBeanName); 60 | 61 | if (exclusiveViewResolver == null) { 62 | 63 | throw new NoSuchBeanDefinitionException(VIEW_RESOLVER_CLASS, exclusiveViewResolverBeanName); 64 | 65 | } 66 | 67 | ContentNegotiatingViewResolver contentNegotiatingViewResolver = 68 | applicationContext.getBean(ContentNegotiatingViewResolver.class); 69 | 70 | contentNegotiatingViewResolver.setViewResolvers(Arrays.asList(exclusiveViewResolver)); 71 | 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/method/HandlerMethodAnnotationResolver.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import org.springframework.core.annotation.AnnotationUtils; 4 | import org.springframework.stereotype.Repository; 5 | import org.springframework.web.method.HandlerMethod; 6 | 7 | import java.lang.annotation.Annotation; 8 | import java.lang.reflect.Method; 9 | import java.util.Collection; 10 | import java.util.Collections; 11 | import java.util.LinkedHashMap; 12 | import java.util.Map; 13 | 14 | /** 15 | * {@link HandlerMethod} {@link Annotation} Resolver 16 | * 17 | * @author Mercy 18 | * @see HandlerMethod 19 | * @see Annotation 20 | * @see Repository 21 | * @since 2017.02.02 22 | */ 23 | public class HandlerMethodAnnotationResolver { 24 | 25 | private final Collection handlerMethods; 26 | 27 | public HandlerMethodAnnotationResolver(Collection handlerMethods) { 28 | this.handlerMethods = handlerMethods; 29 | } 30 | 31 | /** 32 | * Resolve {@link Method} and {@link Annotation} {@link Map} by specified {@link Annotation} type. 33 | * 34 | * @param annotationType {@link Annotation} {@link Class} 35 | * @param {@link Annotation} Type 36 | * @return non-null {@link Collections#unmodifiableMap(Map) unmodifiable map} 37 | */ 38 | public Map resolve(Class annotationType) { 39 | 40 | Map resolvedHandlerMethods = new LinkedHashMap(); 41 | 42 | for (HandlerMethod handlerMethod : handlerMethods) { 43 | 44 | A annotation = handlerMethod.getMethodAnnotation(annotationType); 45 | 46 | if (annotation == null) { 47 | 48 | annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), annotationType); 49 | 50 | } 51 | 52 | if (annotation != null) { 53 | 54 | resolvedHandlerMethods.put(handlerMethod.getMethod(), annotation); 55 | 56 | } 57 | 58 | } 59 | 60 | return Collections.unmodifiableMap(resolvedHandlerMethods); 61 | 62 | } 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/method/HandlerMethodRepository.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import com.alibaba.spring.beans.factory.config.GenericBeanPostProcessorAdapter; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Repository; 6 | import org.springframework.web.method.HandlerMethod; 7 | import org.springframework.web.servlet.HandlerInterceptor; 8 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 9 | 10 | import javax.annotation.PostConstruct; 11 | import java.util.Collection; 12 | import java.util.Collections; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | /** 17 | * {@link HandlerMethod} {@link Repository} 18 | * 19 | * @author Mercy 20 | * @see HandlerMethod 21 | * @see Repository 22 | * @see GenericBeanPostProcessorAdapter 23 | * @since 2017.02.01 24 | */ 25 | @Repository 26 | public class HandlerMethodRepository { 27 | 28 | private Map handlerMethodsCache = Collections.emptyMap(); 29 | 30 | @Autowired(required = false) 31 | private RequestMappingHandlerMapping requestMappingHandlerMapping; 32 | 33 | @PostConstruct 34 | public void init() { 35 | 36 | if (requestMappingHandlerMapping != null) { 37 | 38 | Collection handlerMethods = requestMappingHandlerMapping.getHandlerMethods().values(); 39 | 40 | Map handlerMethodsMap = new HashMap(handlerMethods.size()); 41 | 42 | for (HandlerMethod handlerMethod : handlerMethods) { 43 | 44 | handlerMethodsMap.put(handlerMethod, handlerMethod); 45 | 46 | } 47 | 48 | handlerMethodsCache = Collections.unmodifiableMap(handlerMethodsMap); 49 | 50 | } 51 | 52 | } 53 | 54 | /** 55 | * Get All {@link HandlerMethod}s 56 | * 57 | * @return The {@link Collections#unmodifiableCollection(Collection) unmodifiable collection} of 58 | * {@link HandlerMethod} 59 | */ 60 | public Collection getHandlerMethods() { 61 | return handlerMethodsCache.values(); 62 | } 63 | 64 | /** 65 | * Get {@link HandlerMethod} by handler object 66 | * 67 | * @param handler handler object from {@link HandlerInterceptor} method's parameter 68 | * @return {@link HandlerMethod} if found. 69 | */ 70 | public HandlerMethod get(Object handler) { 71 | return handlerMethodsCache.get(handler); 72 | } 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/method/HandlerMethodResolver.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import com.alibaba.spring.web.servlet.mvc.util.WebMvcUtils; 4 | import org.springframework.web.context.WebApplicationContext; 5 | import org.springframework.web.method.HandlerMethod; 6 | import org.springframework.web.servlet.HandlerExecutionChain; 7 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 8 | 9 | import javax.servlet.ServletContext; 10 | import javax.servlet.http.HttpServletRequest; 11 | import java.util.Collection; 12 | import java.util.Collections; 13 | import java.util.LinkedList; 14 | 15 | import static com.alibaba.spring.web.servlet.mvc.util.WebMvcUtils.getRequestMappingHandlerMapping; 16 | import static com.alibaba.spring.web.util.WebUtils.getServletContext; 17 | 18 | /** 19 | * {@link HandlerMethod} Resolver 20 | * 21 | * @author Mercy 22 | * @see HandlerMethod 23 | * @since 2017.02.02 24 | */ 25 | public class HandlerMethodResolver { 26 | 27 | /** 28 | * {@link HandlerMethod}s {@link ServletContext} attribute name 29 | */ 30 | private static final String HANDLER_METHOD_ATTRIBUTE_NAME = HandlerMethod.class.getName(); 31 | 32 | /** 33 | * Resolve {@link HandlerMethod}s from {@link ServletContext} 34 | * 35 | * @param request {@link HttpServletRequest} 36 | * @param servletContext {@link ServletContext} 37 | * @return non-null {@link Collections#unmodifiableCollection(Collection) unmodifiable collection} 38 | * @throws IllegalStateException if the root WebApplicationContext could not be found 39 | */ 40 | public Collection resolveHandlerMethods(HttpServletRequest request, ServletContext servletContext) throws IllegalStateException { 41 | 42 | WebApplicationContext webApplicationContext = WebMvcUtils.getWebApplicationContext(request, servletContext); 43 | 44 | Collection requestMappingHandlerMappings = 45 | webApplicationContext.getBeansOfType(RequestMappingHandlerMapping.class).values(); 46 | 47 | Collection handlerMethods = new LinkedList(); 48 | 49 | for (RequestMappingHandlerMapping requestMappingHandlerMapping : requestMappingHandlerMappings) { 50 | 51 | handlerMethods.addAll(requestMappingHandlerMapping.getHandlerMethods().values()); 52 | 53 | } 54 | 55 | return Collections.unmodifiableCollection(handlerMethods); 56 | 57 | } 58 | 59 | /** 60 | * Resolve {@link HandlerMethod}s from {@link ServletContext} 61 | * 62 | * @param request {@link HttpServletRequest} 63 | * @return non-null {@link Collections#unmodifiableCollection(Collection) unmodifiable collection} 64 | * @throws IllegalStateException if the root WebApplicationContext could not be found 65 | */ 66 | public Collection resolveHandlerMethods(HttpServletRequest request) throws IllegalStateException { 67 | 68 | return resolveHandlerMethods(request, getServletContext(request)); 69 | 70 | } 71 | 72 | /** 73 | * Resolve {@link HandlerMethod} from {@link ServletContext} 74 | * 75 | * @param request {@link HttpServletRequest} 76 | * @param servletContext {@link ServletContext} 77 | * @return {@link HandlerMethod} 78 | * @throws IllegalStateException if the root WebApplicationContext could not be found 79 | */ 80 | public HandlerMethod resolveHandlerMethod(HttpServletRequest request, ServletContext servletContext) throws IllegalStateException { 81 | 82 | HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute(HANDLER_METHOD_ATTRIBUTE_NAME); 83 | 84 | if (handlerMethod == null) { 85 | 86 | RequestMappingHandlerMapping handlerMapping = getRequestMappingHandlerMapping(request, servletContext); 87 | 88 | try { 89 | 90 | HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request); 91 | 92 | Object handler = handlerExecutionChain == null ? null : handlerExecutionChain.getHandler(); 93 | 94 | if (handler instanceof HandlerMethod) { 95 | 96 | handlerMethod = (HandlerMethod) handler; 97 | 98 | request.setAttribute(HANDLER_METHOD_ATTRIBUTE_NAME, handlerMethod); 99 | 100 | } 101 | 102 | 103 | } catch (Exception e) { 104 | 105 | throw new IllegalStateException(e); 106 | 107 | } 108 | 109 | } 110 | 111 | return handlerMethod; 112 | 113 | } 114 | 115 | /** 116 | * Resolve {@link HandlerMethod} from {@link ServletContext} 117 | * 118 | * @param request {@link HttpServletRequest} 119 | * @return {@link HandlerMethod} 120 | * @throws IllegalStateException if the root WebApplicationContext could not be found 121 | */ 122 | public HandlerMethod resolveHandlerMethod(HttpServletRequest request) throws IllegalStateException { 123 | 124 | return resolveHandlerMethod(request, getServletContext(request)); 125 | 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/servlet/config/annotation/ConfigurableContentNegotiationManagerWebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.config.annotation; 2 | 3 | import org.springframework.beans.MutablePropertyValues; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.util.ReflectionUtils; 6 | import org.springframework.validation.DataBinder; 7 | import org.springframework.web.accept.ContentNegotiationManager; 8 | import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; 9 | import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 12 | 13 | import java.beans.PropertyEditorSupport; 14 | import java.lang.reflect.Field; 15 | import java.util.LinkedHashMap; 16 | import java.util.Map; 17 | 18 | 19 | /** 20 | * Configurable {@link ContentNegotiationManager} {@link WebMvcConfigurer} 21 | * 22 | * @author Mercy 23 | * @see ContentNegotiationManager 24 | * @see WebMvcConfigurer 25 | * @since 2017.03.23 26 | */ 27 | public class ConfigurableContentNegotiationManagerWebMvcConfigurer extends WebMvcConfigurerAdapter { 28 | 29 | /** 30 | * Property separator : "." 31 | */ 32 | private static final String PROPERTY_SEPARATOR = "."; 33 | 34 | private static final Class FACTORY_BEAN_FIELD_CLASS = 35 | ContentNegotiationManagerFactoryBean.class; 36 | 37 | private final Map propertyValues; 38 | 39 | public ConfigurableContentNegotiationManagerWebMvcConfigurer(Map properties) { 40 | this.propertyValues = resolveNestedMap(properties); 41 | } 42 | 43 | public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { 44 | 45 | ReflectionUtils.doWithFields(configurer.getClass(), new ReflectionUtils.FieldCallback() { 46 | @Override 47 | public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { 48 | 49 | boolean accessible = field.isAccessible(); 50 | 51 | try { 52 | 53 | if (!accessible) { 54 | field.setAccessible(true); 55 | } 56 | 57 | ContentNegotiationManagerFactoryBean factoryBean = (ContentNegotiationManagerFactoryBean) field.get(configurer); 58 | 59 | configureContentNegotiationManagerFactoryBean(factoryBean); 60 | 61 | } finally { 62 | 63 | if (!accessible) { 64 | field.setAccessible(accessible); 65 | } 66 | 67 | } 68 | 69 | } 70 | }, new ReflectionUtils.FieldFilter() { 71 | @Override 72 | public boolean matches(Field field) { 73 | Class fieldType = field.getType(); 74 | return FACTORY_BEAN_FIELD_CLASS.isAssignableFrom(fieldType); 75 | } 76 | }); 77 | 78 | } 79 | 80 | 81 | protected void configureContentNegotiationManagerFactoryBean(ContentNegotiationManagerFactoryBean factoryBean) { 82 | 83 | DataBinder dataBinder = new DataBinder(factoryBean); 84 | 85 | dataBinder.setDisallowedFields("contentNegotiationManager", "servletContext"); 86 | 87 | dataBinder.setAutoGrowNestedPaths(true); 88 | 89 | dataBinder.registerCustomEditor(MediaType.class, "defaultContentType", new MediaTypePropertyEditor()); 90 | 91 | MutablePropertyValues propertyValues = new MutablePropertyValues(); 92 | 93 | propertyValues.addPropertyValues(this.propertyValues); 94 | 95 | dataBinder.bind(propertyValues); 96 | 97 | } 98 | 99 | 100 | private static class MediaTypePropertyEditor extends PropertyEditorSupport { 101 | 102 | @Override 103 | public void setAsText(String text) { 104 | 105 | MediaType mediaType = MediaType.valueOf(text); 106 | 107 | setValue(mediaType); 108 | 109 | } 110 | } 111 | 112 | private static Map extraProperties(Map map) { 113 | 114 | Map properties = new LinkedHashMap(); 115 | 116 | if (map != null) { 117 | 118 | for (Map.Entry entry : map.entrySet()) { 119 | 120 | String key = entry.getKey(); 121 | 122 | Object value = entry.getValue(); 123 | 124 | if (value instanceof Map) { 125 | Map subProperties = extraProperties((Map) value); 126 | for (Map.Entry e : subProperties.entrySet()) { 127 | String subKey = e.getKey(); 128 | String subValue = e.getValue(); 129 | properties.put(key + PROPERTY_SEPARATOR + subKey, subValue); 130 | } 131 | } else if (value instanceof String) { 132 | 133 | properties.put(key, value.toString()); 134 | 135 | } 136 | 137 | } 138 | 139 | } 140 | 141 | return properties; 142 | 143 | } 144 | 145 | /** 146 | * 147 | * properties.put("a.b.1", "1"); 148 | * properties.put("a.b.2", "2"); 149 | * properties.put("d.e.f.1", "1"); 150 | * properties.put("d.e.f.2", "2"); 151 | * properties.put("d.e.f.3", "3"); 152 | * 153 | * resolved result : 154 | * 155 | * {a={b={1=1, 2=2}}, d={e={f={1=1, 2=2, 3=3}}}} 156 | * 157 | * 158 | * @param properties Properties 159 | * @return Resolved properties 160 | */ 161 | public static Map resolveNestedMap(Map properties) { 162 | 163 | Map nestedMap = new LinkedHashMap(); 164 | 165 | for (Map.Entry entry : properties.entrySet()) { 166 | 167 | String propertyName = entry.getKey(); 168 | 169 | String propertyValue = entry.getValue(); 170 | 171 | int index = propertyName.indexOf(PROPERTY_SEPARATOR); 172 | 173 | if (index > 0) { 174 | 175 | String actualPropertyName = propertyName.substring(0, index); 176 | 177 | String subPropertyName = propertyName.substring(index + 1, propertyName.length()); 178 | 179 | Object actualPropertyValue = nestedMap.get(actualPropertyName); 180 | 181 | if (actualPropertyValue == null) { 182 | 183 | actualPropertyValue = new LinkedHashMap(); 184 | 185 | nestedMap.put(actualPropertyName, actualPropertyValue); 186 | 187 | } 188 | 189 | if (actualPropertyValue instanceof Map) { 190 | 191 | Map nestedProperties = (Map) actualPropertyValue; 192 | 193 | Map subProperties = extraProperties(nestedProperties); 194 | 195 | subProperties.put(subPropertyName, propertyValue); 196 | 197 | Map subNestedMap = resolveNestedMap(subProperties); 198 | 199 | nestedProperties.putAll(subNestedMap); 200 | 201 | 202 | } 203 | } else { 204 | 205 | nestedMap.put(propertyName, propertyValue); 206 | 207 | } 208 | } 209 | 210 | 211 | return nestedMap; 212 | 213 | } 214 | 215 | } 216 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/servlet/handler/AbstractPageRenderContextHandlerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.handler; 2 | 3 | import com.alibaba.spring.web.servlet.mvc.util.WebMvcUtils; 4 | import org.springframework.web.method.HandlerMethod; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | import org.springframework.web.servlet.ModelAndView; 7 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | /** 13 | * Abstract Page Render Context {@link HandlerInterceptor} 14 | * 15 | * @author Mercy 16 | * @see HandlerInterceptor 17 | * @since 2017.02.01 18 | */ 19 | public abstract class AbstractPageRenderContextHandlerInterceptor extends HandlerInterceptorAdapter { 20 | 21 | 22 | public final void postHandle( 23 | HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 24 | throws Exception { 25 | 26 | if (WebMvcUtils.isPageRenderRequest(modelAndView)) { 27 | 28 | postHandleOnPageRenderContext(request, response, handler, modelAndView); 29 | 30 | } else { 31 | 32 | super.postHandle(request, response, handler, modelAndView); 33 | 34 | } 35 | 36 | } 37 | 38 | /** 39 | * post-handle on page render context. 40 | * 41 | * @param request current HTTP request 42 | * @param response current HTTP response 43 | * @param handler handler (or {@link HandlerMethod}) that started async 44 | * execution, for type and/or instance examination 45 | * @param modelAndView the {@code ModelAndView} that the handler returned 46 | * (can also be {@code null}) 47 | * @throws Exception in case of errors 48 | * @see #postHandle(HttpServletRequest, HttpServletResponse, Object, ModelAndView) 49 | */ 50 | protected abstract void postHandleOnPageRenderContext( 51 | HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 52 | throws Exception; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/servlet/handler/AnnotatedHandlerMethodHandlerInterceptorAdapter.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.handler; 2 | 3 | import com.alibaba.spring.web.method.HandlerMethodResolver; 4 | import org.springframework.core.annotation.AnnotationUtils; 5 | import org.springframework.web.method.HandlerMethod; 6 | import org.springframework.web.servlet.HandlerInterceptor; 7 | import org.springframework.web.servlet.ModelAndView; 8 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.lang.annotation.Annotation; 13 | import java.lang.reflect.Method; 14 | import java.lang.reflect.ParameterizedType; 15 | import java.lang.reflect.Type; 16 | import java.util.Collection; 17 | import java.util.concurrent.ConcurrentHashMap; 18 | import java.util.concurrent.ConcurrentMap; 19 | 20 | /** 21 | * {@link Annotation Annotated} {@link HandlerMethod} {@link HandlerInterceptor} Adapter 22 | * 23 | * @author Mercy 24 | * @see Annotation 25 | * @see HandlerMethod 26 | * @see HandlerInterceptor 27 | * @since 2017.06.21 28 | */ 29 | public class AnnotatedHandlerMethodHandlerInterceptorAdapter extends HandlerInterceptorAdapter { 30 | 31 | private final Class annotationType; 32 | 33 | private final ConcurrentMap annotatedMethodsCache; 34 | 35 | protected AnnotatedHandlerMethodHandlerInterceptorAdapter() { 36 | 37 | annotationType = resolveAnnotationType(); 38 | 39 | annotatedMethodsCache = new ConcurrentHashMap(); 40 | 41 | } 42 | 43 | public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 44 | throws Exception { 45 | 46 | A annotation = getAnnotation(handler); 47 | 48 | if (annotation != null) { 49 | 50 | return preHandle(request, response, (HandlerMethod) handler, annotation); 51 | 52 | 53 | } else { 54 | 55 | return super.preHandle(request, response, handler); 56 | 57 | } 58 | 59 | } 60 | 61 | public final void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 62 | ModelAndView modelAndView) throws Exception { 63 | 64 | A annotation = getAnnotation(handler); 65 | 66 | if (annotation != null) { 67 | 68 | postHandle(request, response, (HandlerMethod) handler, annotation, modelAndView); 69 | 70 | } else { 71 | 72 | super.postHandle(request, response, handler, modelAndView); 73 | 74 | } 75 | 76 | } 77 | 78 | /** 79 | * This implementation is empty. 80 | */ 81 | public final void afterCompletion( 82 | HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 83 | throws Exception { 84 | 85 | A annotation = getAnnotation(handler); 86 | 87 | if (annotation != null) { 88 | 89 | afterCompletion(request, response, (HandlerMethod) handler, annotation, ex); 90 | 91 | } else { 92 | 93 | super.afterCompletion(request, response, handler, ex); 94 | 95 | } 96 | 97 | } 98 | 99 | public final void afterConcurrentHandlingStarted( 100 | HttpServletRequest request, HttpServletResponse response, Object handler) 101 | throws Exception { 102 | 103 | A annotation = getAnnotation(handler); 104 | 105 | if (annotation != null) { 106 | 107 | afterConcurrentHandlingStarted(request, response, (HandlerMethod) handler, annotation); 108 | 109 | } else { 110 | 111 | super.afterConcurrentHandlingStarted(request, response, handler); 112 | 113 | } 114 | 115 | } 116 | 117 | /** 118 | * This implementation is empty. 119 | * 120 | * @param request {@link HttpServletRequest} 121 | * @param response {@link HttpServletResponse} 122 | * @param handlerMethod Spring MVC {@link HandlerMethod} 123 | * @param annotation {@link A Annotation} instance 124 | * @return {@code true} if the execution chain should proceed with the 125 | * next interceptor or the handler itself. Else, DispatcherServlet assumes 126 | * that this interceptor has already dealt with the response itself. 127 | * @throws Exception execution {@link Exception} 128 | */ 129 | protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, 130 | HandlerMethod handlerMethod, A annotation) throws Exception { 131 | 132 | return true; 133 | 134 | } 135 | 136 | /** 137 | * This implementation is empty. 138 | * 139 | * @param request {@link HttpServletRequest} 140 | * @param response {@link HttpServletResponse} 141 | * @param handlerMethod Spring MVC {@link HandlerMethod} 142 | * @param annotation {@link A Annotation} instance 143 | * @param modelAndView Spring MVC {@link ModelAndView} 144 | * @throws Exception execution {@link Exception} 145 | */ 146 | protected void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, 147 | A annotation, ModelAndView modelAndView) throws Exception { 148 | 149 | } 150 | 151 | /** 152 | * This implementation is empty. 153 | * 154 | * @param request {@link HttpServletRequest} 155 | * @param response {@link HttpServletResponse} 156 | * @param handlerMethod Spring MVC {@link HandlerMethod} 157 | * @param annotation {@link A Annotation} instance 158 | * @param ex {@link HandlerMethod} execution {@link Exception} 159 | * @throws Exception execution {@link Exception} 160 | */ 161 | protected void afterCompletion(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, 162 | A annotation, Exception ex) throws Exception { 163 | 164 | } 165 | 166 | /** 167 | * This implementation is empty. 168 | * 169 | * @param request {@link HttpServletRequest} 170 | * @param response {@link HttpServletResponse} 171 | * @param handlerMethod Spring MVC {@link HandlerMethod} 172 | * @param annotation {@link A Annotation} instance 173 | * @throws Exception execution {@link Exception} 174 | */ 175 | protected void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, 176 | HandlerMethod handlerMethod, A annotation) throws Exception { 177 | 178 | } 179 | 180 | /** 181 | * Annotation type 182 | * 183 | * @return non-null 184 | */ 185 | public final Class getAnnotationType() { 186 | return annotationType; 187 | } 188 | 189 | private static Collection resolveHandlerMethods(HttpServletRequest request) { 190 | 191 | HandlerMethodResolver resolver = new HandlerMethodResolver(); 192 | 193 | return resolver.resolveHandlerMethods(request); 194 | 195 | } 196 | 197 | private A getAnnotation(Object handler) { 198 | 199 | A annotation = null; 200 | 201 | if (handler instanceof HandlerMethod) { 202 | 203 | HandlerMethod handlerMethod = (HandlerMethod) handler; 204 | 205 | Method method = handlerMethod.getMethod(); 206 | 207 | annotation = annotatedMethodsCache.get(method); 208 | 209 | if (annotation == null) { 210 | 211 | annotation = AnnotationUtils.findAnnotation(method, annotationType); 212 | 213 | if (annotation == null) { 214 | 215 | annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), annotationType); 216 | 217 | } 218 | 219 | if (annotation != null) { 220 | 221 | annotatedMethodsCache.putIfAbsent(method, annotation); 222 | 223 | } 224 | 225 | } 226 | 227 | } 228 | 229 | return annotation; 230 | 231 | } 232 | 233 | private final Class resolveAnnotationType() { 234 | 235 | ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); 236 | 237 | Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); 238 | 239 | return (Class) actualTypeArguments[0]; 240 | 241 | } 242 | 243 | } 244 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/servlet/mvc/util/WebMvcUtils.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.mvc.util; 2 | 3 | import com.alibaba.spring.util.BeanUtils; 4 | import com.alibaba.spring.web.util.WebUtils; 5 | import org.springframework.context.ApplicationContextInitializer; 6 | import org.springframework.context.ConfigurableApplicationContext; 7 | import org.springframework.context.i18n.LocaleContext; 8 | import org.springframework.core.annotation.AnnotationUtils; 9 | import org.springframework.util.Assert; 10 | import org.springframework.util.ClassUtils; 11 | import org.springframework.util.ObjectUtils; 12 | import org.springframework.util.StringUtils; 13 | import org.springframework.web.bind.annotation.ControllerAdvice; 14 | import org.springframework.web.context.ContextLoader; 15 | import org.springframework.web.context.WebApplicationContext; 16 | import org.springframework.web.context.request.RequestAttributes; 17 | import org.springframework.web.context.request.RequestContextHolder; 18 | import org.springframework.web.context.request.ServletRequestAttributes; 19 | import org.springframework.web.filter.RequestContextFilter; 20 | import org.springframework.web.servlet.DispatcherServlet; 21 | import org.springframework.web.servlet.FrameworkServlet; 22 | import org.springframework.web.servlet.ModelAndView; 23 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 24 | import org.springframework.web.servlet.support.RequestContextUtils; 25 | 26 | import javax.servlet.ServletContext; 27 | import javax.servlet.ServletRegistration; 28 | import javax.servlet.ServletRequest; 29 | import javax.servlet.http.HttpServletRequest; 30 | import java.lang.reflect.Method; 31 | import java.util.ArrayList; 32 | import java.util.Arrays; 33 | import java.util.Collection; 34 | import java.util.List; 35 | 36 | import static org.springframework.util.ReflectionUtils.findMethod; 37 | import static org.springframework.util.ReflectionUtils.invokeMethod; 38 | import static org.springframework.web.context.ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM; 39 | import static org.springframework.web.context.ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM; 40 | 41 | /** 42 | * Web MVC Utilities Class 43 | * 44 | * @author Mercy 45 | * @version 1.0.1 46 | * @see ServletContext 47 | * @since 1.0.0 2016-10-10 48 | */ 49 | public abstract class WebMvcUtils { 50 | 51 | /** 52 | * The name of AbstractJsonpResponseBodyAdvice class which was present in Spring Framework since 4.1 53 | */ 54 | public static final String ABSTRACT_JSONP_RESPONSE_BODY_ADVICE_CLASS_NAME = 55 | "org.springframework.web.servlet.mvc.findWebApplicationContextMethod.annotation.AbstractJsonpResponseBodyAdvice"; 56 | 57 | /** 58 | * Indicates current version of Spring Framework is 4.1 or above 59 | */ 60 | private final static boolean ABSTRACT_JSONP_RESPONSE_BODY_ADVICE_PRESENT = 61 | ClassUtils.isPresent(ABSTRACT_JSONP_RESPONSE_BODY_ADVICE_CLASS_NAME, WebMvcUtils.class.getClassLoader()); 62 | 63 | /** 64 | * {@link RequestMappingHandlerMapping} Context name 65 | */ 66 | private final static String REQUEST_MAPPING_HANDLER_MAPPING_CONTEXT_NAME = RequestMappingHandlerMapping.class.getName(); 67 | 68 | /** 69 | * Any number of these characters are considered delimiters between 70 | * multiple values in a single init-param String value. 71 | * 72 | * @see ContextLoader#INIT_PARAM_DELIMITERS 73 | */ 74 | private static final String INIT_PARAM_DELIMITERS = ",; \t\n"; 75 | 76 | /** 77 | * RequestContextUtils#findWebApplicationContext(HttpServletRequest, ServletContext) method 78 | * 79 | * @since Spring 4.2.1 80 | */ 81 | private static final Method findWebApplicationContextMethod; 82 | 83 | 84 | static { 85 | 86 | findWebApplicationContextMethod = findMethod(RequestContextUtils.class, 87 | "findWebApplicationContext", HttpServletRequest.class, ServletContext.class); 88 | 89 | } 90 | 91 | // /** 92 | // * Determine whether the handler findWebApplicationContextMethod is a response body findWebApplicationContextMethod. 93 | // * 94 | // * @param handlerMethod {@link HandlerMethod} 95 | // * @return true if the handler findWebApplicationContextMethod is a response body findWebApplicationContextMethod. 96 | // */ 97 | // public static boolean isResponseBodyMethod(HandlerMethod handlerMethod) { 98 | // MethodParameter methodParameter = handlerMethod.getReturnType(); 99 | // return methodParameter.getMethodAnnotation(ResponseBody.class) != null; 100 | // } 101 | 102 | /** 103 | * Determine whether the Bean Type is present annotated by {@link ControllerAdvice} 104 | * 105 | * @param beanType Bean Type 106 | * @return If {@link ControllerAdvice} bean type is present , return true , or false. 107 | */ 108 | public static boolean isControllerAdviceBeanType(Class beanType) { 109 | return AnnotationUtils.findAnnotation(beanType, ControllerAdvice.class) != null; 110 | } 111 | 112 | // /** 113 | // * Determine whether the handler findWebApplicationContextMethod is present annotated by {@link ControllerAdvice} 114 | // * when org.springframework.web.servlet.mvc.findWebApplicationContextMethod.annotation.ResponseBodyAdvice is present and 115 | // * can be loaded which indicates the current version of Spring Framework is 4.1 or above. 116 | // * 117 | // * @param handlerMethod {@link HandlerMethod} 118 | // * @return 119 | // */ 120 | // public static boolean isResponseBodyAdvicePresent(HandlerMethod handlerMethod) { 121 | // if (ABSTRACT_JSONP_RESPONSE_BODY_ADVICE_PRESENT) { 122 | // Class controllerType = handlerMethod.getBeanType(); 123 | // return isControllerAdviceBeanType(controllerType); 124 | // } 125 | // return false; 126 | // } 127 | 128 | /** 129 | * Current {@link HttpServletRequest Request} from {@link ThreadLocal} 130 | * 131 | * @return {@link HttpServletRequest Request} 132 | * @throws IllegalStateException If current web environment could not be in Servlet Container with Spring Web MVC 133 | * @see FrameworkServlet#initContextHolders(HttpServletRequest, LocaleContext, RequestAttributes) 134 | * @see RequestContextFilter#initContextHolders(HttpServletRequest, ServletRequestAttributes) 135 | */ 136 | public static HttpServletRequest currentRequest() throws IllegalStateException { 137 | 138 | RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 139 | 140 | if (!(requestAttributes instanceof ServletRequestAttributes)) { 141 | 142 | throw new IllegalStateException("Current web environment could not be in Servlet Container " + 143 | "with Spring Web MVC , because " + 144 | DispatcherServlet.class.getName() + 145 | " or " + 146 | RequestContextFilter.class.getName() + 147 | " never be used !"); 148 | 149 | } 150 | 151 | ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes; 152 | 153 | return servletRequestAttributes.getRequest(); 154 | 155 | } 156 | 157 | 158 | /** 159 | * Get the {@link WebApplicationContext} from {@link HttpServletRequest} 160 | * 161 | * @param request {@link HttpServletRequest} 162 | * @param servletContext {@link ServletContext} 163 | * @return {@link WebApplicationContext} 164 | * @throws IllegalStateException if no servlet-specific context has been found 165 | * @see RequestContextUtils#getWebApplicationContext(ServletRequest) 166 | * @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE 167 | */ 168 | public static WebApplicationContext getWebApplicationContext(HttpServletRequest request, ServletContext servletContext) { 169 | 170 | WebApplicationContext webApplicationContext = null; 171 | 172 | if (findWebApplicationContextMethod != null) { 173 | 174 | try { 175 | 176 | webApplicationContext = (WebApplicationContext) 177 | invokeMethod(findWebApplicationContextMethod, null, request, servletContext); 178 | 179 | } catch (IllegalStateException e) { 180 | 181 | } 182 | 183 | } 184 | 185 | if (webApplicationContext == null) { 186 | 187 | webApplicationContext = RequestContextUtils.getWebApplicationContext(request, servletContext); 188 | 189 | } 190 | 191 | return webApplicationContext; 192 | 193 | } 194 | 195 | /** 196 | * Get the {@link WebApplicationContext} from {@link HttpServletRequest} 197 | * 198 | * @param request {@link HttpServletRequest} 199 | * @return {@link WebApplicationContext} 200 | * @throws IllegalStateException if no servlet-specific context has been found 201 | * @see RequestContextUtils#getWebApplicationContext(ServletRequest) 202 | * @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE 203 | */ 204 | public static WebApplicationContext getWebApplicationContext(HttpServletRequest request) { 205 | return getWebApplicationContext(request, WebUtils.getServletContext(request)); 206 | } 207 | 208 | 209 | /** 210 | * Get Current WebApplicationContext. 211 | * 212 | * @return {@link WebApplicationContext} instance. 213 | */ 214 | public static WebApplicationContext currentWebApplicationContext() { 215 | 216 | return getWebApplicationContext(currentRequest()); 217 | 218 | } 219 | 220 | 221 | /** 222 | * {@link RequestMappingHandlerMapping} from {@link HttpServletRequest} {@link ServletContext} 223 | * 224 | * @param request {@link HttpServletRequest} 225 | * @param servletContext {@link ServletContext} 226 | * @return {@link RequestMappingHandlerMapping} 227 | */ 228 | public static RequestMappingHandlerMapping getRequestMappingHandlerMapping(HttpServletRequest request, 229 | ServletContext servletContext) { 230 | 231 | 232 | WebApplicationContext webApplicationContext = getWebApplicationContext(request, servletContext); 233 | 234 | return getRequestMappingHandlerMapping(webApplicationContext); 235 | 236 | } 237 | 238 | /** 239 | * {@link RequestMappingHandlerMapping} from {@link HttpServletRequest} {@link ServletContext} 240 | * 241 | * @param request {@link HttpServletRequest} 242 | * @return {@link RequestMappingHandlerMapping} 243 | */ 244 | public static RequestMappingHandlerMapping getRequestMappingHandlerMapping(HttpServletRequest request) { 245 | 246 | return getRequestMappingHandlerMapping(request, WebUtils.getServletContext(request)); 247 | 248 | } 249 | 250 | /** 251 | * {@link RequestMappingHandlerMapping} from {@link WebApplicationContext} 252 | * 253 | * @param webApplicationContext {@link WebApplicationContext} 254 | * @return {@link RequestMappingHandlerMapping} 255 | */ 256 | public static RequestMappingHandlerMapping getRequestMappingHandlerMapping(WebApplicationContext webApplicationContext) { 257 | 258 | RequestMappingHandlerMapping requestMappingHandlerMapping = 259 | BeanUtils.getOptionalBean(webApplicationContext, RequestMappingHandlerMapping.class); 260 | 261 | return requestMappingHandlerMapping; 262 | 263 | } 264 | 265 | 266 | /** 267 | * Get {@link ServletContext} in current {@link HttpServletRequest request} 268 | * 269 | * @return current request {@link ServletContext} 270 | * @throws IllegalStateException If current web environment could not be in Servlet Container with Spring Web MVC 271 | * @see RequestContextHolder#getRequestAttributes() 272 | * @see FrameworkServlet#initContextHolders(HttpServletRequest, LocaleContext, RequestAttributes) 273 | * @see RequestContextFilter#initContextHolders(HttpServletRequest, ServletRequestAttributes) 274 | * @see HttpServletRequest 275 | * @see ServletContext 276 | */ 277 | public static ServletContext currentServletContext() throws IllegalStateException { 278 | 279 | HttpServletRequest request = currentRequest(); 280 | 281 | ServletContext servletContext = WebUtils.getServletContext(request); 282 | 283 | return servletContext; 284 | 285 | } 286 | 287 | protected static String appendInitParameter(String existedParameterValue, String... parameterValues) { 288 | 289 | String[] existedParameterValues = StringUtils.hasLength(existedParameterValue) ? 290 | existedParameterValue.split(INIT_PARAM_DELIMITERS) : 291 | new String[0]; 292 | 293 | List parameterValuesList = new ArrayList(); 294 | 295 | if (!ObjectUtils.isEmpty(existedParameterValues)) { 296 | parameterValuesList.addAll(Arrays.asList(existedParameterValues)); 297 | } 298 | 299 | parameterValuesList.addAll(Arrays.asList(parameterValues)); 300 | 301 | String newParameterValue = StringUtils.arrayToDelimitedString(parameterValuesList.toArray(), ","); 302 | 303 | return newParameterValue; 304 | } 305 | 306 | /** 307 | * Append {@link ServletContext#setInitParameter(String, String) ServletContext Intialized Parameters} 308 | * 309 | * @param servletContext {@link ServletContext} 310 | * @param parameterName the name of init parameter 311 | * @param parameterValues the values of init parameters 312 | */ 313 | public static void appendInitParameters(ServletContext servletContext, String parameterName, String... parameterValues) { 314 | 315 | Assert.notNull(servletContext); 316 | Assert.hasLength(parameterName); 317 | Assert.notNull(parameterValues); 318 | 319 | String existedParameterValue = servletContext.getInitParameter(parameterName); 320 | 321 | String newParameterValue = appendInitParameter(existedParameterValue, parameterValues); 322 | 323 | if (StringUtils.hasLength(newParameterValue)) { 324 | servletContext.setInitParameter(parameterName, newParameterValue); 325 | } 326 | 327 | } 328 | 329 | /** 330 | * Append initialized parameter for {@link ApplicationContextInitializer Global Initializer Class} 331 | * 332 | * @param servletContext {@link ServletContext} 333 | * @param contextInitializerClass the class of {@link ApplicationContextInitializer} 334 | * @see ContextLoader#GLOBAL_INITIALIZER_CLASSES_PARAM 335 | */ 336 | public static void appendGlobalInitializerClassInitParameter(ServletContext servletContext, 337 | Class contextInitializerClass) { 338 | 339 | String contextInitializerClassName = contextInitializerClass.getName(); 340 | 341 | appendInitParameters(servletContext, GLOBAL_INITIALIZER_CLASSES_PARAM, contextInitializerClassName); 342 | 343 | } 344 | 345 | /** 346 | * Append initialized parameter for {@link ApplicationContextInitializer Context Initializer Class} 347 | * 348 | * @param servletContext {@link ServletContext} 349 | * @param contextInitializerClass the class of {@link ApplicationContextInitializer} 350 | * @see ContextLoader#CONTEXT_INITIALIZER_CLASSES_PARAM 351 | */ 352 | public static void appendContextInitializerClassInitParameter(ServletContext servletContext, 353 | Class contextInitializerClass) { 354 | 355 | String contextInitializerClassName = contextInitializerClass.getName(); 356 | 357 | appendInitParameters(servletContext, CONTEXT_INITIALIZER_CLASSES_PARAM, contextInitializerClassName); 358 | 359 | } 360 | 361 | 362 | /** 363 | * Append initialized parameter for {@link ApplicationContextInitializer Context Initializer Class} into {@link 364 | * FrameworkServlet} 365 | * 366 | * @param servletContext {@link ServletContext} 367 | * @param contextInitializerClass the class of {@link ApplicationContextInitializer} 368 | * @see FrameworkServlet#applyInitializers(ConfigurableApplicationContext) 369 | */ 370 | public static void appendFrameworkServletContextInitializerClassInitParameter( 371 | ServletContext servletContext, 372 | Class contextInitializerClass) { 373 | 374 | Collection servletRegistrations = 375 | WebUtils.findServletRegistrations(servletContext, FrameworkServlet.class).values(); 376 | 377 | for (ServletRegistration servletRegistration : servletRegistrations) { 378 | String contextInitializerClassName = servletRegistration.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); 379 | String newContextInitializerClassName = appendInitParameter(contextInitializerClassName, contextInitializerClass.getName()); 380 | servletRegistration.setInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM, newContextInitializerClassName); 381 | } 382 | 383 | } 384 | 385 | /** 386 | * Is page render request 387 | * 388 | * @param modelAndView {@link ModelAndView} 389 | * @return If current request is for page render , return true , or false. 390 | */ 391 | public static boolean isPageRenderRequest(ModelAndView modelAndView) { 392 | 393 | if (modelAndView != null) { 394 | 395 | String viewName = modelAndView.getViewName(); 396 | 397 | return StringUtils.hasText(viewName); 398 | 399 | } 400 | 401 | return false; 402 | 403 | } 404 | 405 | 406 | } 407 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/util/HandlerMethodUtils.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.util; 2 | 3 | import org.springframework.core.MethodParameter; 4 | import org.springframework.web.method.HandlerMethod; 5 | 6 | import java.lang.annotation.Annotation; 7 | import java.lang.annotation.ElementType; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * {@link HandlerMethod} Utilities 13 | * 14 | * @author Mercy 15 | * @see HandlerMethod 16 | * @since 2017.01.12 17 | */ 18 | public abstract class HandlerMethodUtils { 19 | 20 | 21 | /** 22 | * Find specified {@link Annotation} type maps from {@link HandlerMethod} 23 | * 24 | * @param handlerMethod {@link HandlerMethod} 25 | * @param annotationClass {@link Annotation} type 26 | * @param {@link Annotation} type 27 | * @return {@link Annotation} type maps , the {@link ElementType} as key , 28 | * the list of {@link Annotation} as value. 29 | * If {@link Annotation} was annotated on {@link HandlerMethod}'s parameters{@link ElementType#PARAMETER} , 30 | * the associated {@link Annotation} list may contain multiple elements. 31 | */ 32 | public static Map> findAnnotations(HandlerMethod handlerMethod, 33 | Class annotationClass) { 34 | return com.alibaba.spring.util.AnnotationUtils.findAnnotations(handlerMethod.getMethod(), annotationClass); 35 | } 36 | 37 | /** 38 | * Find {@link Annotation} from {@link MethodParameter method parameter or method return type} 39 | * 40 | * @param methodParameter {@link MethodParameter method parameter or method return type} 41 | * @param annotationClass {@link Annotation} type 42 | * @param {@link Annotation} type 43 | * @return {@link Annotation} If found , return null 44 | */ 45 | public static A findAnnotation(MethodParameter methodParameter, Class annotationClass) { 46 | 47 | A annotation = null; 48 | 49 | boolean isReturnType = methodParameter.getParameterIndex() < 0; 50 | 51 | if (isReturnType) { 52 | 53 | annotation = methodParameter.getMethodAnnotation(annotationClass); 54 | 55 | } else { // is parameter 56 | 57 | annotation = methodParameter.getParameterAnnotation(annotationClass); 58 | 59 | } 60 | 61 | 62 | return annotation; 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/spring/web/util/WebUtils.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.util; 2 | 3 | import org.springframework.util.ClassUtils; 4 | 5 | import javax.servlet.*; 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.util.Collections; 8 | import java.util.LinkedHashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Web Utilities Class 13 | * 14 | * @author Mercy 15 | * @see WebUtils 16 | * @since 1.0.1 2016-10-20 17 | */ 18 | public abstract class WebUtils { 19 | 20 | /** 21 | * Is Running in Servlet 3 or Above 22 | */ 23 | private static final boolean servlet3OrAbove; 24 | 25 | /** 26 | * javax.servlet.ServletContainerInitializer @since 3.0 27 | */ 28 | private static final String SERVLET_CONTAINER_INITIALIZER_CLASS_NAME = "javax.servlet.ServletContainerInitializer"; 29 | 30 | static { 31 | 32 | ClassLoader classLoader = WebUtils.class.getClassLoader(); 33 | 34 | servlet3OrAbove = ClassUtils.isPresent(SERVLET_CONTAINER_INITIALIZER_CLASS_NAME, classLoader); 35 | 36 | } 37 | 38 | /** 39 | * Is Running below Servlet 3 Container 40 | * 41 | * @return If below , true 42 | */ 43 | public static boolean isRunningBelowServlet3Container() { 44 | return !servlet3OrAbove; 45 | } 46 | 47 | 48 | /** 49 | * Get {@link ServletContext} from {@link HttpServletRequest} 50 | * 51 | * @param request {@link HttpServletRequest} 52 | * @return non-null 53 | */ 54 | public static ServletContext getServletContext(HttpServletRequest request) { 55 | 56 | if (isRunningBelowServlet3Container()) { // below Servlet 3.x 57 | 58 | return request.getSession().getServletContext(); 59 | 60 | } 61 | 62 | return request.getServletContext(); 63 | } 64 | 65 | /** 66 | * Find the {@link Map map} of {@link FilterRegistration} in specified {@link Filter} {@link Class} 67 | * 68 | * @param servletContext {@link ServletContext} 69 | * @param filterClass The {@link Class of class} of {@link Filter} 70 | * @return the {@link Map map} of {@link ServletRegistration} 71 | */ 72 | public static Map findFilterRegistrations( 73 | ServletContext servletContext, Class filterClass) { 74 | Map filterRegistrationsMap = servletContext.getFilterRegistrations(); 75 | return findRegistrations(servletContext, filterRegistrationsMap, filterClass); 76 | } 77 | 78 | /** 79 | * Find the {@link Map map} of {@link ServletRegistration} in specified {@link Servlet} {@link Class} 80 | * 81 | * @param servletContext {@link ServletContext} 82 | * @param servletClass The {@link Class of class} of {@link Servlet} 83 | * @return the unmodifiable {@link Map map} of {@link ServletRegistration} 84 | */ 85 | public static Map findServletRegistrations( 86 | ServletContext servletContext, Class servletClass) { 87 | Map servletRegistrationsMap = servletContext.getServletRegistrations(); 88 | return findRegistrations(servletContext, servletRegistrationsMap, servletClass); 89 | } 90 | 91 | 92 | /** 93 | * Find the {@link Map map} of {@link Registration} in specified {@link Class} 94 | * 95 | * @param servletContext {@link ServletContext} 96 | * @param registrationsMap the {@link Map map} of {@link Registration} 97 | * @param targetClass the target {@link Class} 98 | * @param the subtype of {@link Registration} 99 | * @return the unmodifiable {@link Map map} of {@link Registration} i 100 | */ 101 | protected static Map findRegistrations( 102 | ServletContext servletContext, Map registrationsMap, Class targetClass) { 103 | 104 | if (registrationsMap.isEmpty()) { 105 | return Collections.emptyMap(); 106 | } 107 | 108 | ClassLoader classLoader = servletContext.getClassLoader(); 109 | 110 | Map foundRegistrationsMap = new LinkedHashMap(); 111 | 112 | for (Map.Entry entry : registrationsMap.entrySet()) { 113 | R registration = entry.getValue(); 114 | String className = registration.getClassName(); 115 | Class registeredRegistrationClass = ClassUtils.resolveClassName(className, classLoader); 116 | if (ClassUtils.isAssignable(targetClass, registeredRegistrationClass)) { 117 | String servletName = entry.getKey(); 118 | foundRegistrationsMap.put(servletName, registration); 119 | } 120 | } 121 | 122 | return Collections.unmodifiableMap(foundRegistrationsMap); 123 | 124 | } 125 | 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/TestWebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web; 2 | 3 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 4 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 6 | import org.springframework.web.servlet.mvc.method.annotation.ServletRequestMethodArgumentResolver; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Test {@link WebMvcConfigurer} 12 | * 13 | * @author @throws Exception execution {@link Exception} 14 | * @since 1.0.0 15 | */ 16 | public class TestWebMvcConfigurer extends WebMvcConfigurerAdapter { 17 | 18 | @Override 19 | public void addArgumentResolvers(List argumentResolvers) { 20 | argumentResolvers.add(new ServletRequestMethodArgumentResolver()); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/context/ExclusiveViewResolverApplicationListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.context; 2 | 3 | import com.alibaba.spring.util.FieldUtils; 4 | import org.junit.Assert; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.springframework.beans.BeansException; 8 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 9 | import org.springframework.beans.factory.config.BeanFactoryPostProcessor; 10 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 11 | import org.springframework.context.ApplicationListener; 12 | import org.springframework.context.event.ContextRefreshedEvent; 13 | import org.springframework.mock.web.MockServletContext; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; 16 | import org.springframework.web.servlet.View; 17 | import org.springframework.web.servlet.ViewResolver; 18 | import org.springframework.web.servlet.view.BeanNameViewResolver; 19 | import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; 20 | 21 | import java.util.List; 22 | import java.util.Locale; 23 | 24 | /** 25 | * {@link ExclusiveViewResolverApplicationListener} Test 26 | * 27 | * @author Mercy 28 | * @see ExclusiveViewResolverApplicationListener 29 | * @since 2017.03.23 30 | */ 31 | public class ExclusiveViewResolverApplicationListenerTest { 32 | 33 | private AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); 34 | 35 | private ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); 36 | 37 | private MockServletContext servletContext = new MockServletContext(); 38 | 39 | private BeanNameViewResolver viewResolver = new BeanNameViewResolver(); 40 | 41 | @Before 42 | public void init() { 43 | 44 | applicationContext.setServletContext(servletContext); 45 | 46 | applicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { 47 | 48 | @Override 49 | public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { 50 | 51 | beanFactory.registerSingleton("resolver", resolver); 52 | beanFactory.registerSingleton("viewResolver", viewResolver); 53 | 54 | } 55 | 56 | }); 57 | 58 | } 59 | 60 | @Component("test-view-resolver") 61 | private static class TestViewResolver implements ViewResolver { 62 | 63 | 64 | @Override 65 | public View resolveViewName(String viewName, Locale locale) throws Exception { 66 | return null; 67 | } 68 | 69 | } 70 | 71 | @Test(expected = NoSuchBeanDefinitionException.class) 72 | public void testOnApplicationContextOnNoSuchBeanDefinitionException() { 73 | 74 | // Register ViewResolver Beans 75 | applicationContext.register(ContentNegotiatingViewResolver.class); 76 | 77 | ApplicationListener applicationListener = 78 | new ExclusiveViewResolverApplicationListener("not-existed-view-resolver"); 79 | 80 | applicationContext.addApplicationListener(applicationListener); 81 | 82 | applicationContext.refresh(); 83 | 84 | } 85 | 86 | @Test 87 | public void testOnApplicationContext() { 88 | 89 | // Register ViewResolver Beans 90 | applicationContext.register(TestViewResolver.class); 91 | 92 | ApplicationListener applicationListener = 93 | new ExclusiveViewResolverApplicationListener("test-view-resolver"); 94 | 95 | applicationContext.addApplicationListener(applicationListener); 96 | 97 | applicationContext.refresh(); 98 | 99 | List viewResolvers = FieldUtils.getFieldValue(resolver, "viewResolvers"); 100 | 101 | Assert.assertEquals(1, viewResolvers.size()); 102 | 103 | Assert.assertEquals(TestViewResolver.class, viewResolvers.get(0).getClass()); 104 | 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/method/HandlerMethodAnnotationResolverTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import com.alibaba.spring.web.servlet.mvc.controller.TestController; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.test.context.ContextConfiguration; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 12 | 13 | import java.lang.reflect.Method; 14 | import java.util.Map; 15 | 16 | /** 17 | * {@link HandlerMethodAnnotationResolver} Test 18 | * 19 | * @author Mercy 20 | * @see HandlerMethodAnnotationResolver 21 | * @since 2017.02.02 22 | */ 23 | @RunWith(SpringJUnit4ClassRunner.class) 24 | @ContextConfiguration(classes = {HandlerMethodRepository.class, TestController.class, RequestMappingHandlerMapping.class}) 25 | public class HandlerMethodAnnotationResolverTest { 26 | 27 | @Autowired 28 | private HandlerMethodRepository handlerMethodRepository; 29 | 30 | @Test 31 | public void testResolve() { 32 | 33 | HandlerMethodAnnotationResolver resolver = new HandlerMethodAnnotationResolver(handlerMethodRepository.getHandlerMethods()); 34 | 35 | Map handlerMethodsMap = resolver.resolve(RequestMapping.class); 36 | 37 | Assert.assertEquals(1, handlerMethodsMap.size()); 38 | 39 | for (Map.Entry entry : handlerMethodsMap.entrySet()) { 40 | Method handlerMethod = entry.getKey(); 41 | RequestMapping requestMapping = entry.getValue(); 42 | Assert.assertArrayEquals(new String[]{"echo"}, requestMapping.value()); 43 | Assert.assertEquals("echo", handlerMethod.getName()); 44 | } 45 | 46 | Map result = resolver.resolve(Override.class); 47 | 48 | Assert.assertTrue(result.isEmpty()); 49 | 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/method/HandlerMethodRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import com.alibaba.spring.web.servlet.mvc.controller.TestController; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.test.context.ContextConfiguration; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | import org.springframework.web.method.HandlerMethod; 11 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 12 | 13 | /** 14 | * {@link HandlerMethodRepository} Test 15 | * 16 | * @author Mercy 17 | * @see HandlerMethodRepository 18 | * @since 2017.02.02 19 | */ 20 | @RunWith(SpringJUnit4ClassRunner.class) 21 | @ContextConfiguration(classes = { 22 | HandlerMethodRepository.class, 23 | TestController.class, 24 | RequestMappingHandlerMapping.class}) 25 | public class HandlerMethodRepositoryTest { 26 | 27 | @Autowired 28 | private HandlerMethodRepository handlerMethodRepository; 29 | 30 | @Autowired 31 | private RequestMappingHandlerMapping requestMappingHandlerMapping; 32 | 33 | @Test 34 | public void testGet() { 35 | 36 | Assert.assertNotNull(handlerMethodRepository); 37 | 38 | Assert.assertEquals(1, handlerMethodRepository.getHandlerMethods().size()); 39 | 40 | for (HandlerMethod handlerMethod : handlerMethodRepository.getHandlerMethods()) { 41 | Assert.assertEquals(handlerMethod, handlerMethodRepository.get(handlerMethod)); 42 | } 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/method/HandlerMethodResolverTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.method; 2 | 3 | import com.alibaba.spring.web.TestWebMvcConfigurer; 4 | import com.alibaba.spring.web.servlet.mvc.controller.TestController; 5 | import org.junit.After; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.springframework.mock.web.MockHttpServletRequest; 10 | import org.springframework.mock.web.MockServletContext; 11 | import org.springframework.web.context.request.RequestContextHolder; 12 | import org.springframework.web.context.request.ServletRequestAttributes; 13 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; 14 | import org.springframework.web.method.HandlerMethod; 15 | import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; 16 | 17 | import java.lang.reflect.Method; 18 | import java.util.Collection; 19 | 20 | import static org.springframework.web.context.WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; 21 | import static org.springframework.web.servlet.DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE; 22 | 23 | /** 24 | * {@link HandlerMethodResolver} 25 | * 26 | * @author Mercy 27 | * @see HandlerMethodResolver 28 | * @since 2017.02.02 29 | */ 30 | public class HandlerMethodResolverTest { 31 | 32 | 33 | private HandlerMethodResolver handlerMethodResolver; 34 | 35 | private MockServletContext servletContext; 36 | 37 | private MockHttpServletRequest request; 38 | 39 | private AnnotationConfigWebApplicationContext webApplicationContext; 40 | 41 | @Before 42 | public void init() { 43 | 44 | handlerMethodResolver = new HandlerMethodResolver(); 45 | 46 | servletContext = new MockServletContext(); 47 | 48 | request = new MockHttpServletRequest(servletContext); 49 | 50 | webApplicationContext = new AnnotationConfigWebApplicationContext(); 51 | 52 | webApplicationContext.setServletContext(servletContext); 53 | 54 | request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 55 | 56 | servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 57 | 58 | webApplicationContext.register(TestController.class); 59 | webApplicationContext.register(DelegatingWebMvcConfiguration.class); 60 | webApplicationContext.register(TestWebMvcConfigurer.class); 61 | 62 | webApplicationContext.refresh(); 63 | 64 | RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request), true); 65 | } 66 | 67 | @After 68 | public void destroy() { 69 | 70 | webApplicationContext.destroy(); 71 | 72 | request.removeAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE); 73 | 74 | servletContext.removeAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 75 | 76 | RequestContextHolder.resetRequestAttributes(); 77 | 78 | } 79 | 80 | @Test 81 | public void testResolveHandlerMethods() { 82 | 83 | Collection handlerMethods = handlerMethodResolver.resolveHandlerMethods(request, servletContext); 84 | 85 | Assert.assertEquals(1, handlerMethods.size()); 86 | 87 | handlerMethods = handlerMethodResolver.resolveHandlerMethods(request); 88 | 89 | Assert.assertEquals(1, handlerMethods.size()); 90 | 91 | 92 | } 93 | 94 | @Test 95 | public void testResolveHandlerMethod() { 96 | 97 | HandlerMethod handlerMethod = handlerMethodResolver.resolveHandlerMethod(request, servletContext); 98 | 99 | Assert.assertNull(handlerMethod); 100 | 101 | 102 | request.setRequestURI("/echo"); 103 | 104 | handlerMethod = handlerMethodResolver.resolveHandlerMethod(request, servletContext); 105 | 106 | Assert.assertNotNull(handlerMethod); 107 | 108 | Method method = handlerMethod.getMethod(); 109 | 110 | Assert.assertEquals("echo", method.getName()); 111 | 112 | handlerMethod = handlerMethodResolver.resolveHandlerMethod(request); 113 | 114 | Assert.assertNotNull(handlerMethod); 115 | 116 | method = handlerMethod.getMethod(); 117 | 118 | Assert.assertEquals("echo", method.getName()); 119 | 120 | } 121 | 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/servlet/config/annotation/ConfigurableContentNegotiationManagerWebMvcConfigurerTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.config.annotation; 2 | 3 | import com.alibaba.spring.util.FieldUtils; 4 | import org.junit.Assert; 5 | import org.junit.Test; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.mock.web.MockServletContext; 8 | import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; 9 | import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | import static org.springframework.http.MediaType.*; 16 | 17 | /** 18 | * {@link ConfigurableContentNegotiationManagerWebMvcConfigurer} Test 19 | * 20 | * @author Mercy 21 | * @see ConfigurableContentNegotiationManagerWebMvcConfigurer 22 | * @since 2017.03.23 23 | */ 24 | public class ConfigurableContentNegotiationManagerWebMvcConfigurerTest { 25 | 26 | 27 | @Test 28 | public void testConfigureContentNegotiationOnDefaultValues() { 29 | 30 | WebMvcConfigurer webMvcConfigurer = 31 | new ConfigurableContentNegotiationManagerWebMvcConfigurer(new HashMap()); 32 | 33 | ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(new MockServletContext()); 34 | 35 | webMvcConfigurer.configureContentNegotiation(configurer); 36 | 37 | ContentNegotiationManagerFactoryBean factoryBean = 38 | FieldUtils.getFieldValue(configurer, "factory", ContentNegotiationManagerFactoryBean.class); 39 | 40 | Assert.assertTrue(FieldUtils.getFieldValue(factoryBean, "favorPathExtension", boolean.class)); 41 | Assert.assertFalse(FieldUtils.getFieldValue(factoryBean, "favorParameter", boolean.class)); 42 | Assert.assertFalse(FieldUtils.getFieldValue(factoryBean, "ignoreAcceptHeader", boolean.class)); 43 | Assert.assertNull(FieldUtils.getFieldValue(factoryBean, "useJaf", Boolean.class)); 44 | Assert.assertEquals("format", FieldUtils.getFieldValue(factoryBean, "parameterName", String.class)); 45 | Assert.assertTrue(FieldUtils.getFieldValue(factoryBean, "mediaTypes", Map.class).isEmpty()); 46 | Assert.assertNull(FieldUtils.getFieldValue(factoryBean, "defaultContentType", MediaType.class)); 47 | 48 | } 49 | 50 | @Test 51 | public void testConfigureContentNegotiation() { 52 | 53 | Map properties = new HashMap(); 54 | 55 | properties.put("favorPathExtension", "false"); 56 | properties.put("favorParameter", "true"); 57 | properties.put("ignoreAcceptHeader", "true"); 58 | properties.put("useJaf", "true"); 59 | properties.put("parameterName", "test-format"); 60 | properties.put("mediaTypes.html", TEXT_HTML_VALUE); 61 | properties.put("mediaTypes.xml", APPLICATION_XML_VALUE); 62 | properties.put("mediaTypes.json", APPLICATION_JSON_VALUE); 63 | properties.put("mediaTypes.gif", IMAGE_GIF_VALUE); 64 | properties.put("mediaTypes.jpeg", IMAGE_JPEG_VALUE); 65 | properties.put("defaultContentType", TEXT_HTML_VALUE); 66 | 67 | 68 | WebMvcConfigurer webMvcConfigurer = new ConfigurableContentNegotiationManagerWebMvcConfigurer(properties); 69 | 70 | ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(new MockServletContext()); 71 | 72 | ContentNegotiationManagerFactoryBean factoryBean = 73 | FieldUtils.getFieldValue(configurer, "factory", ContentNegotiationManagerFactoryBean.class); 74 | 75 | webMvcConfigurer.configureContentNegotiation(configurer); 76 | 77 | 78 | Assert.assertFalse(FieldUtils.getFieldValue(factoryBean, "favorPathExtension", boolean.class)); 79 | Assert.assertTrue(FieldUtils.getFieldValue(factoryBean, "favorParameter", boolean.class)); 80 | Assert.assertTrue(FieldUtils.getFieldValue(factoryBean, "ignoreAcceptHeader", boolean.class)); 81 | Assert.assertTrue(FieldUtils.getFieldValue(factoryBean, "useJaf", Boolean.class)); 82 | Assert.assertEquals("test-format", FieldUtils.getFieldValue(factoryBean, "parameterName", String.class)); 83 | 84 | Map mediaTypesMap = FieldUtils.getFieldValue(factoryBean, "mediaTypes", Map.class); 85 | 86 | Assert.assertEquals("html", mediaTypesMap.get("html").getSubtype()); 87 | Assert.assertEquals("xml", mediaTypesMap.get("xml").getSubtype()); 88 | Assert.assertEquals("json", mediaTypesMap.get("json").getSubtype()); 89 | Assert.assertEquals("gif", mediaTypesMap.get("gif").getSubtype()); 90 | Assert.assertEquals("jpeg", mediaTypesMap.get("jpeg").getSubtype()); 91 | 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/servlet/handler/AbstractPageRenderContextHandlerInterceptorTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.handler; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.springframework.mock.web.MockHttpServletRequest; 6 | import org.springframework.mock.web.MockHttpServletResponse; 7 | import org.springframework.web.servlet.ModelAndView; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | /** 13 | * {@link AbstractPageRenderContextHandlerInterceptor} Test 14 | * 15 | * @author Mercy 16 | * @see AbstractPageRenderContextHandlerInterceptor 17 | * @since 2017.02.01 18 | */ 19 | public class AbstractPageRenderContextHandlerInterceptorTest { 20 | 21 | 22 | @Test 23 | public void testPostHandler() throws Exception { 24 | 25 | MockHttpServletRequest request = new MockHttpServletRequest(); 26 | 27 | MockHttpServletResponse response = new MockHttpServletResponse(); 28 | 29 | Object handler = new Object(); 30 | 31 | ModelAndView modelAndView = new ModelAndView(); 32 | 33 | AbstractPageRenderContextHandlerInterceptor handlerInterceptor = new AbstractPageRenderContextHandlerInterceptor() { 34 | 35 | @Override 36 | protected void postHandleOnPageRenderContext(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 37 | 38 | modelAndView.getModel().put("test-key", "test-value"); 39 | 40 | } 41 | }; 42 | 43 | handlerInterceptor.preHandle(request, response, handler); 44 | 45 | handlerInterceptor.postHandle(request, response, handler, modelAndView); 46 | 47 | handlerInterceptor.afterCompletion(request, response, handler, null); 48 | 49 | handlerInterceptor.afterConcurrentHandlingStarted(request, response, handler); 50 | 51 | Assert.assertNull(modelAndView.getModel().get("test-key")); 52 | 53 | modelAndView.setViewName("hello"); 54 | 55 | handlerInterceptor.postHandle(request, response, handler, modelAndView); 56 | 57 | Assert.assertEquals("test-value", modelAndView.getModel().get("test-key")); 58 | 59 | handlerInterceptor.postHandle(null, null, null, null); 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/servlet/handler/AnnotatedHandlerMethodHandlerInterceptorAdapterTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.handler; 2 | 3 | import com.alibaba.spring.web.method.HandlerMethodResolver; 4 | import com.alibaba.spring.web.servlet.mvc.controller.TestController; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Ignore; 8 | import org.junit.Test; 9 | import org.springframework.mock.web.MockHttpServletRequest; 10 | import org.springframework.mock.web.MockHttpServletResponse; 11 | import org.springframework.mock.web.MockServletContext; 12 | import org.springframework.ui.Model; 13 | import org.springframework.util.ReflectionUtils; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.method.HandlerMethod; 16 | import org.springframework.web.servlet.ModelAndView; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import java.util.Arrays; 21 | import java.util.Collection; 22 | 23 | /** 24 | * {@link AnnotatedHandlerMethodHandlerInterceptorAdapter} Test 25 | * 26 | * @author Mercy 27 | * @see AnnotatedHandlerMethodHandlerInterceptorAdapter 28 | * @since 2017.02.02 29 | */ 30 | public class AnnotatedHandlerMethodHandlerInterceptorAdapterTest { 31 | 32 | private MockServletContext servletContext; 33 | 34 | private MockHttpServletRequest request; 35 | 36 | private MockHttpServletResponse response; 37 | 38 | private ModelAndView modelAndView; 39 | 40 | private RequestMappingMethodHandlerInterceptorAdapter requestMappingMethodHandlerInterceptor; 41 | 42 | private Collection handlerMethods; 43 | 44 | @Before 45 | public void init() { 46 | 47 | HandlerMethodResolver handlerMethodResolver = new HandlerMethodResolver(); 48 | 49 | servletContext = new MockServletContext(); 50 | 51 | request = new MockHttpServletRequest(servletContext); 52 | 53 | requestMappingMethodHandlerInterceptor = new RequestMappingMethodHandlerInterceptorAdapter(); 54 | 55 | HandlerMethod handlerMethod = new HandlerMethod(new TestController(), 56 | ReflectionUtils.findMethod(TestController.class, "echo", Model.class)); 57 | handlerMethods = Arrays.asList(handlerMethod, handlerMethod, handlerMethod); 58 | 59 | } 60 | 61 | 62 | @Test 63 | public void testPreHandle() throws Exception { 64 | 65 | for (HandlerMethod handlerMethod : handlerMethods) { 66 | 67 | boolean result = requestMappingMethodHandlerInterceptor.preHandle(request, response, handlerMethod); 68 | 69 | Assert.assertFalse(result); 70 | 71 | } 72 | 73 | boolean result = requestMappingMethodHandlerInterceptor.preHandle(request, response, new Object()); 74 | 75 | Assert.assertTrue(result); 76 | 77 | } 78 | 79 | @Test 80 | public void testPostHandle() throws Exception { 81 | 82 | for (HandlerMethod handlerMethod : handlerMethods) { 83 | 84 | requestMappingMethodHandlerInterceptor.postHandle(request, response, handlerMethod, modelAndView); 85 | 86 | } 87 | 88 | requestMappingMethodHandlerInterceptor.postHandle(request, response, new Object(), modelAndView); 89 | 90 | } 91 | 92 | @Test 93 | public void testAfterCompletion() throws Exception { 94 | 95 | for (HandlerMethod handlerMethod : handlerMethods) { 96 | 97 | requestMappingMethodHandlerInterceptor.afterCompletion(request, response, handlerMethod, new Exception()); 98 | 99 | } 100 | 101 | requestMappingMethodHandlerInterceptor.afterCompletion(request, response, new Object(), new Exception()); 102 | 103 | } 104 | 105 | @Test 106 | public void testAfterConcurrentHandlingStarted() throws Exception { 107 | 108 | for (HandlerMethod handlerMethod : handlerMethods) { 109 | 110 | requestMappingMethodHandlerInterceptor.afterConcurrentHandlingStarted(request, response, handlerMethod); 111 | 112 | } 113 | 114 | requestMappingMethodHandlerInterceptor.afterConcurrentHandlingStarted(request, response, new Object()); 115 | 116 | } 117 | 118 | @Test 119 | public void testGetAnnotationType() { 120 | 121 | Assert.assertEquals(RequestMapping.class, requestMappingMethodHandlerInterceptor.getAnnotationType()); 122 | 123 | } 124 | 125 | @Ignore 126 | protected static class RequestMappingMethodHandlerInterceptorAdapter extends 127 | AnnotatedHandlerMethodHandlerInterceptorAdapter { 128 | 129 | @Override 130 | protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, 131 | HandlerMethod handlerMethod, RequestMapping annotation) throws Exception { 132 | 133 | Assert.assertArrayEquals(new String[]{"echo"}, annotation.value()); 134 | Assert.assertEquals("echo", handlerMethod.getMethod().getName()); 135 | 136 | return false; 137 | } 138 | 139 | protected void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, 140 | RequestMapping annotation, ModelAndView modelAndView) throws Exception { 141 | 142 | Assert.assertArrayEquals(new String[]{"echo"}, annotation.value()); 143 | Assert.assertEquals("echo", handlerMethod.getMethod().getName()); 144 | 145 | } 146 | 147 | protected void afterCompletion(HttpServletRequest request, HttpServletResponse response, 148 | HandlerMethod handlerMethod, RequestMapping annotation, Exception ex) 149 | throws Exception { 150 | 151 | Assert.assertArrayEquals(new String[]{"echo"}, annotation.value()); 152 | Assert.assertEquals("echo", handlerMethod.getMethod().getName()); 153 | 154 | } 155 | 156 | protected void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, 157 | HandlerMethod handlerMethod, RequestMapping annotation) throws Exception { 158 | 159 | Assert.assertArrayEquals(new String[]{"echo"}, annotation.value()); 160 | Assert.assertEquals("echo", handlerMethod.getMethod().getName()); 161 | 162 | } 163 | 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/servlet/mvc/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.mvc.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.ui.Model; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | 7 | /** 8 | * Test {@link Controller} 9 | * 10 | * @author Mercy 11 | * @see Controller 12 | * @since 2017.02.02 13 | */ 14 | @Controller 15 | public class TestController { 16 | 17 | @RequestMapping("echo") 18 | public String echo(Model model) { 19 | 20 | return "echo"; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/servlet/mvc/util/WebMvcUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.servlet.mvc.util; 2 | 3 | import com.alibaba.spring.web.TestWebMvcConfigurer; 4 | import com.alibaba.spring.web.servlet.mvc.controller.TestController; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.springframework.context.ApplicationContextInitializer; 9 | import org.springframework.mock.web.MockHttpServletRequest; 10 | import org.springframework.mock.web.MockServletContext; 11 | import org.springframework.web.bind.annotation.ControllerAdvice; 12 | import org.springframework.web.context.WebApplicationContext; 13 | import org.springframework.web.context.request.RequestAttributes; 14 | import org.springframework.web.context.request.RequestContextHolder; 15 | import org.springframework.web.context.request.ServletRequestAttributes; 16 | import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; 17 | import org.springframework.web.context.support.GenericWebApplicationContext; 18 | import org.springframework.web.servlet.DispatcherServlet; 19 | import org.springframework.web.servlet.ModelAndView; 20 | import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; 21 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 22 | 23 | import javax.servlet.ServletContext; 24 | import javax.servlet.http.HttpServletRequest; 25 | 26 | import static org.springframework.web.context.ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM; 27 | import static org.springframework.web.context.ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM; 28 | import static org.springframework.web.context.WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; 29 | 30 | /** 31 | * {@link WebMvcUtils} Test 32 | * 33 | * @author Mercy 34 | * @see WebMvcUtils 35 | * @since 2017.01.13 36 | */ 37 | @ControllerAdvice 38 | public class WebMvcUtilsTest { 39 | 40 | private MockServletContext servletContext; 41 | 42 | private MockHttpServletRequest request; 43 | 44 | @Before 45 | public void init() { 46 | 47 | servletContext = new MockServletContext(); 48 | 49 | request = new MockHttpServletRequest(servletContext); 50 | 51 | RequestContextHolder.resetRequestAttributes(); 52 | 53 | } 54 | 55 | @Test 56 | public void testIsControllerAdviceBeanType() { 57 | 58 | Assert.assertFalse(WebMvcUtils.isControllerAdviceBeanType(WebMvcUtils.class)); 59 | 60 | Assert.assertTrue(WebMvcUtils.isControllerAdviceBeanType(WebMvcUtilsTest.class)); 61 | 62 | } 63 | 64 | @Test 65 | public void testCurrentRequest() { 66 | 67 | MockHttpServletRequest request = new MockHttpServletRequest(); 68 | 69 | ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); 70 | 71 | RequestContextHolder.setRequestAttributes(requestAttributes); 72 | 73 | HttpServletRequest httpServletRequest = WebMvcUtils.currentRequest(); 74 | 75 | Assert.assertEquals(request, httpServletRequest); 76 | 77 | } 78 | 79 | @Test(expected = IllegalStateException.class) 80 | public void testCurrentRequestWithoutRequestAttributes() { 81 | 82 | WebMvcUtils.currentRequest(); 83 | 84 | } 85 | 86 | @Test(expected = IllegalStateException.class) 87 | public void testCurrentRequestInNotServletContainer() { 88 | 89 | RequestContextHolder.setRequestAttributes(new RequestAttributes() { 90 | 91 | @Override 92 | public Object getAttribute(String name, int scope) { 93 | return null; 94 | } 95 | 96 | @Override 97 | public void setAttribute(String name, Object value, int scope) { 98 | 99 | } 100 | 101 | @Override 102 | public void removeAttribute(String name, int scope) { 103 | 104 | } 105 | 106 | @Override 107 | public String[] getAttributeNames(int scope) { 108 | return new String[0]; 109 | } 110 | 111 | @Override 112 | public void registerDestructionCallback(String name, Runnable callback, int scope) { 113 | 114 | } 115 | 116 | @Override 117 | public Object resolveReference(String key) { 118 | return null; 119 | } 120 | 121 | @Override 122 | public String getSessionId() { 123 | return null; 124 | } 125 | 126 | @Override 127 | public Object getSessionMutex() { 128 | return null; 129 | } 130 | 131 | }); 132 | 133 | WebMvcUtils.currentRequest(); 134 | 135 | 136 | } 137 | 138 | @Test 139 | public void testCurrentServletContext() { 140 | 141 | MockHttpServletRequest request = new MockHttpServletRequest(); 142 | 143 | ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); 144 | 145 | RequestContextHolder.setRequestAttributes(requestAttributes); 146 | 147 | ServletContext servletContext = WebMvcUtils.currentServletContext(); 148 | 149 | Assert.assertNotNull(servletContext); 150 | 151 | request = new MockHttpServletRequest(new MockServletContext()); 152 | 153 | requestAttributes = new ServletRequestAttributes(request); 154 | 155 | RequestContextHolder.setRequestAttributes(requestAttributes); 156 | 157 | servletContext = WebMvcUtils.currentServletContext(); 158 | 159 | Assert.assertNotNull(servletContext); 160 | 161 | } 162 | 163 | @Test 164 | public void testAppendInitParameter() { 165 | 166 | String parameterValue = WebMvcUtils.appendInitParameter("value1"); 167 | 168 | Assert.assertEquals("value1", parameterValue); 169 | 170 | parameterValue = WebMvcUtils.appendInitParameter("value1", "value2"); 171 | 172 | Assert.assertEquals("value1,value2", parameterValue); 173 | 174 | } 175 | 176 | @Test 177 | public void testAppendInitParameters() { 178 | 179 | MockServletContext servletContext = new MockServletContext(); 180 | 181 | String parameterName = "name"; 182 | 183 | String parameterValue = "value"; 184 | 185 | Assert.assertNull(servletContext.getInitParameter(parameterName)); 186 | 187 | WebMvcUtils.appendInitParameters(servletContext, parameterName); 188 | 189 | Assert.assertNull(servletContext.getInitParameter(parameterName)); 190 | 191 | WebMvcUtils.appendInitParameters(servletContext, parameterName, parameterValue, parameterValue); 192 | 193 | Assert.assertEquals("value,value", servletContext.getInitParameter(parameterName)); 194 | 195 | } 196 | 197 | @Test 198 | public void testAppendGlobalInitializerClassInitParameter() { 199 | 200 | MockServletContext servletContext = new MockServletContext(); 201 | 202 | WebMvcUtils.appendGlobalInitializerClassInitParameter(servletContext, ApplicationContextInitializer.class); 203 | 204 | Assert.assertEquals(ApplicationContextInitializer.class.getName(), 205 | servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM)); 206 | 207 | } 208 | 209 | @Test 210 | public void testAppendContextInitializerClassInitParameter() { 211 | 212 | MockServletContext servletContext = new MockServletContext(); 213 | 214 | WebMvcUtils.appendContextInitializerClassInitParameter(servletContext, ApplicationContextInitializer.class); 215 | 216 | Assert.assertEquals(ApplicationContextInitializer.class.getName(), 217 | servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM)); 218 | 219 | } 220 | 221 | // @Test 222 | // public void testAppendFrameworkServletContextInitializerClassInitParameter() { 223 | // 224 | // MockServletContext servletContext = new MockServletContext(); 225 | // 226 | // WebMvcUtils.appendFrameworkServletContextInitializerClassInitParameter(servletContext, ApplicationContextInitializer.class); 227 | // 228 | // Assert.assertEquals(ApplicationContextInitializer.class.getName(), 229 | // servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM)); 230 | // 231 | // } 232 | 233 | @Test 234 | public void testIsPageRenderRequest() { 235 | 236 | Assert.assertFalse(WebMvcUtils.isPageRenderRequest(null)); 237 | 238 | ModelAndView modelAndView = new ModelAndView(); 239 | 240 | Assert.assertFalse(WebMvcUtils.isPageRenderRequest(modelAndView)); 241 | 242 | modelAndView.setViewName("hello"); 243 | 244 | Assert.assertTrue(WebMvcUtils.isPageRenderRequest(modelAndView)); 245 | 246 | } 247 | 248 | @Test(expected = IllegalStateException.class) 249 | public void testGetWebApplicationContextWithoutServletContext() { 250 | 251 | WebMvcUtils.getWebApplicationContext(request, null); 252 | 253 | } 254 | 255 | @Test(expected = IllegalStateException.class) 256 | public void testGetWebApplicationContextWithoutWebApplicationContext() { 257 | 258 | WebMvcUtils.getWebApplicationContext(request, servletContext); 259 | 260 | } 261 | 262 | @Test 263 | public void testGetWebApplicationContext() { 264 | 265 | WebApplicationContext webApplicationContext = new GenericWebApplicationContext(); 266 | 267 | request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 268 | 269 | WebApplicationContext applicationContext = WebMvcUtils.getWebApplicationContext(request, servletContext); 270 | 271 | Assert.assertEquals(webApplicationContext, applicationContext); 272 | 273 | applicationContext = WebMvcUtils.getWebApplicationContext(request); 274 | 275 | Assert.assertEquals(webApplicationContext, applicationContext); 276 | 277 | } 278 | 279 | @Test 280 | public void testCurrentWebApplicationContext() { 281 | 282 | WebApplicationContext webApplicationContext = new GenericWebApplicationContext(); 283 | 284 | RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); 285 | 286 | servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 287 | 288 | WebApplicationContext applicationContext = WebMvcUtils.currentWebApplicationContext(); 289 | 290 | Assert.assertEquals(webApplicationContext, applicationContext); 291 | 292 | } 293 | 294 | @Test 295 | public void testGetRequestMappingHandlerMapping() { 296 | 297 | AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext(); 298 | 299 | servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 300 | 301 | webApplicationContext.setServletContext(servletContext); 302 | 303 | webApplicationContext.register(TestController.class); 304 | webApplicationContext.register(DelegatingWebMvcConfiguration.class); 305 | webApplicationContext.register(TestWebMvcConfigurer.class); 306 | 307 | webApplicationContext.refresh(); 308 | 309 | request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); 310 | 311 | RequestMappingHandlerMapping requestMappingHandlerMapping = 312 | WebMvcUtils.getRequestMappingHandlerMapping(request, servletContext); 313 | 314 | Assert.assertNotNull(requestMappingHandlerMapping); 315 | 316 | Assert.assertFalse(requestMappingHandlerMapping.getHandlerMethods().isEmpty()); 317 | 318 | requestMappingHandlerMapping = 319 | WebMvcUtils.getRequestMappingHandlerMapping(request); 320 | 321 | Assert.assertNotNull(requestMappingHandlerMapping); 322 | 323 | Assert.assertFalse(requestMappingHandlerMapping.getHandlerMethods().isEmpty()); 324 | 325 | } 326 | 327 | } 328 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/util/HandlerMethodUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.util; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.springframework.web.method.HandlerMethod; 6 | 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | /** 15 | * {@link HandlerMethodUtils} Test 16 | * 17 | * @author Mercy 18 | * @see HandlerMethodUtils 19 | * @since 2017.01.12 20 | */ 21 | public class HandlerMethodUtilsTest { 22 | 23 | 24 | @Test 25 | public void testFindAnnotation() throws Exception { 26 | 27 | HandlerMethod handlerMethod = new HandlerMethod(new RuntimeAnnotationHandler(), "handle", String.class); 28 | 29 | RuntimeAnnotation runtimeAnnotation = HandlerMethodUtils.findAnnotation(handlerMethod.getReturnType(), 30 | RuntimeAnnotation.class); 31 | 32 | Assert.assertEquals("method", runtimeAnnotation.value()); 33 | 34 | runtimeAnnotation = HandlerMethodUtils.findAnnotation(handlerMethod.getMethodParameters()[0], 35 | RuntimeAnnotation.class); 36 | 37 | Assert.assertEquals("parameter", runtimeAnnotation.value()); 38 | 39 | handlerMethod = new HandlerMethod(new ClassAnnotationHandler(), "handle", String.class); 40 | 41 | runtimeAnnotation = HandlerMethodUtils.findAnnotation(handlerMethod.getReturnType(), 42 | RuntimeAnnotation.class); 43 | 44 | Assert.assertNull(runtimeAnnotation); 45 | 46 | runtimeAnnotation = HandlerMethodUtils.findAnnotation(handlerMethod.getMethodParameters()[0], 47 | RuntimeAnnotation.class); 48 | 49 | Assert.assertNull(runtimeAnnotation); 50 | 51 | ClassAnnotation classAnnotation = HandlerMethodUtils.findAnnotation(handlerMethod.getReturnType(), 52 | ClassAnnotation.class); 53 | 54 | Assert.assertNull(classAnnotation); 55 | } 56 | 57 | 58 | @Test 59 | public void testFindAnnotations() throws Exception { 60 | 61 | HandlerMethod handlerMethod = new HandlerMethod(new RuntimeAnnotationHandler(), "handle", 62 | String.class, String.class); 63 | 64 | Map> annotationsMap = 65 | HandlerMethodUtils.findAnnotations(handlerMethod, RuntimeAnnotation.class); 66 | 67 | Assert.assertEquals(3, annotationsMap.size()); 68 | 69 | List annotationsList = annotationsMap.get(ElementType.TYPE); 70 | 71 | Assert.assertEquals(1, annotationsList.size()); 72 | 73 | RuntimeAnnotation runtimeAnnotation = annotationsList.get(0); 74 | 75 | Assert.assertEquals("type", runtimeAnnotation.value()); 76 | 77 | annotationsList = annotationsMap.get(ElementType.METHOD); 78 | 79 | Assert.assertEquals(1, annotationsList.size()); 80 | 81 | runtimeAnnotation = annotationsList.get(0); 82 | 83 | Assert.assertEquals("method", runtimeAnnotation.value()); 84 | 85 | annotationsList = annotationsMap.get(ElementType.PARAMETER); 86 | 87 | Assert.assertEquals(2, annotationsList.size()); 88 | 89 | runtimeAnnotation = annotationsList.get(0); 90 | 91 | Assert.assertEquals("parameter1", runtimeAnnotation.value()); 92 | 93 | runtimeAnnotation = annotationsList.get(1); 94 | 95 | Assert.assertEquals("parameter2", runtimeAnnotation.value()); 96 | 97 | 98 | annotationsList = annotationsMap.get(ElementType.PACKAGE); 99 | 100 | Assert.assertNull(annotationsList); 101 | 102 | 103 | handlerMethod = new HandlerMethod(new ClassAnnotationHandler(), "handle", String.class); 104 | 105 | annotationsMap = 106 | HandlerMethodUtils.findAnnotations(handlerMethod, RuntimeAnnotation.class); 107 | 108 | Assert.assertTrue(annotationsMap.isEmpty()); 109 | 110 | Map> classAnnotationsMap = HandlerMethodUtils.findAnnotations(handlerMethod, 111 | ClassAnnotation.class); 112 | 113 | Assert.assertTrue(classAnnotationsMap.isEmpty()); 114 | 115 | } 116 | 117 | @RuntimeAnnotation("type") 118 | private static class RuntimeAnnotationHandler { 119 | 120 | @RuntimeAnnotation("method") 121 | public String handle(@RuntimeAnnotation("parameter") String message) { 122 | return message; 123 | } 124 | 125 | @RuntimeAnnotation("method") 126 | public String handle(@RuntimeAnnotation("parameter1") String message, 127 | @RuntimeAnnotation("parameter2") String message2) { 128 | return message + message2; 129 | } 130 | 131 | } 132 | 133 | @ClassAnnotation 134 | private static class ClassAnnotationHandler { 135 | 136 | @ClassAnnotation 137 | public String handle(@ClassAnnotation String message) { 138 | return message; 139 | } 140 | 141 | } 142 | 143 | 144 | @Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.METHOD}) 145 | @Retention(RetentionPolicy.RUNTIME) 146 | private static @interface RuntimeAnnotation { 147 | 148 | String value(); 149 | 150 | } 151 | 152 | @Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.METHOD}) 153 | @Retention(RetentionPolicy.CLASS) 154 | private static @interface ClassAnnotation { 155 | 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/spring/web/util/WebUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.spring.web.util; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.springframework.mock.web.MockHttpServletRequest; 6 | import org.springframework.mock.web.MockServletContext; 7 | 8 | /** 9 | * {@link WebUtils} Test 10 | * 11 | * @author Mercy 12 | * @see WebUtils 13 | * @since 2017.01.13 14 | */ 15 | public class WebUtilsTest { 16 | 17 | 18 | @Test 19 | public void testIsRunningBelowServlet3Container() { 20 | 21 | MockServletContext servletContext = new MockServletContext(); 22 | 23 | servletContext.setMajorVersion(3); 24 | 25 | Assert.assertFalse(WebUtils.isRunningBelowServlet3Container()); 26 | 27 | servletContext.setMajorVersion(2); 28 | 29 | Assert.assertFalse(WebUtils.isRunningBelowServlet3Container()); 30 | 31 | } 32 | 33 | @Test 34 | public void testGetServletContext() { 35 | 36 | MockServletContext servletContext = new MockServletContext(); 37 | 38 | MockHttpServletRequest request = new MockHttpServletRequest(servletContext); 39 | 40 | Assert.assertEquals(servletContext, WebUtils.getServletContext(request)); 41 | 42 | } 43 | 44 | 45 | // @Test 46 | // public void testFindFilterRegistrations() { 47 | // 48 | // MockServletContext servletContext = new MockServletContext(); 49 | // 50 | // Map filterRegistrations = 51 | // findFilterRegistrations(servletContext, Filter.class); 52 | // 53 | // Assert.assertTrue(filterRegistrations.isEmpty()); 54 | // 55 | // } 56 | 57 | } 58 | --------------------------------------------------------------------------------