web-reactive.md 325.8 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286
# Web on Reactive Stack

This part of the documentation covers support for reactive-stack web applications built
on a [Reactive Streams](https://www.reactive-streams.org/) API to run on non-blocking
servers, such as Netty, Undertow, and Servlet 3.1+ containers. Individual chapters cover
the [Spring WebFlux](webflux.html#webflux) framework,
the reactive [`WebClient`](#webflux-client), support for [testing](#webflux-test),
and [reactive libraries](#webflux-reactive-libraries). For Servlet-stack web applications,
see [Web on Servlet Stack](web.html#spring-web).

## 1. Spring WebFlux

The original web framework included in the Spring Framework, Spring Web MVC, was
purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework,
Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports[Reactive Streams](https://www.reactive-streams.org/) back pressure, and runs on such servers as
Netty, Undertow, and Servlet 3.1+ containers.

Both web frameworks mirror the names of their source modules
([spring-webmvc](https://github.com/spring-projects/spring-framework/tree/main/spring-webmvc) and[spring-webflux](https://github.com/spring-projects/spring-framework/tree/main/spring-webflux)) and co-exist side by side in the
Spring Framework. Each module is optional. Applications can use one or the other module or,
in some cases, both — for example, Spring MVC controllers with the reactive `WebClient`.

### 1.1. Overview

Why was Spring WebFlux created?

Part of the answer is the need for a non-blocking web stack to handle concurrency with a
small number of threads and scale with fewer hardware resources. Servlet 3.1 did provide
an API for non-blocking I/O. However, using it leads away from the rest of the Servlet API,
where contracts are synchronous (`Filter`, `Servlet`) or blocking (`getParameter`,`getPart`). This was the motivation for a new common API to serve as a foundation across
any non-blocking runtime. That is important because of servers (such as Netty) that are
well-established in the async, non-blocking space.

The other part of the answer is functional programming. Much as the addition of annotations
in Java 5 created opportunities (such as annotated REST controllers or unit tests), the addition
of lambda expressions in Java 8 created opportunities for functional APIs in Java.
This is a boon for non-blocking applications and continuation-style APIs (as popularized
by `CompletableFuture` and [ReactiveX](http://reactivex.io/)) that allow declarative
composition of asynchronous logic. At the programming-model level, Java 8 enabled Spring
WebFlux to offer functional web endpoints alongside annotated controllers.

#### 1.1.1. Define “Reactive”

We touched on “non-blocking” and “functional” but what does reactive mean?

The term, “reactive,” refers to programming models that are built around reacting to change — network components reacting to I/O events, UI controllers reacting to mouse events, and others.
In that sense, non-blocking is reactive, because, instead of being blocked, we are now in the mode
of reacting to notifications as operations complete or data becomes available.

There is also another important mechanism that we on the Spring team associate with “reactive”
and that is non-blocking back pressure. In synchronous, imperative code, blocking calls
serve as a natural form of back pressure that forces the caller to wait. In non-blocking
code, it becomes important to control the rate of events so that a fast producer does not
overwhelm its destination.

Reactive Streams is a[small spec](https://github.com/reactive-streams/reactive-streams-jvm/blob/master/README.md#specification)(also [adopted](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Flow.html) in Java 9)
that defines the interaction between asynchronous components with back pressure.
For example a data repository (acting as[Publisher](https://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Publisher.html))
can produce data that an HTTP server (acting as[Subscriber](https://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Subscriber.html))
can then write to the response. The main purpose of Reactive Streams is to let the
subscriber control how quickly or how slowly the publisher produces data.

|   |**Common question: what if a publisher cannot slow down?**  <br/>The purpose of Reactive Streams is only to establish the mechanism and a boundary.<br/>If a publisher cannot slow down, it has to decide whether to buffer, drop, or fail.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.1.2. Reactive API

Reactive Streams plays an important role for interoperability. It is of interest to libraries
and infrastructure components but less useful as an application API, because it is too
low-level. Applications need a higher-level and richer, functional API to
compose async logic — similar to the Java 8 `Stream` API but not only for collections.
This is the role that reactive libraries play.

[Reactor](https://github.com/reactor/reactor) is the reactive library of choice for
Spring WebFlux. It provides the[`Mono`](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html) and[`Flux`](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html) API types
to work on data sequences of 0..1 (`Mono`) and 0..N (`Flux`) through a rich set of operators aligned with the
ReactiveX [vocabulary of operators](http://reactivex.io/documentation/operators.html).
Reactor is a Reactive Streams library and, therefore, all of its operators support non-blocking back pressure.
Reactor has a strong focus on server-side Java. It is developed in close collaboration
with Spring.

WebFlux requires Reactor as a core dependency but it is interoperable with other reactive
libraries via Reactive Streams. As a general rule, a WebFlux API accepts a plain `Publisher`as input, adapts it to a Reactor type internally, uses that, and returns either a`Flux` or a `Mono` as output. So, you can pass any `Publisher` as input and you can apply
operations on the output, but you need to adapt the output for use with another reactive library.
Whenever feasible (for example, annotated controllers), WebFlux adapts transparently to the use
of RxJava or another reactive library. See [Reactive Libraries](#webflux-reactive-libraries) for more details.

|   |In addition to Reactive APIs, WebFlux can also be used with[Coroutines](languages.html#coroutines) APIs in Kotlin which provides a more imperative style of programming.<br/>The following Kotlin code samples will be provided with Coroutines APIs.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.1.3. Programming Models

The `spring-web` module contains the reactive foundation that underlies Spring WebFlux,
including HTTP abstractions, Reactive Streams [adapters](#webflux-httphandler) for supported
servers, [codecs](#webflux-codecs), and a core [`WebHandler` API](#webflux-web-handler-api) comparable to
the Servlet API but with non-blocking contracts.

On that foundation, Spring WebFlux provides a choice of two programming models:

* [Annotated Controllers](#webflux-controller): Consistent with Spring MVC and based on the same annotations
  from the `spring-web` module. Both Spring MVC and WebFlux controllers support reactive
  (Reactor and RxJava) return types, and, as a result, it is not easy to tell them apart. One notable
  difference is that WebFlux also supports reactive `@RequestBody` arguments.

* [Functional Endpoints](#webflux-fn): Lambda-based, lightweight, and functional programming model. You can think of
  this as a small library or a set of utilities that an application can use to route and
  handle requests. The big difference with annotated controllers is that the application
  is in charge of request handling from start to finish versus declaring intent through
  annotations and being called back.

#### 1.1.4. Applicability

Spring MVC or WebFlux?

A natural question to ask but one that sets up an unsound dichotomy. Actually, both
work together to expand the range of available options. The two are designed for
continuity and consistency with each other, they are available side by side, and feedback
from each side benefits both sides. The following diagram shows how the two relate, what they
have in common, and what each supports uniquely:

![spring mvc and webflux venn](images/spring-mvc-and-webflux-venn.png)

We suggest that you consider the following specific points:

* If you have a Spring MVC application that works fine, there is no need to change.
  Imperative programming is the easiest way to write, understand, and debug code.
  You have maximum choice of libraries, since, historically, most are blocking.

* If you are already shopping for a non-blocking web stack, Spring WebFlux offers the same
  execution model benefits as others in this space and also provides a choice of servers
  (Netty, Tomcat, Jetty, Undertow, and Servlet 3.1+ containers), a choice of programming models
  (annotated controllers and functional web endpoints), and a choice of reactive libraries
  (Reactor, RxJava, or other).

* If you are interested in a lightweight, functional web framework for use with Java 8 lambdas
  or Kotlin, you can use the Spring WebFlux functional web endpoints. That can also be a good choice
  for smaller applications or microservices with less complex requirements that can benefit
  from greater transparency and control.

* In a microservice architecture, you can have a mix of applications with either Spring MVC
  or Spring WebFlux controllers or with Spring WebFlux functional endpoints. Having support
  for the same annotation-based programming model in both frameworks makes it easier to
  re-use knowledge while also selecting the right tool for the right job.

* A simple way to evaluate an application is to check its dependencies. If you have blocking
  persistence APIs (JPA, JDBC) or networking APIs to use, Spring MVC is the best choice
  for common architectures at least. It is technically feasible with both Reactor and
  RxJava to perform blocking calls on a separate thread but you would not be making the
  most of a non-blocking web stack.

* If you have a Spring MVC application with calls to remote services, try the reactive `WebClient`.
  You can return reactive types (Reactor, RxJava, [or other](#webflux-reactive-libraries))
  directly from Spring MVC controller methods. The greater the latency per call or the
  interdependency among calls, the more dramatic the benefits. Spring MVC controllers
  can call other reactive components too.

* If you have a large team, keep in mind the steep learning curve in the shift to non-blocking,
  functional, and declarative programming. A practical way to start without a full switch
  is to use the reactive `WebClient`. Beyond that, start small and measure the benefits.
  We expect that, for a wide range of applications, the shift is unnecessary. If you are
  unsure what benefits to look for, start by learning about how non-blocking I/O works
  (for example, concurrency on single-threaded Node.js) and its effects.

#### 1.1.5. Servers

Spring WebFlux is supported on Tomcat, Jetty, Servlet 3.1+ containers, as well as on
non-Servlet runtimes such as Netty and Undertow. All servers are adapted to a low-level,[common API](#webflux-httphandler) so that higher-level[programming models](#webflux-programming-models) can be supported across servers.

Spring WebFlux does not have built-in support to start or stop a server. However, it is
easy to [assemble](#webflux-web-handler-api) an application from Spring configuration and[WebFlux infrastructure](#webflux-config) and [run it](#webflux-httphandler) with a few
lines of code.

Spring Boot has a WebFlux starter that automates these steps. By default, the starter uses
Netty, but it is easy to switch to Tomcat, Jetty, or Undertow by changing your
Maven or Gradle dependencies. Spring Boot defaults to Netty, because it is more widely
used in the asynchronous, non-blocking space and lets a client and a server share resources.

Tomcat and Jetty can be used with both Spring MVC and WebFlux. Keep in mind, however, that
the way they are used is very different. Spring MVC relies on Servlet blocking I/O and
lets applications use the Servlet API directly if they need to. Spring WebFlux
relies on Servlet 3.1 non-blocking I/O and uses the Servlet API behind a low-level
adapter. It is not exposed for direct use.

For Undertow, Spring WebFlux uses Undertow APIs directly without the Servlet API.

#### 1.1.6. Performance

Performance has many characteristics and meanings. Reactive and non-blocking generally
do not make applications run faster. They can, in some cases, (for example, if using the`WebClient` to run remote calls in parallel). On the whole, it requires more work to do
things the non-blocking way and that can slightly increase the required processing time.

The key expected benefit of reactive and non-blocking is the ability to scale with a small,
fixed number of threads and less memory. That makes applications more resilient under load,
because they scale in a more predictable way. In order to observe those benefits, however, you
need to have some latency (including a mix of slow and unpredictable network I/O).
That is where the reactive stack begins to show its strengths, and the differences can be
dramatic.

#### 1.1.7. Concurrency Model

Both Spring MVC and Spring WebFlux support annotated controllers, but there is a key
difference in the concurrency model and the default assumptions for blocking and threads.

In Spring MVC (and servlet applications in general), it is assumed that applications can
block the current thread, (for example, for remote calls). For this reason, servlet containers
use a large thread pool to absorb potential blocking during request handling.

In Spring WebFlux (and non-blocking servers in general), it is assumed that applications
do not block. Therefore, non-blocking servers use a small, fixed-size thread pool
(event loop workers) to handle requests.

|   |“To scale” and “small number of threads” may sound contradictory but to never block the<br/>current thread (and rely on callbacks instead) means that you do not need extra threads, as<br/>there are no blocking calls to absorb.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Invoking a Blocking API

What if you do need to use a blocking library? Both Reactor and RxJava provide the`publishOn` operator to continue processing on a different thread. That means there is an
easy escape hatch. Keep in mind, however, that blocking APIs are not a good fit for
this concurrency model.

Mutable State

In Reactor and RxJava, you declare logic through operators. At runtime, a reactive
pipeline is formed where data is processed sequentially, in distinct stages. A key benefit
of this is that it frees applications from having to protect mutable state because
application code within that pipeline is never invoked concurrently.

Threading Model

What threads should you expect to see on a server running with Spring WebFlux?

* On a “vanilla” Spring WebFlux server (for example, no data access nor other optional
  dependencies), you can expect one thread for the server and several others for request
  processing (typically as many as the number of CPU cores). Servlet containers, however,
  may start with more threads (for example, 10 on Tomcat), in support of both servlet (blocking) I/O
  and servlet 3.1 (non-blocking) I/O usage.

* The reactive `WebClient` operates in event loop style. So you can see a small, fixed
  number of processing threads related to that (for example, `reactor-http-nio-` with the Reactor
  Netty connector). However, if Reactor Netty is used for both client and server, the two
  share event loop resources by default.

* Reactor and RxJava provide thread pool abstractions, called schedulers, to use with the`publishOn` operator that is used to switch processing to a different thread pool.
  The schedulers have names that suggest a specific concurrency strategy — for example, “parallel”
  (for CPU-bound work with a limited number of threads) or “elastic” (for I/O-bound work with
  a large number of threads). If you see such threads, it means some code is using a
  specific thread pool `Scheduler` strategy.

* Data access libraries and other third party dependencies can also create and use threads
  of their own.

Configuring

The Spring Framework does not provide support for starting and stopping[servers](#webflux-server-choice). To configure the threading model for a server,
you need to use server-specific configuration APIs, or, if you use Spring Boot,
check the Spring Boot configuration options for each server. You can[configure](#webflux-client-builder) the `WebClient` directly.
For all other libraries, see their respective documentation.

### 1.2. Reactive Core

The `spring-web` module contains the following foundational support for reactive web
applications:

* For server request processing there are two levels of support.

  * [HttpHandler](#webflux-httphandler): Basic contract for HTTP request handling with
    non-blocking I/O and Reactive Streams back pressure, along with adapters for Reactor Netty,
    Undertow, Tomcat, Jetty, and any Servlet 3.1+ container.

  * [`WebHandler` API](#webflux-web-handler-api): Slightly higher level, general-purpose web API for
    request handling, on top of which concrete programming models such as annotated
    controllers and functional endpoints are built.

* For the client side, there is a basic `ClientHttpConnector` contract to perform HTTP
  requests with non-blocking I/O and Reactive Streams back pressure, along with adapters for[Reactor Netty](https://github.com/reactor/reactor-netty), reactive[Jetty HttpClient](https://github.com/jetty-project/jetty-reactive-httpclient)and [Apache HttpComponents](https://hc.apache.org/).
  The higher level [WebClient](#webflux-client) used in applications
  builds on this basic contract.

* For client and server, [codecs](#webflux-codecs) for serialization and
  deserialization of HTTP request and response content.

#### 1.2.1. `HttpHandler`

[HttpHandler](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/server/reactive/HttpHandler.html)is a simple contract with a single method to handle a request and a response. It is
intentionally minimal, and its main and only purpose is to be a minimal abstraction
over different HTTP server APIs.

The following table describes the supported server APIs:

|     Server name     |                                Server API used                                 |                     Reactive Streams support                      |
|---------------------|--------------------------------------------------------------------------------|-------------------------------------------------------------------|
|        Netty        |                                   Netty API                                    |     [Reactor Netty](https://github.com/reactor/reactor-netty)     |
|      Undertow       |                                  Undertow API                                  |          spring-web: Undertow to Reactive Streams bridge          |
|       Tomcat        |Servlet 3.1 non-blocking I/O; Tomcat API to read and write ByteBuffers vs byte[]|spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge|
|        Jetty        |     Servlet 3.1 non-blocking I/O; Jetty API to write ByteBuffers vs byte[]     |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge|
|Servlet 3.1 container|                          Servlet 3.1 non-blocking I/O                          |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge|

The following table describes server dependencies (also see[supported versions](https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework)):

| Server name |       Group id        |       Artifact name       |
|-------------|-----------------------|---------------------------|
|Reactor Netty|io.projectreactor.netty|       reactor-netty       |
|  Undertow   |      io.undertow      |       undertow-core       |
|   Tomcat    |org.apache.tomcat.embed|     tomcat-embed-core     |
|    Jetty    |   org.eclipse.jetty   |jetty-server, jetty-servlet|

The code snippets below show using the `HttpHandler` adapters with each server API:

**Reactor Netty**

Java

```
HttpHandler handler = ...
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
HttpServer.create().host(host).port(port).handle(adapter).bind().block();
```

Kotlin

```
val handler: HttpHandler = ...
val adapter = ReactorHttpHandlerAdapter(handler)
HttpServer.create().host(host).port(port).handle(adapter).bind().block()
```

**Undertow**

Java

```
HttpHandler handler = ...
UndertowHttpHandlerAdapter adapter = new UndertowHttpHandlerAdapter(handler);
Undertow server = Undertow.builder().addHttpListener(port, host).setHandler(adapter).build();
server.start();
```

Kotlin

```
val handler: HttpHandler = ...
val adapter = UndertowHttpHandlerAdapter(handler)
val server = Undertow.builder().addHttpListener(port, host).setHandler(adapter).build()
server.start()
```

**Tomcat**

Java

```
HttpHandler handler = ...
Servlet servlet = new TomcatHttpHandlerAdapter(handler);

Tomcat server = new Tomcat();
File base = new File(System.getProperty("java.io.tmpdir"));
Context rootContext = server.addContext("", base.getAbsolutePath());
Tomcat.addServlet(rootContext, "main", servlet);
rootContext.addServletMappingDecoded("/", "main");
server.setHost(host);
server.setPort(port);
server.start();
```

Kotlin

```
val handler: HttpHandler = ...
val servlet = TomcatHttpHandlerAdapter(handler)

val server = Tomcat()
val base = File(System.getProperty("java.io.tmpdir"))
val rootContext = server.addContext("", base.absolutePath)
Tomcat.addServlet(rootContext, "main", servlet)
rootContext.addServletMappingDecoded("/", "main")
server.host = host
server.setPort(port)
server.start()
```

**Jetty**

Java

```
HttpHandler handler = ...
Servlet servlet = new JettyHttpHandlerAdapter(handler);

Server server = new Server();
ServletContextHandler contextHandler = new ServletContextHandler(server, "");
contextHandler.addServlet(new ServletHolder(servlet), "/");
contextHandler.start();

ServerConnector connector = new ServerConnector(server);
connector.setHost(host);
connector.setPort(port);
server.addConnector(connector);
server.start();
```

Kotlin

```
val handler: HttpHandler = ...
val servlet = JettyHttpHandlerAdapter(handler)

val server = Server()
val contextHandler = ServletContextHandler(server, "")
contextHandler.addServlet(ServletHolder(servlet), "/")
contextHandler.start();

val connector = ServerConnector(server)
connector.host = host
connector.port = port
server.addConnector(connector)
server.start()
```

**Servlet 3.1+ Container**

To deploy as a WAR to any Servlet 3.1+ container, you can extend and include[`AbstractReactiveWebInitializer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/adapter/AbstractReactiveWebInitializer.html)in the WAR. That class wraps an `HttpHandler` with `ServletHttpHandlerAdapter` and registers
that as a `Servlet`.

#### 1.2.2. `WebHandler` API

The `org.springframework.web.server` package builds on the [`HttpHandler`](#webflux-httphandler) contract
to provide a general-purpose web API for processing requests through a chain of multiple[`WebExceptionHandler`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/WebExceptionHandler.html), multiple[`WebFilter`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/WebFilter.html), and a single[`WebHandler`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/WebHandler.html) component. The chain can
be put together with `WebHttpHandlerBuilder` by simply pointing to a Spring`ApplicationContext` where components are[auto-detected](#webflux-web-handler-api-special-beans), and/or by registering components
with the builder.

While `HttpHandler` has a simple goal to abstract the use of different HTTP servers, the`WebHandler` API aims to provide a broader set of features commonly used in web applications
such as:

* User session with attributes.

* Request attributes.

* Resolved `Locale` or `Principal` for the request.

* Access to parsed and cached form data.

* Abstractions for multipart data.

* and more..

##### Special bean types

The table below lists the components that `WebHttpHandlerBuilder` can auto-detect in a
Spring ApplicationContext, or that can be registered directly with it:

|         Bean name          |         Bean type          |Count|                                                                                           Description                                                                                            |
|----------------------------|----------------------------|-----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|          \<any\>           |   `WebExceptionHandler`    |0..N |               Provide handling for exceptions from the chain of `WebFilter` instances and the target`WebHandler`. For more details, see [Exceptions](#webflux-exception-handler).                |
|          \<any\>           |        `WebFilter`         |0..N |               Apply interception style logic to before and after the rest of the filter chain and<br/>the target `WebHandler`. For more details, see [Filters](#webflux-filters).                |
|        `webHandler`        |        `WebHandler`        |  1  |                                                                                   The handler for the request.                                                                                   |
|    `webSessionManager`     |    `WebSessionManager`     |0..1 |                                  The manager for `WebSession` instances exposed through a method on `ServerWebExchange`.`DefaultWebSessionManager` by default.                                   |
|  `serverCodecConfigurer`   |  `ServerCodecConfigurer`   |0..1 |For access to `HttpMessageReader` instances for parsing form data and multipart data that is then<br/>exposed through methods on `ServerWebExchange`. `ServerCodecConfigurer.create()` by default.|
|  `localeContextResolver`   |  `LocaleContextResolver`   |0..1 |                                 The resolver for `LocaleContext` exposed through a method on `ServerWebExchange`.`AcceptHeaderLocaleContextResolver` by default.                                 |
|`forwardedHeaderTransformer`|`ForwardedHeaderTransformer`|0..1 |                                 For processing forwarded type headers, either by extracting and removing them or by removing them only.<br/>Not used by default.                                 |

##### Form Data

`ServerWebExchange` exposes the following method for accessing form data:

Java

```
Mono<MultiValueMap<String, String>> getFormData();
```

Kotlin

```
suspend fun getFormData(): MultiValueMap<String, String>
```

The `DefaultServerWebExchange` uses the configured `HttpMessageReader` to parse form data
(`application/x-www-form-urlencoded`) into a `MultiValueMap`. By default,`FormHttpMessageReader` is configured for use by the `ServerCodecConfigurer` bean
(see the [Web Handler API](#webflux-web-handler-api)).

##### Multipart Data

[Web MVC](web.html#mvc-multipart)

`ServerWebExchange` exposes the following method for accessing multipart data:

Java

```
Mono<MultiValueMap<String, Part>> getMultipartData();
```

Kotlin

```
suspend fun getMultipartData(): MultiValueMap<String, Part>
```

The `DefaultServerWebExchange` uses the configured`HttpMessageReader<MultiValueMap<String, Part>>` to parse `multipart/form-data` content
into a `MultiValueMap`.
By default, this is the `DefaultPartHttpMessageReader`, which does not have any third-party
dependencies.
Alternatively, the `SynchronossPartHttpMessageReader` can be used, which is based on the[Synchronoss NIO Multipart](https://github.com/synchronoss/nio-multipart) library.
Both are configured through the `ServerCodecConfigurer` bean
(see the [Web Handler API](#webflux-web-handler-api)).

To parse multipart data in streaming fashion, you can use the `Flux<Part>` returned from an`HttpMessageReader<Part>` instead. For example, in an annotated controller, use of`@RequestPart` implies `Map`-like access to individual parts by name and, hence, requires
parsing multipart data in full. By contrast, you can use `@RequestBody` to decode the
content to `Flux<Part>` without collecting to a `MultiValueMap`.

##### Forwarded Headers

[Web MVC](web.html#filters-forwarded-headers)

As a request goes through proxies (such as load balancers), the host, port, and
scheme may change. That makes it a challenge, from a client perspective, to create links that point to the correct
host, port, and scheme.

[RFC 7239](https://tools.ietf.org/html/rfc7239) defines the `Forwarded` HTTP header
that proxies can use to provide information about the original request. There are other
non-standard headers, too, including `X-Forwarded-Host`, `X-Forwarded-Port`,`X-Forwarded-Proto`, `X-Forwarded-Ssl`, and `X-Forwarded-Prefix`.

`ForwardedHeaderTransformer` is a component that modifies the host, port, and scheme of
the request, based on forwarded headers, and then removes those headers. If you declare
it as a bean with the name `forwardedHeaderTransformer`, it will be[detected](#webflux-web-handler-api-special-beans) and used.

There are security considerations for forwarded headers, since an application cannot know
if the headers were added by a proxy, as intended, or by a malicious client. This is why
a proxy at the boundary of trust should be configured to remove untrusted forwarded traffic coming
from the outside. You can also configure the `ForwardedHeaderTransformer` with`removeOnly=true`, in which case it removes but does not use the headers.

|   |In 5.1 `ForwardedHeaderFilter` was deprecated and superceded by`ForwardedHeaderTransformer` so forwarded headers can be processed earlier, before the<br/>exchange is created. If the filter is configured anyway, it is taken out of the list of<br/>filters, and `ForwardedHeaderTransformer` is used instead.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.2.3. Filters

[Web MVC](web.html#filters)

In the [`WebHandler` API](#webflux-web-handler-api), you can use a `WebFilter` to apply interception-style
logic before and after the rest of the processing chain of filters and the target`WebHandler`. When using the [WebFlux Config](#webflux-config), registering a `WebFilter` is as simple
as declaring it as a Spring bean and (optionally) expressing precedence by using `@Order` on
the bean declaration or by implementing `Ordered`.

##### CORS

[Web MVC](web.html#filters-cors)

Spring WebFlux provides fine-grained support for CORS configuration through annotations on
controllers. However, when you use it with Spring Security, we advise relying on the built-in`CorsFilter`, which must be ordered ahead of Spring Security’s chain of filters.

See the section on [CORS](#webflux-cors) and the [webflux-cors.html](webflux-cors.html#webflux-cors-webfilter) for more details.

#### 1.2.4. Exceptions

[Web MVC](web.html#mvc-ann-customer-servlet-container-error-page)

In the [`WebHandler` API](#webflux-web-handler-api), you can use a `WebExceptionHandler` to handle
exceptions from the chain of `WebFilter` instances and the target `WebHandler`. When using the[WebFlux Config](#webflux-config), registering a `WebExceptionHandler` is as simple as declaring it as a
Spring bean and (optionally) expressing precedence by using `@Order` on the bean declaration or
by implementing `Ordered`.

The following table describes the available `WebExceptionHandler` implementations:

|           Exception Handler           |                                                                                                                           Description                                                                                                                           |
|---------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|   `ResponseStatusExceptionHandler`    |Provides handling for exceptions of type[`ResponseStatusException`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/ResponseStatusException.html)by setting the response to the HTTP status code of the exception.|
|`WebFluxResponseStatusExceptionHandler`|                 Extension of `ResponseStatusExceptionHandler` that can also determine the HTTP status<br/>code of a `@ResponseStatus` annotation on any exception.<br/><br/> This handler is declared in the [WebFlux Config](#webflux-config).                 |

#### 1.2.5. Codecs

[Web MVC](integration.html#rest-message-conversion)

The `spring-web` and `spring-core` modules provide support for serializing and
deserializing byte content to and from higher level objects through non-blocking I/O with
Reactive Streams back pressure. The following describes this support:

* [`Encoder`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/codec/Encoder.html) and[`Decoder`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/codec/Decoder.html) are low level contracts to
  encode and decode content independent of HTTP.

* [`HttpMessageReader`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/codec/HttpMessageReader.html) and[`HttpMessageWriter`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/codec/HttpMessageWriter.html) are contracts
  to encode and decode HTTP message content.

* An `Encoder` can be wrapped with `EncoderHttpMessageWriter` to adapt it for use in a web
  application, while a `Decoder` can be wrapped with `DecoderHttpMessageReader`.

* [`DataBuffer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/io/buffer/DataBuffer.html) abstracts different
  byte buffer representations (e.g. Netty `ByteBuf`, `java.nio.ByteBuffer`, etc.) and is
  what all codecs work on. See [Data Buffers and Codecs](core.html#databuffers) in the
  "Spring Core" section for more on this topic.

The `spring-core` module provides `byte[]`, `ByteBuffer`, `DataBuffer`, `Resource`, and`String` encoder and decoder implementations. The `spring-web` module provides Jackson
JSON, Jackson Smile, JAXB2, Protocol Buffers and other encoders and decoders along with
web-only HTTP message reader and writer implementations for form data, multipart content,
server-sent events, and others.

`ClientCodecConfigurer` and `ServerCodecConfigurer` are typically used to configure and
customize the codecs to use in an application. See the section on configuring[HTTP message codecs](#webflux-config-message-codecs).

##### Jackson JSON

JSON and binary JSON ([Smile](https://github.com/FasterXML/smile-format-specification)) are
both supported when the Jackson library is present.

The `Jackson2Decoder` works as follows:

* Jackson’s asynchronous, non-blocking parser is used to aggregate a stream of byte chunks
  into `TokenBuffer`'s each representing a JSON object.

* Each `TokenBuffer` is passed to Jackson’s `ObjectMapper` to create a higher level object.

* When decoding to a single-value publisher (e.g. `Mono`), there is one `TokenBuffer`.

* When decoding to a multi-value publisher (e.g. `Flux`), each `TokenBuffer` is passed to
  the `ObjectMapper` as soon as enough bytes are received for a fully formed object. The
  input content can be a JSON array, or any[line-delimited JSON](https://en.wikipedia.org/wiki/JSON_streaming) format such as NDJSON,
  JSON Lines, or JSON Text Sequences.

The `Jackson2Encoder` works as follows:

* For a single value publisher (e.g. `Mono`), simply serialize it through the`ObjectMapper`.

* For a multi-value publisher with `application/json`, by default collect the values with`Flux#collectToList()` and then serialize the resulting collection.

* For a multi-value publisher with a streaming media type such as`application/x-ndjson` or `application/stream+x-jackson-smile`, encode, write, and
  flush each value individually using a[line-delimited JSON](https://en.wikipedia.org/wiki/JSON_streaming) format. Other
  streaming media types may be registered with the encoder.

* For SSE the `Jackson2Encoder` is invoked per event and the output is flushed to ensure
  delivery without delay.

|   |By default both `Jackson2Encoder` and `Jackson2Decoder` do not support elements of type`String`. Instead the default assumption is that a string or a sequence of strings<br/>represent serialized JSON content, to be rendered by the `CharSequenceEncoder`. If what<br/>you need is to render a JSON array from `Flux<String>`, use `Flux#collectToList()` and<br/>encode a `Mono<List<String>>`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

##### Form Data

`FormHttpMessageReader` and `FormHttpMessageWriter` support decoding and encoding`application/x-www-form-urlencoded` content.

On the server side where form content often needs to be accessed from multiple places,`ServerWebExchange` provides a dedicated `getFormData()` method that parses the content
through `FormHttpMessageReader` and then caches the result for repeated access.
See [Form Data](#webflux-form-data) in the [`WebHandler` API](#webflux-web-handler-api) section.

Once `getFormData()` is used, the original raw content can no longer be read from the
request body. For this reason, applications are expected to go through `ServerWebExchange`consistently for access to the cached form data versus reading from the raw request body.

##### Multipart

`MultipartHttpMessageReader` and `MultipartHttpMessageWriter` support decoding and
encoding "multipart/form-data" content. In turn `MultipartHttpMessageReader` delegates to
another `HttpMessageReader` for the actual parsing to a `Flux<Part>` and then simply
collects the parts into a `MultiValueMap`.
By default, the `DefaultPartHttpMessageReader` is used, but this can be changed through the`ServerCodecConfigurer`.
For more information about the `DefaultPartHttpMessageReader`, refer to to the[javadoc of `DefaultPartHttpMessageReader`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.html).

On the server side where multipart form content may need to be accessed from multiple
places, `ServerWebExchange` provides a dedicated `getMultipartData()` method that parses
the content through `MultipartHttpMessageReader` and then caches the result for repeated access.
See [Multipart Data](#webflux-multipart) in the [`WebHandler` API](#webflux-web-handler-api) section.

Once `getMultipartData()` is used, the original raw content can no longer be read from the
request body. For this reason applications have to consistently use `getMultipartData()`for repeated, map-like access to parts, or otherwise rely on the`SynchronossPartHttpMessageReader` for a one-time access to `Flux<Part>`.

##### Limits

`Decoder` and `HttpMessageReader` implementations that buffer some or all of the input
stream can be configured with a limit on the maximum number of bytes to buffer in memory.
In some cases buffering occurs because input is aggregated and represented as a single
object — for example, a controller method with `@RequestBody byte[]`,`x-www-form-urlencoded` data, and so on. Buffering can also occur with streaming, when
splitting the input stream — for example, delimited text, a stream of JSON objects, and
so on. For those streaming cases, the limit applies to the number of bytes associated
with one object in the stream.

To configure buffer sizes, you can check if a given `Decoder` or `HttpMessageReader`exposes a `maxInMemorySize` property and if so the Javadoc will have details about default
values. On the server side, `ServerCodecConfigurer` provides a single place from where to
set all codecs, see [HTTP message codecs](#webflux-config-message-codecs). On the client side, the limit for
all codecs can be changed in[WebClient.Builder](#webflux-client-builder-maxinmemorysize).

For [Multipart parsing](#webflux-codecs-multipart) the `maxInMemorySize` property limits
the size of non-file parts. For file parts, it determines the threshold at which the part
is written to disk. For file parts written to disk, there is an additional`maxDiskUsagePerPart` property to limit the amount of disk space per part. There is also
a `maxParts` property to limit the overall number of parts in a multipart request.
To configure all three in WebFlux, you’ll need to supply a pre-configured instance of`MultipartHttpMessageReader` to `ServerCodecConfigurer`.

##### Streaming

[Web MVC](web.html#mvc-ann-async-http-streaming)

When streaming to the HTTP response (for example, `text/event-stream`,`application/x-ndjson`), it is important to send data periodically, in order to
reliably detect a disconnected client sooner rather than later. Such a send could be a
comment-only, empty SSE event or any other "no-op" data that would effectively serve as
a heartbeat.

##### `DataBuffer`

`DataBuffer` is the representation for a byte buffer in WebFlux. The Spring Core part of
this reference has more on that in the section on[Data Buffers and Codecs](core.html#databuffers). The key point to understand is that on some
servers like Netty, byte buffers are pooled and reference counted, and must be released
when consumed to avoid memory leaks.

WebFlux applications generally do not need to be concerned with such issues, unless they
consume or produce data buffers directly, as opposed to relying on codecs to convert to
and from higher level objects, or unless they choose to create custom codecs. For such
cases please review the information in [Data Buffers and Codecs](core.html#databuffers),
especially the section on [Using DataBuffer](core.html#databuffers-using).

#### 1.2.6. Logging

[Web MVC](web.html#mvc-logging)

`DEBUG` level logging in Spring WebFlux is designed to be compact, minimal, and
human-friendly. It focuses on high value bits of information that are useful over and
over again vs others that are useful only when debugging a specific issue.

`TRACE` level logging generally follows the same principles as `DEBUG` (and for example also
should not be a firehose) but can be used for debugging any issue. In addition, some log
messages may show a different level of detail at `TRACE` vs `DEBUG`.

Good logging comes from the experience of using the logs. If you spot anything that does
not meet the stated goals, please let us know.

##### Log Id

In WebFlux, a single request can be run over multiple threads and the thread ID
is not useful for correlating log messages that belong to a specific request. This is why
WebFlux log messages are prefixed with a request-specific ID by default.

On the server side, the log ID is stored in the `ServerWebExchange` attribute
([`LOG_ID_ATTRIBUTE`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/ServerWebExchange.html#LOG_ID_ATTRIBUTE)),
while a fully formatted prefix based on that ID is available from`ServerWebExchange#getLogPrefix()`. On the `WebClient` side, the log ID is stored in the`ClientRequest` attribute
([`LOG_ID_ATTRIBUTE`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/function/client/ClientRequest.html#LOG_ID_ATTRIBUTE))
,while a fully formatted prefix is available from `ClientRequest#logPrefix()`.

##### Sensitive Data

[Web MVC](web.html#mvc-logging-sensitive-data)

`DEBUG` and `TRACE` logging can log sensitive information. This is why form parameters and
headers are masked by default and you must explicitly enable their logging in full.

The following example shows how to do so for server-side requests:

Java

```
@Configuration
@EnableWebFlux
class MyConfig implements WebFluxConfigurer {

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.defaultCodecs().enableLoggingRequestDetails(true);
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class MyConfig : WebFluxConfigurer {

    override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
        configurer.defaultCodecs().enableLoggingRequestDetails(true)
    }
}
```

The following example shows how to do so for client-side requests:

Java

```
Consumer<ClientCodecConfigurer> consumer = configurer ->
        configurer.defaultCodecs().enableLoggingRequestDetails(true);

WebClient webClient = WebClient.builder()
        .exchangeStrategies(strategies -> strategies.codecs(consumer))
        .build();
```

Kotlin

```
val consumer: (ClientCodecConfigurer) -> Unit  = { configurer -> configurer.defaultCodecs().enableLoggingRequestDetails(true) }

val webClient = WebClient.builder()
        .exchangeStrategies({ strategies -> strategies.codecs(consumer) })
        .build()
```

##### Appenders

Logging libraries such as SLF4J and Log4J 2 provide asynchronous loggers that avoid
blocking. While those have their own drawbacks such as potentially dropping messages
that could not be queued for logging, they are the best available options currently
for use in a reactive, non-blocking application.

##### Custom codecs

Applications can register custom codecs for supporting additional media types,
or specific behaviors that are not supported by the default codecs.

Some configuration options expressed by developers are enforced on default codecs.
Custom codecs might want to get a chance to align with those preferences,
like [enforcing buffering limits](#webflux-codecs-limits)or [logging sensitive data](#webflux-logging-sensitive-data).

The following example shows how to do so for client-side requests:

Java

```
WebClient webClient = WebClient.builder()
        .codecs(configurer -> {
                CustomDecoder decoder = new CustomDecoder();
                configurer.customCodecs().registerWithDefaultConfig(decoder);
        })
        .build();
```

Kotlin

```
val webClient = WebClient.builder()
        .codecs({ configurer ->
                val decoder = CustomDecoder()
                configurer.customCodecs().registerWithDefaultConfig(decoder)
         })
        .build()
```

### 1.3. `DispatcherHandler`

[Web MVC](web.html#mvc-servlet)

Spring WebFlux, similarly to Spring MVC, is designed around the front controller pattern,
where a central `WebHandler`, the `DispatcherHandler`, provides a shared algorithm for
request processing, while actual work is performed by configurable, delegate components.
This model is flexible and supports diverse workflows.

`DispatcherHandler` discovers the delegate components it needs from Spring configuration.
It is also designed to be a Spring bean itself and implements `ApplicationContextAware`for access to the context in which it runs. If `DispatcherHandler` is declared with a bean
name of `webHandler`, it is, in turn, discovered by[`WebHttpHandlerBuilder`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/adapter/WebHttpHandlerBuilder.html),
which puts together a request-processing chain, as described in [`WebHandler` API](#webflux-web-handler-api).

Spring configuration in a WebFlux application typically contains:

* `DispatcherHandler` with the bean name `webHandler`

* `WebFilter` and `WebExceptionHandler` beans

* [`DispatcherHandler` special beans](#webflux-special-bean-types)

* Others

The configuration is given to `WebHttpHandlerBuilder` to build the processing chain,
as the following example shows:

Java

```
ApplicationContext context = ...
HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
```

Kotlin

```
val context: ApplicationContext = ...
val handler = WebHttpHandlerBuilder.applicationContext(context).build()
```

The resulting `HttpHandler` is ready for use with a [server adapter](#webflux-httphandler).

#### 1.3.1. Special Bean Types

[Web MVC](web.html#mvc-servlet-special-bean-types)

The `DispatcherHandler` delegates to special beans to process requests and render the
appropriate responses. By “special beans,” we mean Spring-managed `Object` instances that
implement WebFlux framework contracts. Those usually come with built-in contracts, but
you can customize their properties, extend them, or replace them.

The following table lists the special beans detected by the `DispatcherHandler`. Note that
there are also some other beans detected at a lower level (see[Special bean types](#webflux-web-handler-api-special-beans) in the Web Handler API).

|      Bean type       |                                                                                                                                                                                                                                                   Explanation                                                                                                                                                                                                                                                    |
|----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|   `HandlerMapping`   |Map a request to a handler. The mapping is based on some criteria, the details of<br/>which vary by `HandlerMapping` implementation — annotated controllers, simple<br/>URL pattern mappings, and others.<br/><br/> The main `HandlerMapping` implementations are `RequestMappingHandlerMapping` for`@RequestMapping` annotated methods, `RouterFunctionMapping` for functional endpoint<br/>routes, and `SimpleUrlHandlerMapping` for explicit registrations of URI path patterns<br/>and `WebHandler` instances.|
|   `HandlerAdapter`   |                                                                                                   Help the `DispatcherHandler` to invoke a handler mapped to a request regardless of<br/>how the handler is actually invoked. For example, invoking an annotated controller<br/>requires resolving annotations. The main purpose of a `HandlerAdapter` is to shield the`DispatcherHandler` from such details.                                                                                                    |
|`HandlerResultHandler`|                                                                                                                                                                                          Process the result from the handler invocation and finalize the response.<br/>See [Result Handling](#webflux-resulthandling).                                                                                                                                                                                           |

#### 1.3.2. WebFlux Config

[Web MVC](web.html#mvc-servlet-config)

Applications can declare the infrastructure beans (listed under[Web Handler API](#webflux-web-handler-api-special-beans) and[`DispatcherHandler`](#webflux-special-bean-types)) that are required to process requests.
However, in most cases, the [WebFlux Config](#webflux-config) is the best starting point. It declares the
required beans and provides a higher-level configuration callback API to customize it.

|   |Spring Boot relies on the WebFlux config to configure Spring WebFlux and also provides<br/>many extra convenient options.|
|---|-------------------------------------------------------------------------------------------------------------------------|

#### 1.3.3. Processing

[Web MVC](web.html#mvc-servlet-sequence)

`DispatcherHandler` processes requests as follows:

* Each `HandlerMapping` is asked to find a matching handler, and the first match is used.

* If a handler is found, it is run through an appropriate `HandlerAdapter`, which
  exposes the return value from the execution as `HandlerResult`.

* The `HandlerResult` is given to an appropriate `HandlerResultHandler` to complete
  processing by writing to the response directly or by using a view to render.

#### 1.3.4. Result Handling

The return value from the invocation of a handler, through a `HandlerAdapter`, is wrapped
as a `HandlerResult`, along with some additional context, and passed to the first`HandlerResultHandler` that claims support for it. The following table shows the available`HandlerResultHandler` implementations, all of which are declared in the [WebFlux Config](#webflux-config):

|     Result Handler Type     |                                                                                                                                                                                                                                                            Return Values                                                                                                                                                                                                                                                             |   Default Order   |
|-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------|
|`ResponseEntityResultHandler`|                                                                                                                                                                                                                                      `ResponseEntity`, typically from `@Controller` instances.                                                                                                                                                                                                                                       |         0         |
|`ServerResponseResultHandler`|                                                                                                                                                                                                                                        `ServerResponse`, typically from functional endpoints.                                                                                                                                                                                                                                        |         0         |
| `ResponseBodyResultHandler` |                                                                                                                                                                                                                           Handle return values from `@ResponseBody` methods or `@RestController` classes.                                                                                                                                                                                                                            |        100        |
|`ViewResolutionResultHandler`|`CharSequence`, [`View`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/result/view/View.html),[Model](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/ui/Model.html), `Map`,[Rendering](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/result/view/Rendering.html),<br/>or any other `Object` is treated as a model attribute.<br/><br/> See also [View Resolution](#webflux-viewresolution).|`Integer.MAX_VALUE`|

#### 1.3.5. Exceptions

[Web MVC](web.html#mvc-exceptionhandlers)

The `HandlerResult` returned from a `HandlerAdapter` can expose a function for error
handling based on some handler-specific mechanism. This error function is called if:

* The handler (for example, `@Controller`) invocation fails.

* The handling of the handler return value through a `HandlerResultHandler` fails.

The error function can change the response (for example, to an error status), as long as an error
signal occurs before the reactive type returned from the handler produces any data items.

This is how `@ExceptionHandler` methods in `@Controller` classes are supported.
By contrast, support for the same in Spring MVC is built on a `HandlerExceptionResolver`.
This generally should not matter. However, keep in mind that, in WebFlux, you cannot use a`@ControllerAdvice` to handle exceptions that occur before a handler is chosen.

See also [Managing Exceptions](#webflux-ann-controller-exceptions) in the “Annotated Controller” section or[Exceptions](#webflux-exception-handler) in the WebHandler API section.

#### 1.3.6. View Resolution

[Web MVC](web.html#mvc-viewresolver)

View resolution enables rendering to a browser with an HTML template and a model without
tying you to a specific view technology. In Spring WebFlux, view resolution is
supported through a dedicated [HandlerResultHandler](#webflux-resulthandling) that uses`ViewResolver` instances to map a String (representing a logical view name) to a `View`instance. The `View` is then used to render the response.

##### Handling

[Web MVC](web.html#mvc-handling)

The `HandlerResult` passed into `ViewResolutionResultHandler` contains the return value
from the handler and the model that contains attributes added during request
handling. The return value is processed as one of the following:

* `String`, `CharSequence`: A logical view name to be resolved to a `View` through
  the list of configured `ViewResolver` implementations.

* `void`: Select a default view name based on the request path, minus the leading and
  trailing slash, and resolve it to a `View`. The same also happens when a view name
  was not provided (for example, model attribute was returned) or an async return value
  (for example, `Mono` completed empty).

* [Rendering](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/result/view/Rendering.html): API for
  view resolution scenarios. Explore the options in your IDE with code completion.

* `Model`, `Map`: Extra model attributes to be added to the model for the request.

* Any other: Any other return value (except for simple types, as determined by[BeanUtils#isSimpleProperty](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-))
  is treated as a model attribute to be added to the model. The attribute name is derived
  from the class name by using [conventions](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/Conventions.html),
  unless a handler method `@ModelAttribute` annotation is present.

The model can contain asynchronous, reactive types (for example, from Reactor or RxJava). Prior
to rendering, `AbstractView` resolves such model attributes into concrete values
and updates the model. Single-value reactive types are resolved to a single
value or no value (if empty), while multi-value reactive types (for example, `Flux<T>`) are
collected and resolved to `List<T>`.

To configure view resolution is as simple as adding a `ViewResolutionResultHandler` bean
to your Spring configuration. [WebFlux Config](#webflux-config-view-resolvers) provides a
dedicated configuration API for view resolution.

See [View Technologies](#webflux-view) for more on the view technologies integrated with Spring WebFlux.

##### Redirecting

[Web MVC](web.html#mvc-redirecting-redirect-prefix)

The special `redirect:` prefix in a view name lets you perform a redirect. The`UrlBasedViewResolver` (and sub-classes) recognize this as an instruction that a
redirect is needed. The rest of the view name is the redirect URL.

The net effect is the same as if the controller had returned a `RedirectView` or`Rendering.redirectTo("abc").build()`, but now the controller itself can
operate in terms of logical view names. A view name such as`redirect:/some/resource` is relative to the current application, while a view name such as`redirect:https://example.com/arbitrary/path` redirects to an absolute URL.

##### Content Negotiation

[Web MVC](web.html#mvc-multiple-representations)

`ViewResolutionResultHandler` supports content negotiation. It compares the request
media types with the media types supported by each selected `View`. The first `View`that supports the requested media type(s) is used.

In order to support media types such as JSON and XML, Spring WebFlux provides`HttpMessageWriterView`, which is a special `View` that renders through an[HttpMessageWriter](#webflux-codecs). Typically, you would configure these as default
views through the [WebFlux Configuration](#webflux-config-view-resolvers). Default views are
always selected and used if they match the requested media type.

### 1.4. Annotated Controllers

[Web MVC](web.html#mvc-controller)

Spring WebFlux provides an annotation-based programming model, where `@Controller` and`@RestController` components use annotations to express request mappings, request input,
handle exceptions, and more. Annotated controllers have flexible method signatures and
do not have to extend base classes nor implement specific interfaces.

The following listing shows a basic example:

Java

```
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String handle() {
        return "Hello WebFlux";
    }
}
```

Kotlin

```
@RestController
class HelloController {

    @GetMapping("/hello")
    fun handle() = "Hello WebFlux"
}
```

In the preceding example, the method returns a `String` to be written to the response body.

#### 1.4.1. `@Controller`

[Web MVC](web.html#mvc-ann-controller)

You can define controller beans by using a standard Spring bean definition.
The `@Controller` stereotype allows for auto-detection and is aligned with Spring general support
for detecting `@Component` classes in the classpath and auto-registering bean definitions
for them. It also acts as a stereotype for the annotated class, indicating its role as
a web component.

To enable auto-detection of such `@Controller` beans, you can add component scanning to
your Java configuration, as the following example shows:

Java

```
@Configuration
@ComponentScan("org.example.web") (1)
public class WebConfig {

    // ...
}
```

|**1**|Scan the `org.example.web` package.|
|-----|-----------------------------------|

Kotlin

```
@Configuration
@ComponentScan("org.example.web") (1)
class WebConfig {

    // ...
}
```

|**1**|Scan the `org.example.web` package.|
|-----|-----------------------------------|

`@RestController` is a [composed annotation](core.html#beans-meta-annotations) that is
itself meta-annotated with `@Controller` and `@ResponseBody`, indicating a controller whose
every method inherits the type-level `@ResponseBody` annotation and, therefore, writes
directly to the response body versus view resolution and rendering with an HTML template.

#### 1.4.2. Request Mapping

[Web MVC](web.html#mvc-ann-requestmapping)

The `@RequestMapping` annotation is used to map requests to controllers methods. It has
various attributes to match by URL, HTTP method, request parameters, headers, and media
types. You can use it at the class level to express shared mappings or at the method level
to narrow down to a specific endpoint mapping.

There are also HTTP method specific shortcut variants of `@RequestMapping`:

* `@GetMapping`

* `@PostMapping`

* `@PutMapping`

* `@DeleteMapping`

* `@PatchMapping`

The preceding annotations are [Custom Annotations](#webflux-ann-requestmapping-composed) that are provided
because, arguably, most controller methods should be mapped to a specific HTTP method versus
using `@RequestMapping`, which, by default, matches to all HTTP methods. At the same time, a`@RequestMapping` is still needed at the class level to express shared mappings.

The following example uses type and method level mappings:

Java

```
@RestController
@RequestMapping("/persons")
class PersonController {

    @GetMapping("/{id}")
    public Person getPerson(@PathVariable Long id) {
        // ...
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void add(@RequestBody Person person) {
        // ...
    }
}
```

Kotlin

```
@RestController
@RequestMapping("/persons")
class PersonController {

    @GetMapping("/{id}")
    fun getPerson(@PathVariable id: Long): Person {
        // ...
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    fun add(@RequestBody person: Person) {
        // ...
    }
}
```

##### URI Patterns

[Web MVC](web.html#mvc-ann-requestmapping-uri-templates)

You can map requests by using glob patterns and wildcards:

|    Pattern    |                                              Description                                              |                                                                                      Example                                                                                      |
|---------------|-------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|      `?`      |                                         Matches one character                                         |                                                    `"/pages/t?st.html"` matches `"/pages/test.html"` and `"/pages/t3st.html"`                                                     |
|      `*`      |                         Matches zero or more characters within a path segment                         |`"/resources/*.png"` matches `"/resources/file.png"`<br/><br/>`"/projects/*/versions"` matches `"/projects/spring/versions"` but does not match `"/projects/spring/boot/versions"` |
|     `**`      |                     Matches zero or more path segments until the end of the path                      |`"/resources/**"` matches `"/resources/file.png"` and `"/resources/images/file.png"`<br/><br/>`"/resources/**/file.png"` is invalid as `**` is only allowed at the end of the path.|
|   `{name}`    |                   Matches a path segment and captures it as a variable named "name"                   |                                       `"/projects/{project}/versions"` matches `"/projects/spring/versions"` and captures `project=spring`                                        |
|`{name:[a-z]+}`|                     Matches the regexp `"[a-z]+"` as a path variable named "name"                     |                               `"/projects/{project:[a-z]+}/versions"` matches `"/projects/spring/versions"` but not `"/projects/spring1/versions"`                                |
|   `{*path}`   |Matches zero or more path segments until the end of the path and captures it as a variable named "path"|                                        `"/resources/{*file}"` matches `"/resources/images/file.png"` and captures `file=/images/file.png`                                         |

Captured URI variables can be accessed with `@PathVariable`, as the following example shows:

Java

```
@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
    // ...
}
```

Kotlin

```
@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(@PathVariable ownerId: Long, @PathVariable petId: Long): Pet {
    // ...
}
```

You can declare URI variables at the class and method levels, as the following example shows:

Java

```
@Controller
@RequestMapping("/owners/{ownerId}") (1)
public class OwnerController {

    @GetMapping("/pets/{petId}") (2)
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...
    }
}
```

|**1**|Class-level URI mapping. |
|-----|-------------------------|
|**2**|Method-level URI mapping.|

Kotlin

```
@Controller
@RequestMapping("/owners/{ownerId}") (1)
class OwnerController {

    @GetMapping("/pets/{petId}") (2)
    fun findPet(@PathVariable ownerId: Long, @PathVariable petId: Long): Pet {
        // ...
    }
}
```

|**1**|Class-level URI mapping. |
|-----|-------------------------|
|**2**|Method-level URI mapping.|

URI variables are automatically converted to the appropriate type or a `TypeMismatchException`is raised. Simple types (`int`, `long`, `Date`, and so on) are supported by default and you can
register support for any other data type.
See [Type Conversion](#webflux-ann-typeconversion) and [`DataBinder`](#webflux-ann-initbinder).

URI variables can be named explicitly (for example, `@PathVariable("customId")`), but you can
leave that detail out if the names are the same and you compile your code with debugging
information or with the `-parameters` compiler flag on Java 8.

The syntax `{*varName}` declares a URI variable that matches zero or more remaining path
segments. For example `/resources/{*path}` matches all files under `/resources/`, and the`"path"` variable captures the complete path under `/resources`.

The syntax `{varName:regex}` declares a URI variable with a regular expression that has the
syntax: `{varName:regex}`. For example, given a URL of `/spring-web-3.0.5.jar`, the following method
extracts the name, version, and file extension:

Java

```
@GetMapping("/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
public void handle(@PathVariable String version, @PathVariable String ext) {
    // ...
}
```

Kotlin

```
@GetMapping("/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
fun handle(@PathVariable version: String, @PathVariable ext: String) {
    // ...
}
```

URI path patterns can also have embedded `${…​}` placeholders that are resolved on startup
through `PropertyPlaceHolderConfigurer` against local, system, environment, and other property
sources. You ca use this to, for example, parameterize a base URL based on some external
configuration.

|   |Spring WebFlux uses `PathPattern` and the `PathPatternParser` for URI path matching support.<br/>Both classes are located in `spring-web` and are expressly designed for use with HTTP URL<br/>paths in web applications where a large number of URI path patterns are matched at runtime.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Spring WebFlux does not support suffix pattern matching — unlike Spring MVC, where a
mapping such as `/person` also matches to `/person.*`. For URL-based content
negotiation, if needed, we recommend using a query parameter, which is simpler, more
explicit, and less vulnerable to URL path based exploits.

##### Pattern Comparison

[Web MVC](web.html#mvc-ann-requestmapping-pattern-comparison)

When multiple patterns match a URL, they must be compared to find the best match. This is done
with `PathPattern.SPECIFICITY_COMPARATOR`, which looks for patterns that are more specific.

For every pattern, a score is computed, based on the number of URI variables and wildcards,
where a URI variable scores lower than a wildcard. A pattern with a lower total score
wins. If two patterns have the same score, the longer is chosen.

Catch-all patterns (for example, `**`, `{*varName}`) are excluded from the scoring and are always
sorted last instead. If two patterns are both catch-all, the longer is chosen.

##### Consumable Media Types

[Web MVC](web.html#mvc-ann-requestmapping-consumes)

You can narrow the request mapping based on the `Content-Type` of the request,
as the following example shows:

Java

```
@PostMapping(path = "/pets", consumes = "application/json")
public void addPet(@RequestBody Pet pet) {
    // ...
}
```

Kotlin

```
@PostMapping("/pets", consumes = ["application/json"])
fun addPet(@RequestBody pet: Pet) {
    // ...
}
```

The consumes attribute also supports negation expressions — for example, `!text/plain` means any
content type other than `text/plain`.

You can declare a shared `consumes` attribute at the class level. Unlike most other request
mapping attributes, however, when used at the class level, a method-level `consumes` attribute
overrides rather than extends the class-level declaration.

|   |`MediaType` provides constants for commonly used media types — for example,`APPLICATION_JSON_VALUE` and `APPLICATION_XML_VALUE`.|
|---|--------------------------------------------------------------------------------------------------------------------------------|

##### Producible Media Types

[Web MVC](web.html#mvc-ann-requestmapping-produces)

You can narrow the request mapping based on the `Accept` request header and the list of
content types that a controller method produces, as the following example shows:

Java

```
@GetMapping(path = "/pets/{petId}", produces = "application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId) {
    // ...
}
```

Kotlin

```
@GetMapping("/pets/{petId}", produces = ["application/json"])
@ResponseBody
fun getPet(@PathVariable String petId): Pet {
    // ...
}
```

The media type can specify a character set. Negated expressions are supported — for example,`!text/plain` means any content type other than `text/plain`.

You can declare a shared `produces` attribute at the class level. Unlike most other request
mapping attributes, however, when used at the class level, a method-level `produces` attribute
overrides rather than extend the class level declaration.

|   |`MediaType` provides constants for commonly used media types — e.g.`APPLICATION_JSON_VALUE`, `APPLICATION_XML_VALUE`.|
|---|---------------------------------------------------------------------------------------------------------------------|

##### Parameters and Headers

[Web MVC](web.html#mvc-ann-requestmapping-params-and-headers)

You can narrow request mappings based on query parameter conditions. You can test for the
presence of a query parameter (`myParam`), for its absence (`!myParam`), or for a
specific value (`myParam=myValue`). The following examples tests for a parameter with a value:

Java

```
@GetMapping(path = "/pets/{petId}", params = "myParam=myValue") (1)
public void findPet(@PathVariable String petId) {
    // ...
}
```

|**1**|Check that `myParam` equals `myValue`.|
|-----|--------------------------------------|

Kotlin

```
@GetMapping("/pets/{petId}", params = ["myParam=myValue"]) (1)
fun findPet(@PathVariable petId: String) {
    // ...
}
```

|**1**|Check that `myParam` equals `myValue`.|
|-----|--------------------------------------|

You can also use the same with request header conditions, as the follwing example shows:

Java

```
@GetMapping(path = "/pets", headers = "myHeader=myValue") (1)
public void findPet(@PathVariable String petId) {
    // ...
}
```

|**1**|Check that `myHeader` equals `myValue`.|
|-----|---------------------------------------|

Kotlin

```
@GetMapping("/pets", headers = ["myHeader=myValue"]) (1)
fun findPet(@PathVariable petId: String) {
    // ...
}
```

|**1**|Check that `myHeader` equals `myValue`.|
|-----|---------------------------------------|

##### HTTP HEAD, OPTIONS

[Web MVC](web.html#mvc-ann-requestmapping-head-options)

`@GetMapping` and `@RequestMapping(method=HttpMethod.GET)` support HTTP HEAD
transparently for request mapping purposes. Controller methods need not change.
A response wrapper, applied in the `HttpHandler` server adapter, ensures a `Content-Length`header is set to the number of bytes written without actually writing to the response.

By default, HTTP OPTIONS is handled by setting the `Allow` response header to the list of HTTP
methods listed in all `@RequestMapping` methods with matching URL patterns.

For a `@RequestMapping` without HTTP method declarations, the `Allow` header is set to`GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS`. Controller methods should always declare the
supported HTTP methods (for example, by using the HTTP method specific variants — `@GetMapping`, `@PostMapping`, and others).

You can explicitly map a `@RequestMapping` method to HTTP HEAD and HTTP OPTIONS, but that
is not necessary in the common case.

##### Custom Annotations

[Web MVC](web.html#mvc-ann-requestmapping-composed)

Spring WebFlux supports the use of [composed annotations](core.html#beans-meta-annotations)for request mapping. Those are annotations that are themselves meta-annotated with`@RequestMapping` and composed to redeclare a subset (or all) of the `@RequestMapping`attributes with a narrower, more specific purpose.

`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, and `@PatchMapping` are
examples of composed annotations. They are provided, because, arguably, most
controller methods should be mapped to a specific HTTP method versus using `@RequestMapping`,
which, by default, matches to all HTTP methods. If you need an example of composed
annotations, look at how those are declared.

Spring WebFlux also supports custom request mapping attributes with custom request matching
logic. This is a more advanced option that requires sub-classing`RequestMappingHandlerMapping` and overriding the `getCustomMethodCondition` method, where
you can check the custom attribute and return your own `RequestCondition`.

##### Explicit Registrations

[Web MVC](web.html#mvc-ann-requestmapping-registration)

You can programmatically register Handler methods, which can be used for dynamic
registrations or for advanced cases, such as different instances of the same handler
under different URLs. The following example shows how to do so:

Java

```
@Configuration
public class MyConfig {

    @Autowired
    public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) (1)
            throws NoSuchMethodException {

        RequestMappingInfo info = RequestMappingInfo
                .paths("/user/{id}").methods(RequestMethod.GET).build(); (2)

        Method method = UserHandler.class.getMethod("getUser", Long.class); (3)

        mapping.registerMapping(info, handler, method); (4)
    }

}
```

|**1**|Inject target handlers and the handler mapping for controllers.|
|-----|---------------------------------------------------------------|
|**2**|             Prepare the request mapping metadata.             |
|**3**|                    Get the handler method.                    |
|**4**|                     Add the registration.                     |

Kotlin

```
@Configuration
class MyConfig {

    @Autowired
    fun setHandlerMapping(mapping: RequestMappingHandlerMapping, handler: UserHandler) { (1)

        val info = RequestMappingInfo.paths("/user/{id}").methods(RequestMethod.GET).build() (2)

        val method = UserHandler::class.java.getMethod("getUser", Long::class.java) (3)

        mapping.registerMapping(info, handler, method) (4)
    }
}
```

|**1**|Inject target handlers and the handler mapping for controllers.|
|-----|---------------------------------------------------------------|
|**2**|             Prepare the request mapping metadata.             |
|**3**|                    Get the handler method.                    |
|**4**|                     Add the registration.                     |

#### 1.4.3. Handler Methods

[Web MVC](web.html#mvc-ann-methods)

`@RequestMapping` handler methods have a flexible signature and can choose from a range of
supported controller method arguments and return values.

##### Method Arguments

[Web MVC](web.html#mvc-ann-arguments)

The following table shows the supported controller method arguments.

Reactive types (Reactor, RxJava, [or other](#webflux-reactive-libraries)) are
supported on arguments that require blocking I/O (for example, reading the request body) to
be resolved. This is marked in the Description column. Reactive types are not expected
on arguments that do not require blocking.

JDK 1.8’s `java.util.Optional` is supported as a method argument in combination with
annotations that have a `required` attribute (for example, `@RequestParam`, `@RequestHeader`,
and others) and is equivalent to `required=false`.

|                              Controller method argument                               |                                                                                                                                                                                                                    Description                                                                                                                                                                                                                    |
|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|                                  `ServerWebExchange`                                  |                                                                                                                                         Access to the full `ServerWebExchange` — container for the HTTP request and response,<br/>request and session attributes, `checkNotModified` methods, and others.                                                                                                                                         |
|                       `ServerHttpRequest`, `ServerHttpResponse`                       |                                                                                                                                                                                                      Access to the HTTP request or response.                                                                                                                                                                                                      |
|                                     `WebSession`                                      |                                                                                                                                                          Access to the session. This does not force the start of a new session unless attributes<br/>are added. Supports reactive types.                                                                                                                                                          |
|                               `java.security.Principal`                               |                                                                                                                                                          The currently authenticated user — possibly a specific `Principal` implementation class if known.<br/>Supports reactive types.                                                                                                                                                           |
|                         `org.springframework.http.HttpMethod`                         |                                                                                                                                                                                                          The HTTP method of the request.                                                                                                                                                                                                          |
|                                  `java.util.Locale`                                   |                                                                                                                                         The current request locale, determined by the most specific `LocaleResolver` available — in<br/>effect, the configured `LocaleResolver`/`LocaleContextResolver`.                                                                                                                                          |
|                       `java.util.TimeZone` + `java.time.ZoneId`                       |                                                                                                                                                                          The time zone associated with the current request, as determined by a `LocaleContextResolver`.                                                                                                                                                                           |
|                                    `@PathVariable`                                    |                                                                                                                                                                       For access to URI template variables. See [URI Patterns](#webflux-ann-requestmapping-uri-templates).                                                                                                                                                                        |
|                                   `@MatrixVariable`                                   |                                                                                                                                                                    For access to name-value pairs in URI path segments. See [Matrix Variables](#webflux-ann-matrix-variables).                                                                                                                                                                    |
|                                    `@RequestParam`                                    |                                                                For access to Servlet request parameters. Parameter values are converted to the declared<br/>method argument type. See [`@RequestParam`](#webflux-ann-requestparam).<br/><br/> Note that use of `@RequestParam` is optional — for example, to set its attributes.<br/>See “Any other argument” later in this table.                                                                |
|                                   `@RequestHeader`                                    |                                                                                                                                             For access to request headers. Header values are converted to the declared method argument<br/>type. See [`@RequestHeader`](#webflux-ann-requestheader).                                                                                                                                              |
|                                    `@CookieValue`                                     |                                                                                                                                                   For access to cookies. Cookie values are converted to the declared method argument type.<br/>See [`@CookieValue`](#webflux-ann-cookievalue).                                                                                                                                                    |
|                                    `@RequestBody`                                     |                                                                                                           For access to the HTTP request body. Body content is converted to the declared method<br/>argument type by using `HttpMessageReader` instances. Supports reactive types.<br/>See [`@RequestBody`](#webflux-ann-requestbody).                                                                                                            |
|                                    `HttpEntity<B>`                                    |                                                                                                                                    For access to request headers and body. The body is converted with `HttpMessageReader` instances.<br/>Supports reactive types. See [`HttpEntity`](#webflux-ann-httpentity).                                                                                                                                    |
|                                    `@RequestPart`                                     |                                                                                                                                 For access to a part in a `multipart/form-data` request. Supports reactive types.<br/>See [Multipart Content](#webflux-multipart-forms) and [Multipart Data](#webflux-multipart).                                                                                                                                 |
|`java.util.Map`, `org.springframework.ui.Model`, and `org.springframework.ui.ModelMap`.|                                                                                                                                                                For access to the model that is used in HTML controllers and is exposed to templates as<br/>part of view rendering.                                                                                                                                                                |
|                                   `@ModelAttribute`                                   |For access to an existing attribute in the model (instantiated if not present) with<br/>data binding and validation applied. See [`@ModelAttribute`](#webflux-ann-modelattrib-method-args) as well<br/>as [`Model`](#webflux-ann-modelattrib-methods) and [`DataBinder`](#webflux-ann-initbinder).<br/><br/> Note that use of `@ModelAttribute` is optional — for example, to set its attributes.<br/>See “Any other argument” later in this table.|
|                               `Errors`, `BindingResult`                               |                                                                                                           For access to errors from validation and data binding for a command object, i.e. a`@ModelAttribute` argument. An `Errors`, or `BindingResult` argument must be declared<br/>immediately after the validated method argument.                                                                                                            |
|                  `SessionStatus` + class-level `@SessionAttributes`                   |                                                                                                      For marking form processing complete, which triggers cleanup of session attributes<br/>declared through a class-level `@SessionAttributes` annotation.<br/>See [`@SessionAttributes`](#webflux-ann-sessionattributes) for more details.                                                                                                      |
|                                `UriComponentsBuilder`                                 |                                                                                                                                                      For preparing a URL relative to the current request’s host, port, scheme, and<br/>context path. See [URI Links](#webflux-uri-building).                                                                                                                                                      |
|                                  `@SessionAttribute`                                  |                                                                                                     For access to any session attribute — in contrast to model attributes stored in the session<br/>as a result of a class-level `@SessionAttributes` declaration. See[`@SessionAttribute`](#webflux-ann-sessionattribute) for more details.                                                                                                      |
|                                  `@RequestAttribute`                                  |                                                                                                                                                                     For access to request attributes. See [`@RequestAttribute`](#webflux-ann-requestattrib) for more details.                                                                                                                                                                     |
|                                  Any other argument                                   |                                     If a method argument is not matched to any of the above, it is, by default, resolved as<br/>a `@RequestParam` if it is a simple type, as determined by[BeanUtils#isSimpleProperty](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-),<br/>or as a `@ModelAttribute`, otherwise.                                     |

##### Return Values

[Web MVC](web.html#mvc-ann-return-types)

The following table shows the supported controller method return values. Note that reactive
types from libraries such as Reactor, RxJava, [or other](#webflux-reactive-libraries) are
generally supported for all return values.

|                        Controller method return value                        |                                                                                                                                                                                                                                                                                                                         Description                                                                                                                                                                                                                                                                                                                         |
|------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|                               `@ResponseBody`                                |                                                                                                                                                                                                                                                    The return value is encoded through `HttpMessageWriter` instances and written to the response.<br/>See [`@ResponseBody`](#webflux-ann-responsebody).                                                                                                                                                                                                                                                     |
|                     `HttpEntity<B>`, `ResponseEntity<B>`                     |                                                                                                                                                                                                                The return value specifies the full response, including HTTP headers, and the body is encoded<br/>through `HttpMessageWriter` instances and written to the response.<br/>See [`ResponseEntity`](#webflux-ann-responseentity).                                                                                                                                                                                                                |
|                                `HttpHeaders`                                 |                                                                                                                                                                                                                                                                                                     For returning a response with headers and no body.                                                                                                                                                                                                                                                                                                      |
|                                   `String`                                   |                                                                                                                                                          A view name to be resolved with `ViewResolver` instances and used together with the implicit<br/>model — determined through command objects and `@ModelAttribute` methods. The handler<br/>method can also programmatically enrich the model by declaring a `Model` argument<br/>(described [earlier](#webflux-viewresolution-handling)).                                                                                                                                                          |
|                                    `View`                                    |                                                                                                                                                                       A `View` instance to use for rendering together with the implicit model — determined<br/>through command objects and `@ModelAttribute` methods. The handler method can also<br/>programmatically enrich the model by declaring a `Model` argument<br/>(described [earlier](#webflux-viewresolution-handling)).                                                                                                                                                                        |
|               `java.util.Map`, `org.springframework.ui.Model`                |                                                                                                                                                                                                                                                                    Attributes to be added to the implicit model, with the view name implicitly determined<br/>based on the request path.                                                                                                                                                                                                                                                                    |
|                              `@ModelAttribute`                               |                                                                                                                                                                                                                   An attribute to be added to the model, with the view name implicitly determined based<br/>on the request path.<br/><br/> Note that `@ModelAttribute` is optional. See “Any other return value” later in<br/>this table.                                                                                                                                                                                                                   |
|                                 `Rendering`                                  |                                                                                                                                                                                                                                                                                                       An API for model and view rendering scenarios.                                                                                                                                                                                                                                                                                                        |
|                                    `void`                                    |A method with a `void`, possibly asynchronous (for example, `Mono<Void>`), return type (or a `null` return<br/>value) is considered to have fully handled the response if it also has a `ServerHttpResponse`,<br/>a `ServerWebExchange` argument, or an `@ResponseStatus` annotation. The same is also true<br/>if the controller has made a positive ETag or `lastModified` timestamp check.<br/>// TODO: See [Controllers](#webflux-caching-etag-lastmodified) for details.<br/><br/> If none of the above is true, a `void` return type can also indicate “no response body” for<br/>REST controllers or default view name selection for HTML controllers.|
|`Flux<ServerSentEvent>`, `Observable<ServerSentEvent>`, or other reactive type|                                                                                                                                                                                                               Emit server-sent events. The `ServerSentEvent` wrapper can be omitted when only data needs<br/>to be written (however, `text/event-stream` must be requested or declared in the mapping<br/>through the `produces` attribute).                                                                                                                                                                                                                |
|                            Any other return value                            |                                                                                If a return value is not matched to any of the above, it is, by default, treated as a view<br/>name, if it is `String` or `void` (default view name selection applies), or as a model<br/>attribute to be added to the model, unless it is a simple type, as determined by[BeanUtils#isSimpleProperty](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-),<br/>in which case it remains unresolved.                                                                                 |

##### Type Conversion

[Web MVC](web.html#mvc-ann-typeconversion)

Some annotated controller method arguments that represent String-based request input (for example,`@RequestParam`, `@RequestHeader`, `@PathVariable`, `@MatrixVariable`, and `@CookieValue`)
can require type conversion if the argument is declared as something other than `String`.

For such cases, type conversion is automatically applied based on the configured converters.
By default, simple types (such as `int`, `long`, `Date`, and others) are supported. Type conversion
can be customized through a `WebDataBinder` (see [`DataBinder`](#webflux-ann-initbinder)) or by registering`Formatters` with the `FormattingConversionService` (see [Spring Field Formatting](core.html#format)).

A practical issue in type conversion is the treatment of an empty String source value.
Such a value is treated as missing if it becomes `null` as a result of type conversion.
This can be the case for `Long`, `UUID`, and other target types. If you want to allow `null`to be injected, either use the `required` flag on the argument annotation, or declare the
argument as `@Nullable`.

##### Matrix Variables

[Web MVC](web.html#mvc-ann-matrix-variables)

[RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.3) discusses name-value pairs in
path segments. In Spring WebFlux, we refer to those as “matrix variables” based on an[“old post”](https://www.w3.org/DesignIssues/MatrixURIs.html) by Tim Berners-Lee, but they
can be also be referred to as URI path parameters.

Matrix variables can appear in any path segment, with each variable separated by a semicolon and
multiple values separated by commas — for example, `"/cars;color=red,green;year=2012"`. Multiple
values can also be specified through repeated variable names — for example,`"color=red;color=green;color=blue"`.

Unlike Spring MVC, in WebFlux, the presence or absence of matrix variables in a URL does
not affect request mappings. In other words, you are not required to use a URI variable
to mask variable content. That said, if you want to access matrix variables from a
controller method, you need to add a URI variable to the path segment where matrix
variables are expected. The following example shows how to do so:

Java

```
// GET /pets/42;q=11;r=22

@GetMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {

    // petId == 42
    // q == 11
}
```

Kotlin

```
// GET /pets/42;q=11;r=22

@GetMapping("/pets/{petId}")
fun findPet(@PathVariable petId: String, @MatrixVariable q: Int) {

    // petId == 42
    // q == 11
}
```

Given that all path segments can contain matrix variables, you may sometimes need to
disambiguate which path variable the matrix variable is expected to be in,
as the following example shows:

Java

```
// GET /owners/42;q=11/pets/21;q=22

@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
        @MatrixVariable(name="q", pathVar="ownerId") int q1,
        @MatrixVariable(name="q", pathVar="petId") int q2) {

    // q1 == 11
    // q2 == 22
}
```

Kotlin

```
@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(
        @MatrixVariable(name = "q", pathVar = "ownerId") q1: Int,
        @MatrixVariable(name = "q", pathVar = "petId") q2: Int) {

    // q1 == 11
    // q2 == 22
}
```

You can define a matrix variable may be defined as optional and specify a default value
as the following example shows:

Java

```
// GET /pets/42

@GetMapping("/pets/{petId}")
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {

    // q == 1
}
```

Kotlin

```
// GET /pets/42

@GetMapping("/pets/{petId}")
fun findPet(@MatrixVariable(required = false, defaultValue = "1") q: Int) {

    // q == 1
}
```

To get all matrix variables, use a `MultiValueMap`, as the following example shows:

Java

```
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23

@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
        @MatrixVariable MultiValueMap<String, String> matrixVars,
        @MatrixVariable(pathVar="petId") MultiValueMap<String, String> petMatrixVars) {

    // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
    // petMatrixVars: ["q" : 22, "s" : 23]
}
```

Kotlin

```
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23

@GetMapping("/owners/{ownerId}/pets/{petId}")
fun findPet(
        @MatrixVariable matrixVars: MultiValueMap<String, String>,
        @MatrixVariable(pathVar="petId") petMatrixVars: MultiValueMap<String, String>) {

    // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
    // petMatrixVars: ["q" : 22, "s" : 23]
}
```

##### `@RequestParam`

[Web MVC](web.html#mvc-ann-requestparam)

You can use the `@RequestParam` annotation to bind query parameters to a method argument in a
controller. The following code snippet shows the usage:

Java

```
@Controller
@RequestMapping("/pets")
public class EditPetForm {

    // ...

    @GetMapping
    public String setupForm(@RequestParam("petId") int petId, Model model) { (1)
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

    // ...
}
```

|**1**|Using `@RequestParam`.|
|-----|----------------------|

Kotlin

```
import org.springframework.ui.set

@Controller
@RequestMapping("/pets")
class EditPetForm {

    // ...

    @GetMapping
    fun setupForm(@RequestParam("petId") petId: Int, model: Model): String { (1)
        val pet = clinic.loadPet(petId)
        model["pet"] = pet
        return "petForm"
    }

    // ...
}
```

|**1**|Using `@RequestParam`.|
|-----|----------------------|

|   |The Servlet API “request parameter” concept conflates query parameters, form<br/>data, and multiparts into one. However, in WebFlux, each is accessed individually through`ServerWebExchange`. While `@RequestParam` binds to query parameters only, you can use<br/>data binding to apply query parameters, form data, and multiparts to a[command object](#webflux-ann-modelattrib-method-args).|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Method parameters that use the `@RequestParam` annotation are required by default, but
you can specify that a method parameter is optional by setting the required flag of a `@RequestParam`to `false` or by declaring the argument with a `java.util.Optional`wrapper.

Type conversion is applied automatically if the target method parameter type is not`String`. See [Type Conversion](#webflux-ann-typeconversion).

When a `@RequestParam` annotation is declared on a `Map<String, String>` or`MultiValueMap<String, String>` argument, the map is populated with all query parameters.

Note that use of `@RequestParam` is optional — for example, to set its attributes. By
default, any argument that is a simple value type (as determined by[BeanUtils#isSimpleProperty](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-))
and is not resolved by any other argument resolver is treated as if it were annotated
with `@RequestParam`.

##### `@RequestHeader`

[Web MVC](web.html#mvc-ann-requestheader)

You can use the `@RequestHeader` annotation to bind a request header to a method argument in a
controller.

The following example shows a request with headers:

```
Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300
```

The following example gets the value of the `Accept-Encoding` and `Keep-Alive` headers:

Java

```
@GetMapping("/demo")
public void handle(
        @RequestHeader("Accept-Encoding") String encoding, (1)
        @RequestHeader("Keep-Alive") long keepAlive) { (2)
    //...
}
```

|**1**|Get the value of the `Accept-Encoging` header.|
|-----|----------------------------------------------|
|**2**|  Get the value of the `Keep-Alive` header.   |

Kotlin

```
@GetMapping("/demo")
fun handle(
        @RequestHeader("Accept-Encoding") encoding: String, (1)
        @RequestHeader("Keep-Alive") keepAlive: Long) { (2)
    //...
}
```

|**1**|Get the value of the `Accept-Encoging` header.|
|-----|----------------------------------------------|
|**2**|  Get the value of the `Keep-Alive` header.   |

Type conversion is applied automatically if the target method parameter type is not`String`. See [Type Conversion](#webflux-ann-typeconversion).

When a `@RequestHeader` annotation is used on a `Map<String, String>`,`MultiValueMap<String, String>`, or `HttpHeaders` argument, the map is populated
with all header values.

|   |Built-in support is available for converting a comma-separated string into an<br/>array or collection of strings or other types known to the type conversion system. For<br/>example, a method parameter annotated with `@RequestHeader("Accept")` may be of type`String` but also of `String[]` or `List<String>`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

##### `@CookieValue`

[Web MVC](web.html#mvc-ann-cookievalue)

You can use the `@CookieValue` annotation to bind the value of an HTTP cookie to a method argument
in a controller.

The following example shows a request with a cookie:

```
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
```

The following code sample demonstrates how to get the cookie value:

Java

```
@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) { (1)
    //...
}
```

|**1**|Get the cookie value.|
|-----|---------------------|

Kotlin

```
@GetMapping("/demo")
fun handle(@CookieValue("JSESSIONID") cookie: String) { (1)
    //...
}
```

|**1**|Get the cookie value.|
|-----|---------------------|

Type conversion is applied automatically if the target method parameter type is not`String`. See [Type Conversion](#webflux-ann-typeconversion).

##### `@ModelAttribute`

[Web MVC](web.html#mvc-ann-modelattrib-method-args)

You can use the `@ModelAttribute` annotation on a method argument to access an attribute from the
model or have it instantiated if not present. The model attribute is also overlaid with
the values of query parameters and form fields whose names match to field names. This is
referred to as data binding, and it saves you from having to deal with parsing and
converting individual query parameters and form fields. The following example binds an instance of `Pet`:

Java

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute Pet pet) { } (1)
```

|**1**|Bind an instance of `Pet`.|
|-----|--------------------------|

Kotlin

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@ModelAttribute pet: Pet): String { } (1)
```

|**1**|Bind an instance of `Pet`.|
|-----|--------------------------|

The `Pet` instance in the preceding example is resolved as follows:

* From the model if already added through [`Model`](#webflux-ann-modelattrib-methods).

* From the HTTP session through [`@SessionAttributes`](#webflux-ann-sessionattributes).

* From the invocation of a default constructor.

* From the invocation of a “primary constructor” with arguments that match query
  parameters or form fields. Argument names are determined through JavaBeans`@ConstructorProperties` or through runtime-retained parameter names in the bytecode.

After the model attribute instance is obtained, data binding is applied. The`WebExchangeDataBinder` class matches names of query parameters and form fields to field
names on the target `Object`. Matching fields are populated after type conversion is applied
where necessary. For more on data binding (and validation), see[Validation](core.html#validation). For more on customizing data binding, see[`DataBinder`](#webflux-ann-initbinder).

Data binding can result in errors. By default, a `WebExchangeBindException` is raised, but,
to check for such errors in the controller method, you can add a `BindingResult` argument
immediately next to the `@ModelAttribute`, as the following example shows:

Java

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) { (1)
    if (result.hasErrors()) {
        return "petForm";
    }
    // ...
}
```

|**1**|Adding a `BindingResult`.|
|-----|-------------------------|

Kotlin

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1)
    if (result.hasErrors()) {
        return "petForm"
    }
    // ...
}
```

|**1**|Adding a `BindingResult`.|
|-----|-------------------------|

You can automatically apply validation after data binding by adding the`javax.validation.Valid` annotation or Spring’s `@Validated` annotation (see also[Bean Validation](core.html#validation-beanvalidation) and[Spring validation](core.html#validation)). The following example uses the `@Valid` annotation:

Java

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result) { (1)
    if (result.hasErrors()) {
        return "petForm";
    }
    // ...
}
```

|**1**|Using `@Valid` on a model attribute argument.|
|-----|---------------------------------------------|

Kotlin

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@Valid @ModelAttribute("pet") pet: Pet, result: BindingResult): String { (1)
    if (result.hasErrors()) {
        return "petForm"
    }
    // ...
}
```

|**1**|Using `@Valid` on a model attribute argument.|
|-----|---------------------------------------------|

Spring WebFlux, unlike Spring MVC, supports reactive types in the model — for example,`Mono<Account>` or `io.reactivex.Single<Account>`. You can declare a `@ModelAttribute` argument
with or without a reactive type wrapper, and it will be resolved accordingly,
to the actual value if necessary. However, note that, to use a `BindingResult`argument, you must declare the `@ModelAttribute` argument before it without a reactive
type wrapper, as shown earlier. Alternatively, you can handle any errors through the
reactive type, as the following example shows:

Java

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public Mono<String> processSubmit(@Valid @ModelAttribute("pet") Mono<Pet> petMono) {
    return petMono
        .flatMap(pet -> {
            // ...
        })
        .onErrorResume(ex -> {
            // ...
        });
}
```

Kotlin

```
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
fun processSubmit(@Valid @ModelAttribute("pet") petMono: Mono<Pet>): Mono<String> {
    return petMono
            .flatMap { pet ->
                // ...
            }
            .onErrorResume{ ex ->
                // ...
            }
}
```

Note that use of `@ModelAttribute` is optional — for example, to set its attributes.
By default, any argument that is not a simple value type( as determined by[BeanUtils#isSimpleProperty](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-))
and is not resolved by any other argument resolver is treated as if it were annotated
with `@ModelAttribute`.

##### `@SessionAttributes`

[Web MVC](web.html#mvc-ann-sessionattributes)

`@SessionAttributes` is used to store model attributes in the `WebSession` between
requests. It is a type-level annotation that declares session attributes used by a
specific controller. This typically lists the names of model attributes or types of
model attributes that should be transparently stored in the session for subsequent
requests to access.

Consider the following example:

Java

```
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {
    // ...
}
```

|**1**|Using the `@SessionAttributes` annotation.|
|-----|------------------------------------------|

Kotlin

```
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {
    // ...
}
```

|**1**|Using the `@SessionAttributes` annotation.|
|-----|------------------------------------------|

On the first request, when a model attribute with the name, `pet`, is added to the model,
it is automatically promoted to and saved in the `WebSession`. It remains there until
another controller method uses a `SessionStatus` method argument to clear the storage,
as the following example shows:

Java

```
@Controller
@SessionAttributes("pet") (1)
public class EditPetForm {

    // ...

    @PostMapping("/pets/{id}")
    public String handle(Pet pet, BindingResult errors, SessionStatus status) { (2)
        if (errors.hasErrors()) {
            // ...
        }
            status.setComplete();
            // ...
        }
    }
}
```

|**1**|Using the `@SessionAttributes` annotation.|
|-----|------------------------------------------|
|**2**|    Using a `SessionStatus` variable.     |

Kotlin

```
@Controller
@SessionAttributes("pet") (1)
class EditPetForm {

    // ...

    @PostMapping("/pets/{id}")
    fun handle(pet: Pet, errors: BindingResult, status: SessionStatus): String { (2)
        if (errors.hasErrors()) {
            // ...
        }
        status.setComplete()
        // ...
    }
}
```

|**1**|Using the `@SessionAttributes` annotation.|
|-----|------------------------------------------|
|**2**|    Using a `SessionStatus` variable.     |

##### `@SessionAttribute`

[Web MVC](web.html#mvc-ann-sessionattribute)

If you need access to pre-existing session attributes that are managed globally
(that is, outside the controller — for example, by a filter) and may or may not be present,
you can use the `@SessionAttribute` annotation on a method parameter, as the following example shows:

Java

```
@GetMapping("/")
public String handle(@SessionAttribute User user) { (1)
    // ...
}
```

|**1**|Using `@SessionAttribute`.|
|-----|--------------------------|

Kotlin

```
@GetMapping("/")
fun handle(@SessionAttribute user: User): String { (1)
    // ...
}
```

|**1**|Using `@SessionAttribute`.|
|-----|--------------------------|

For use cases that require adding or removing session attributes, consider injecting`WebSession` into the controller method.

For temporary storage of model attributes in the session as part of a controller
workflow, consider using `SessionAttributes`, as described in[`@SessionAttributes`](#webflux-ann-sessionattributes).

##### `@RequestAttribute`

[Web MVC](web.html#mvc-ann-requestattrib)

Similarly to `@SessionAttribute`, you can use the `@RequestAttribute` annotation to
access pre-existing request attributes created earlier (for example, by a `WebFilter`),
as the following example shows:

Java

```
@GetMapping("/")
public String handle(@RequestAttribute Client client) { (1)
    // ...
}
```

|**1**|Using `@RequestAttribute`.|
|-----|--------------------------|

Kotlin

```
@GetMapping("/")
fun handle(@RequestAttribute client: Client): String { (1)
    // ...
}
```

|**1**|Using `@RequestAttribute`.|
|-----|--------------------------|

##### Multipart Content

[Web MVC](web.html#mvc-multipart-forms)

As explained in [Multipart Data](#webflux-multipart), `ServerWebExchange` provides access to multipart
content. The best way to handle a file upload form (for example, from a browser) in a controller
is through data binding to a [command object](#webflux-ann-modelattrib-method-args),
as the following example shows:

Java

```
class MyForm {

    private String name;

    private MultipartFile file;

    // ...

}

@Controller
public class FileUploadController {

    @PostMapping("/form")
    public String handleFormUpload(MyForm form, BindingResult errors) {
        // ...
    }

}
```

Kotlin

```
class MyForm(
        val name: String,
        val file: MultipartFile)

@Controller
class FileUploadController {

    @PostMapping("/form")
    fun handleFormUpload(form: MyForm, errors: BindingResult): String {
        // ...
    }

}
```

You can also submit multipart requests from non-browser clients in a RESTful service
scenario. The following example uses a file along with JSON:

```
POST /someUrl
Content-Type: multipart/mixed

--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="meta-data"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit

{
    "name": "value"
}
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="file-data"; filename="file.properties"
Content-Type: text/xml
Content-Transfer-Encoding: 8bit
... File Data ...
```

You can access individual parts with `@RequestPart`, as the following example shows:

Java

```
@PostMapping("/")
public String handle(@RequestPart("meta-data") Part metadata, (1)
        @RequestPart("file-data") FilePart file) { (2)
    // ...
}
```

|**1**|Using `@RequestPart` to get the metadata.|
|-----|-----------------------------------------|
|**2**|  Using `@RequestPart` to get the file.  |

Kotlin

```
@PostMapping("/")
fun handle(@RequestPart("meta-data") Part metadata, (1)
        @RequestPart("file-data") FilePart file): String { (2)
    // ...
}
```

|**1**|Using `@RequestPart` to get the metadata.|
|-----|-----------------------------------------|
|**2**|  Using `@RequestPart` to get the file.  |

To deserialize the raw part content (for example, to JSON — similar to `@RequestBody`),
you can declare a concrete target `Object`, instead of `Part`, as the following example shows:

Java

```
@PostMapping("/")
public String handle(@RequestPart("meta-data") MetaData metadata) { (1)
    // ...
}
```

|**1**|Using `@RequestPart` to get the metadata.|
|-----|-----------------------------------------|

Kotlin

```
@PostMapping("/")
fun handle(@RequestPart("meta-data") metadata: MetaData): String { (1)
    // ...
}
```

|**1**|Using `@RequestPart` to get the metadata.|
|-----|-----------------------------------------|

You can use `@RequestPart` in combination with `javax.validation.Valid` or Spring’s`@Validated` annotation, which causes Standard Bean Validation to be applied. Validation
errors lead to a `WebExchangeBindException` that results in a 400 (BAD\_REQUEST) response.
The exception contains a `BindingResult` with the error details and can also be handled
in the controller method by declaring the argument with an async wrapper and then using
error related operators:

Java

```
@PostMapping("/")
public String handle(@Valid @RequestPart("meta-data") Mono<MetaData> metadata) {
    // use one of the onError* operators...
}
```

Kotlin

```
@PostMapping("/")
fun handle(@Valid @RequestPart("meta-data") metadata: MetaData): String {
    // ...
}
```

To access all multipart data as a `MultiValueMap`, you can use `@RequestBody`,
as the following example shows:

Java

```
@PostMapping("/")
public String handle(@RequestBody Mono<MultiValueMap<String, Part>> parts) { (1)
    // ...
}
```

|**1**|Using `@RequestBody`.|
|-----|---------------------|

Kotlin

```
@PostMapping("/")
fun handle(@RequestBody parts: MultiValueMap<String, Part>): String { (1)
    // ...
}
```

|**1**|Using `@RequestBody`.|
|-----|---------------------|

To access multipart data sequentially, in streaming fashion, you can use `@RequestBody` with`Flux<Part>` (or `Flow<Part>` in Kotlin) instead, as the following example shows:

Java

```
@PostMapping("/")
public String handle(@RequestBody Flux<Part> parts) { (1)
    // ...
}
```

|**1**|Using `@RequestBody`.|
|-----|---------------------|

Kotlin

```
@PostMapping("/")
fun handle(@RequestBody parts: Flow<Part>): String { (1)
    // ...
}
```

|**1**|Using `@RequestBody`.|
|-----|---------------------|

##### `@RequestBody`

[Web MVC](web.html#mvc-ann-requestbody)

You can use the `@RequestBody` annotation to have the request body read and deserialized into an`Object` through an [HttpMessageReader](#webflux-codecs).
The following example uses a `@RequestBody` argument:

Java

```
@PostMapping("/accounts")
public void handle(@RequestBody Account account) {
    // ...
}
```

Kotlin

```
@PostMapping("/accounts")
fun handle(@RequestBody account: Account) {
    // ...
}
```

Unlike Spring MVC, in WebFlux, the `@RequestBody` method argument supports reactive types
and fully non-blocking reading and (client-to-server) streaming.

Java

```
@PostMapping("/accounts")
public void handle(@RequestBody Mono<Account> account) {
    // ...
}
```

Kotlin

```
@PostMapping("/accounts")
fun handle(@RequestBody accounts: Flow<Account>) {
    // ...
}
```

You can use the [HTTP message codecs](#webflux-config-message-codecs) option of the [WebFlux Config](#webflux-config) to
configure or customize message readers.

You can use `@RequestBody` in combination with `javax.validation.Valid` or Spring’s`@Validated` annotation, which causes Standard Bean Validation to be applied. Validation
errors cause a `WebExchangeBindException`, which results in a 400 (BAD\_REQUEST) response.
The exception contains a `BindingResult` with error details and can be handled in the
controller method by declaring the argument with an async wrapper and then using error
related operators:

Java

```
@PostMapping("/accounts")
public void handle(@Valid @RequestBody Mono<Account> account) {
    // use one of the onError* operators...
}
```

Kotlin

```
@PostMapping("/accounts")
fun handle(@Valid @RequestBody account: Mono<Account>) {
    // ...
}
```

##### `HttpEntity`

[Web MVC](web.html#mvc-ann-httpentity)

`HttpEntity` is more or less identical to using [`@RequestBody`](#webflux-ann-requestbody) but is based on a
container object that exposes request headers and the body. The following example uses an`HttpEntity`:

Java

```
@PostMapping("/accounts")
public void handle(HttpEntity<Account> entity) {
    // ...
}
```

Kotlin

```
@PostMapping("/accounts")
fun handle(entity: HttpEntity<Account>) {
    // ...
}
```

##### `@ResponseBody`

[Web MVC](web.html#mvc-ann-responsebody)

You can use the `@ResponseBody` annotation on a method to have the return serialized
to the response body through an [HttpMessageWriter](#webflux-codecs). The following
example shows how to do so:

Java

```
@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
    // ...
}
```

Kotlin

```
@GetMapping("/accounts/{id}")
@ResponseBody
fun handle(): Account {
    // ...
}
```

`@ResponseBody` is also supported at the class level, in which case it is inherited by
all controller methods. This is the effect of `@RestController`, which is nothing more
than a meta-annotation marked with `@Controller` and `@ResponseBody`.

`@ResponseBody` supports reactive types, which means you can return Reactor or RxJava
types and have the asynchronous values they produce rendered to the response.
For additional details, see [Streaming](#webflux-codecs-streaming) and[JSON rendering](#webflux-codecs-jackson).

You can combine `@ResponseBody` methods with JSON serialization views.
See [Jackson JSON](#webflux-ann-jackson) for details.

You can use the [HTTP message codecs](#webflux-config-message-codecs) option of the [WebFlux Config](#webflux-config) to
configure or customize message writing.

##### `ResponseEntity`

[Web MVC](web.html#mvc-ann-responseentity)

`ResponseEntity` is like [`@ResponseBody`](#webflux-ann-responsebody) but with status and headers. For example:

Java

```
@GetMapping("/something")
public ResponseEntity<String> handle() {
    String body = ... ;
    String etag = ... ;
    return ResponseEntity.ok().eTag(etag).build(body);
}
```

Kotlin

```
@GetMapping("/something")
fun handle(): ResponseEntity<String> {
    val body: String = ...
    val etag: String = ...
    return ResponseEntity.ok().eTag(etag).build(body)
}
```

WebFlux supports using a single value [reactive type](#webflux-reactive-libraries) to
produce the `ResponseEntity` asynchronously, and/or single and multi-value reactive types
for the body. This allows a variety of async responses with `ResponseEntity` as follows:

* `ResponseEntity<Mono<T>>` or `ResponseEntity<Flux<T>>` make the response status and
  headers known immediately while the body is provided asynchronously at a later point.
  Use `Mono` if the body consists of 0..1 values or `Flux` if it can produce multiple values.

* `Mono<ResponseEntity<T>>` provides all three — response status, headers, and body,
  asynchronously at a later point. This allows the response status and headers to vary
  depending on the outcome of asynchronous request handling.

* `Mono<ResponseEntity<Mono<T>>>` or `Mono<ResponseEntity<Flux<T>>>` are yet another
  possible, albeit less common alternative. They provide the response status and headers
  asynchronously first and then the response body, also asynchronously, second.

##### Jackson JSON

Spring offers support for the Jackson JSON library.

##### JSON Views#

[Web MVC](web.html#mvc-ann-jackson)

Spring WebFlux provides built-in support for[Jackson’s Serialization Views](https://www.baeldung.com/jackson-json-view-annotation),
which allows rendering only a subset of all fields in an `Object`. To use it with`@ResponseBody` or `ResponseEntity` controller methods, you can use Jackson’s`@JsonView` annotation to activate a serialization view class, as the following example shows:

Java

```
@RestController
public class UserController {

    @GetMapping("/user")
    @JsonView(User.WithoutPasswordView.class)
    public User getUser() {
        return new User("eric", "7!jd#h23");
    }
}

public class User {

    public interface WithoutPasswordView {};
    public interface WithPasswordView extends WithoutPasswordView {};

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @JsonView(WithoutPasswordView.class)
    public String getUsername() {
        return this.username;
    }

    @JsonView(WithPasswordView.class)
    public String getPassword() {
        return this.password;
    }
}
```

Kotlin

```
@RestController
class UserController {

    @GetMapping("/user")
    @JsonView(User.WithoutPasswordView::class)
    fun getUser(): User {
        return User("eric", "7!jd#h23")
    }
}

class User(
        @JsonView(WithoutPasswordView::class) val username: String,
        @JsonView(WithPasswordView::class) val password: String
) {
    interface WithoutPasswordView
    interface WithPasswordView : WithoutPasswordView
}
```

|   |`@JsonView` allows an array of view classes but you can only specify only one per<br/>controller method. Use a composite interface if you need to activate multiple views.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.4.4. `Model`

[Web MVC](web.html#mvc-ann-modelattrib-methods)

You can use the `@ModelAttribute` annotation:

* On a [method argument](#webflux-ann-modelattrib-method-args) in `@RequestMapping` methods
  to create or access an Object from the model and to bind it to the request through a`WebDataBinder`.

* As a method-level annotation in `@Controller` or `@ControllerAdvice` classes, helping
  to initialize the model prior to any `@RequestMapping` method invocation.

* On a `@RequestMapping` method to mark its return value as a model attribute.

This section discusses `@ModelAttribute` methods, or the second item from the preceding list.
A controller can have any number of `@ModelAttribute` methods. All such methods are
invoked before `@RequestMapping` methods in the same controller. A `@ModelAttribute`method can also be shared across controllers through `@ControllerAdvice`. See the section on[Controller Advice](#webflux-ann-controller-advice) for more details.

`@ModelAttribute` methods have flexible method signatures. They support many of the same
arguments as `@RequestMapping` methods (except for `@ModelAttribute` itself and anything
related to the request body).

The following example uses a `@ModelAttribute` method:

Java

```
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
    model.addAttribute(accountRepository.findAccount(number));
    // add more ...
}
```

Kotlin

```
@ModelAttribute
fun populateModel(@RequestParam number: String, model: Model) {
    model.addAttribute(accountRepository.findAccount(number))
    // add more ...
}
```

The following example adds one attribute only:

Java

```
@ModelAttribute
public Account addAccount(@RequestParam String number) {
    return accountRepository.findAccount(number);
}
```

Kotlin

```
@ModelAttribute
fun addAccount(@RequestParam number: String): Account {
    return accountRepository.findAccount(number);
}
```

|   |When a name is not explicitly specified, a default name is chosen based on the type,<br/>as explained in the javadoc for [`Conventions`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/Conventions.html).<br/>You can always assign an explicit name by using the overloaded `addAttribute` method or<br/>through the name attribute on `@ModelAttribute` (for a return value).|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Spring WebFlux, unlike Spring MVC, explicitly supports reactive types in the model
(for example, `Mono<Account>` or `io.reactivex.Single<Account>`). Such asynchronous model
attributes can be transparently resolved (and the model updated) to their actual values
at the time of `@RequestMapping` invocation, provided a `@ModelAttribute` argument is
declared without a wrapper, as the following example shows:

Java

```
@ModelAttribute
public void addAccount(@RequestParam String number) {
    Mono<Account> accountMono = accountRepository.findAccount(number);
    model.addAttribute("account", accountMono);
}

@PostMapping("/accounts")
public String handle(@ModelAttribute Account account, BindingResult errors) {
    // ...
}
```

Kotlin

```
import org.springframework.ui.set

@ModelAttribute
fun addAccount(@RequestParam number: String) {
    val accountMono: Mono<Account> = accountRepository.findAccount(number)
    model["account"] = accountMono
}

@PostMapping("/accounts")
fun handle(@ModelAttribute account: Account, errors: BindingResult): String {
    // ...
}
```

In addition, any model attributes that have a reactive type wrapper are resolved to their
actual values (and the model updated) just prior to view rendering.

You can also use `@ModelAttribute` as a method-level annotation on `@RequestMapping`methods, in which case the return value of the `@RequestMapping` method is interpreted as a
model attribute. This is typically not required, as it is the default behavior in HTML
controllers, unless the return value is a `String` that would otherwise be interpreted
as a view name. `@ModelAttribute` can also help to customize the model attribute name,
as the following example shows:

Java

```
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
public Account handle() {
    // ...
    return account;
}
```

Kotlin

```
@GetMapping("/accounts/{id}")
@ModelAttribute("myAccount")
fun handle(): Account {
    // ...
    return account
}
```

#### 1.4.5. `DataBinder`

[Web MVC](web.html#mvc-ann-initbinder)

`@Controller` or `@ControllerAdvice` classes can have `@InitBinder` methods, to
initialize instances of `WebDataBinder`. Those, in turn, are used to:

* Bind request parameters (that is, form data or query) to a model object.

* Convert `String`-based request values (such as request parameters, path variables,
  headers, cookies, and others) to the target type of controller method arguments.

* Format model object values as `String` values when rendering HTML forms.

`@InitBinder` methods can register controller-specific `java.beans.PropertyEditor` or
Spring `Converter` and `Formatter` components. In addition, you can use the[WebFlux Java configuration](#webflux-config-conversion) to register `Converter` and`Formatter` types in a globally shared `FormattingConversionService`.

`@InitBinder` methods support many of the same arguments that `@RequestMapping` methods
do, except for `@ModelAttribute` (command object) arguments. Typically, they are declared
with a `WebDataBinder` argument, for registrations, and a `void` return value.
The following example uses the `@InitBinder` annotation:

Java

```
@Controller
public class FormController {

    @InitBinder (1)
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    // ...
}
```

|**1**|Using the `@InitBinder` annotation.|
|-----|-----------------------------------|

Kotlin

```
@Controller
class FormController {

    @InitBinder (1)
    fun initBinder(binder: WebDataBinder) {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd")
        dateFormat.isLenient = false
        binder.registerCustomEditor(Date::class.java, CustomDateEditor(dateFormat, false))
    }

    // ...
}
```

Alternatively, when using a `Formatter`-based setup through a shared`FormattingConversionService`, you could re-use the same approach and register
controller-specific `Formatter` instances, as the following example shows:

Java

```
@Controller
public class FormController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); (1)
    }

    // ...
}
```

|**1**|Adding a custom formatter (a `DateFormatter`, in this case).|
|-----|------------------------------------------------------------|

Kotlin

```
@Controller
class FormController {

    @InitBinder
    fun initBinder(binder: WebDataBinder) {
        binder.addCustomFormatter(DateFormatter("yyyy-MM-dd")) (1)
    }

    // ...
}
```

|**1**|Adding a custom formatter (a `DateFormatter`, in this case).|
|-----|------------------------------------------------------------|

#### 1.4.6. Managing Exceptions

[Web MVC](web.html#mvc-ann-exceptionhandler)

`@Controller` and [@ControllerAdvice](#webflux-ann-controller-advice) classes can have`@ExceptionHandler` methods to handle exceptions from controller methods. The following
example includes such a handler method:

Java

```
@Controller
public class SimpleController {

    // ...

    @ExceptionHandler (1)
    public ResponseEntity<String> handle(IOException ex) {
        // ...
    }
}
```

|**1**|Declaring an `@ExceptionHandler`.|
|-----|---------------------------------|

Kotlin

```
@Controller
class SimpleController {

    // ...

    @ExceptionHandler (1)
    fun handle(ex: IOException): ResponseEntity<String> {
        // ...
    }
}
```

|**1**|Declaring an `@ExceptionHandler`.|
|-----|---------------------------------|

The exception can match against a top-level exception being propagated (that is, a direct`IOException` being thrown) or against the immediate cause within a top-level wrapper
exception (for example, an `IOException` wrapped inside an `IllegalStateException`).

For matching exception types, preferably declare the target exception as a method argument,
as shown in the preceding example. Alternatively, the annotation declaration can narrow the
exception types to match. We generally recommend being as specific as possible in the
argument signature and to declare your primary root exception mappings on a`@ControllerAdvice` prioritized with a corresponding order.
See [the MVC section](web.html#mvc-ann-exceptionhandler) for details.

|   |An `@ExceptionHandler` method in WebFlux supports the same method arguments and<br/>return values as a `@RequestMapping` method, with the exception of request body-<br/>and `@ModelAttribute`-related method arguments.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Support for `@ExceptionHandler` methods in Spring WebFlux is provided by the`HandlerAdapter` for `@RequestMapping` methods. See [`DispatcherHandler`](#webflux-dispatcher-handler)for more detail.

##### REST API exceptions

[Web MVC](web.html#mvc-ann-rest-exceptions)

A common requirement for REST services is to include error details in the body of the
response. The Spring Framework does not automatically do so, because the representation
of error details in the response body is application-specific. However, a`@RestController` can use `@ExceptionHandler` methods with a `ResponseEntity` return
value to set the status and the body of the response. Such methods can also be declared
in `@ControllerAdvice` classes to apply them globally.

|   |Note that Spring WebFlux does not have an equivalent for the Spring MVC`ResponseEntityExceptionHandler`, because WebFlux raises only `ResponseStatusException`(or subclasses thereof), and those do not need to be translated to<br/>an HTTP status code.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.4.7. Controller Advice

[Web MVC](web.html#mvc-ann-controller-advice)

Typically, the `@ExceptionHandler`, `@InitBinder`, and `@ModelAttribute` methods apply
within the `@Controller` class (or class hierarchy) in which they are declared. If you
want such methods to apply more globally (across controllers), you can declare them in a
class annotated with `@ControllerAdvice` or `@RestControllerAdvice`.

`@ControllerAdvice` is annotated with `@Component`, which means that such classes can be
registered as Spring beans through [component scanning](core.html#beans-java-instantiating-container-scan). `@RestControllerAdvice` is a composed annotation that is annotated
with both `@ControllerAdvice` and `@ResponseBody`, which essentially means`@ExceptionHandler` methods are rendered to the response body through message conversion
(versus view resolution or template rendering).

On startup, the infrastructure classes for `@RequestMapping` and `@ExceptionHandler`methods detect Spring beans annotated with `@ControllerAdvice` and then apply their
methods at runtime. Global `@ExceptionHandler` methods (from a `@ControllerAdvice`) are
applied *after* local ones (from the `@Controller`). By contrast, global `@ModelAttribute`and `@InitBinder` methods are applied *before* local ones.

By default, `@ControllerAdvice` methods apply to every request (that is, all controllers),
but you can narrow that down to a subset of controllers by using attributes on the
annotation, as the following example shows:

Java

```
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
```

Kotlin

```
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = [RestController::class])
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = [ControllerInterface::class, AbstractController::class])
public class ExampleAdvice3 {}
```

The selectors in the preceding example are evaluated at runtime and may negatively impact
performance if used extensively. See the[`@ControllerAdvice`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html)javadoc for more details.

### 1.5. Functional Endpoints

[Web MVC](web.html#webmvc-fn)

Spring WebFlux includes WebFlux.fn, a lightweight functional programming model in which functions
are used to route and handle requests and contracts are designed for immutability.
It is an alternative to the annotation-based programming model but otherwise runs on
the same [Reactive Core](#webflux-reactive-spring-web) foundation.

#### 1.5.1. Overview

[Web MVC](web.html#webmvc-fn-overview)

In WebFlux.fn, an HTTP request is handled with a `HandlerFunction`: a function that takes`ServerRequest` and returns a delayed `ServerResponse` (i.e. `Mono<ServerResponse>`).
Both the request and the response object have immutable contracts that offer JDK 8-friendly
access to the HTTP request and response.`HandlerFunction` is the equivalent of the body of a `@RequestMapping` method in the
annotation-based programming model.

Incoming requests are routed to a handler function with a `RouterFunction`: a function that
takes `ServerRequest` and returns a delayed `HandlerFunction` (i.e. `Mono<HandlerFunction>`).
When the router function matches, a handler function is returned; otherwise an empty Mono.`RouterFunction` is the equivalent of a `@RequestMapping` annotation, but with the major
difference that router functions provide not just data, but also behavior.

`RouterFunctions.route()` provides a router builder that facilitates the creation of routers,
as the following example shows:

Java

```
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);

RouterFunction<ServerResponse> route = route()
    .GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
    .GET("/person", accept(APPLICATION_JSON), handler::listPeople)
    .POST("/person", handler::createPerson)
    .build();

public class PersonHandler {

    // ...

    public Mono<ServerResponse> listPeople(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> createPerson(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> getPerson(ServerRequest request) {
        // ...
    }
}
```

Kotlin

```
val repository: PersonRepository = ...
val handler = PersonHandler(repository)

val route = coRouter { (1)
    accept(APPLICATION_JSON).nest {
        GET("/person/{id}", handler::getPerson)
        GET("/person", handler::listPeople)
    }
    POST("/person", handler::createPerson)
}

class PersonHandler(private val repository: PersonRepository) {

    // ...

    suspend fun listPeople(request: ServerRequest): ServerResponse {
        // ...
    }

    suspend fun createPerson(request: ServerRequest): ServerResponse {
        // ...
    }

    suspend fun getPerson(request: ServerRequest): ServerResponse {
        // ...
    }
}
```

|**1**|Create router using Coroutines router DSL, a Reactive alternative is also available via `router { }`.|
|-----|-----------------------------------------------------------------------------------------------------|

One way to run a `RouterFunction` is to turn it into an `HttpHandler` and install it
through one of the built-in [server adapters](#webflux-httphandler):

* `RouterFunctions.toHttpHandler(RouterFunction)`

* `RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies)`

Most applications can run through the WebFlux Java configuration, see [Running a Server](#webflux-fn-running).

#### 1.5.2. HandlerFunction

[Web MVC](web.html#webmvc-fn-handler-functions)

`ServerRequest` and `ServerResponse` are immutable interfaces that offer JDK 8-friendly
access to the HTTP request and response.
Both request and response provide [Reactive Streams](https://www.reactive-streams.org) back pressure
against the body streams.
The request body is represented with a Reactor `Flux` or `Mono`.
The response body is represented with any Reactive Streams `Publisher`, including `Flux` and `Mono`.
For more on that, see [Reactive Libraries](#webflux-reactive-libraries).

##### ServerRequest

`ServerRequest` provides access to the HTTP method, URI, headers, and query parameters,
while access to the body is provided through the `body` methods.

The following example extracts the request body to a `Mono<String>`:

Java

```
Mono<String> string = request.bodyToMono(String.class);
```

Kotlin

```
val string = request.awaitBody<String>()
```

The following example extracts the body to a `Flux<Person>` (or a `Flow<Person>` in Kotlin),
where `Person` objects are decoded from someserialized form, such as JSON or XML:

Java

```
Flux<Person> people = request.bodyToFlux(Person.class);
```

Kotlin

```
val people = request.bodyToFlow<Person>()
```

The preceding examples are shortcuts that use the more general `ServerRequest.body(BodyExtractor)`,
which accepts the `BodyExtractor` functional strategy interface. The utility class`BodyExtractors` provides access to a number of instances. For example, the preceding examples can
also be written as follows:

Java

```
Mono<String> string = request.body(BodyExtractors.toMono(String.class));
Flux<Person> people = request.body(BodyExtractors.toFlux(Person.class));
```

Kotlin

```
    val string = request.body(BodyExtractors.toMono(String::class.java)).awaitSingle()
    val people = request.body(BodyExtractors.toFlux(Person::class.java)).asFlow()
```

The following example shows how to access form data:

Java

```
Mono<MultiValueMap<String, String>> map = request.formData();
```

Kotlin

```
val map = request.awaitFormData()
```

The following example shows how to access multipart data as a map:

Java

```
Mono<MultiValueMap<String, Part>> map = request.multipartData();
```

Kotlin

```
val map = request.awaitMultipartData()
```

The following example shows how to access multiparts, one at a time, in streaming fashion:

Java

```
Flux<Part> parts = request.body(BodyExtractors.toParts());
```

Kotlin

```
val parts = request.body(BodyExtractors.toParts()).asFlow()
```

##### ServerResponse

`ServerResponse` provides access to the HTTP response and, since it is immutable, you can use
a `build` method to create it. You can use the builder to set the response status, to add response
headers, or to provide a body. The following example creates a 200 (OK) response with JSON
content:

Java

```
Mono<Person> person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person, Person.class);
```

Kotlin

```
val person: Person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(person)
```

The following example shows how to build a 201 (CREATED) response with a `Location` header and no body:

Java

```
URI location = ...
ServerResponse.created(location).build();
```

Kotlin

```
val location: URI = ...
ServerResponse.created(location).build()
```

Depending on the codec used, it is possible to pass hint parameters to customize how the
body is serialized or deserialized. For example, to specify a [Jackson JSON view](https://www.baeldung.com/jackson-json-view-annotation):

Java

```
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView.class).body(...);
```

Kotlin

```
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView::class.java).body(...)
```

##### Handler Classes

We can write a handler function as a lambda, as the following example shows:

Java

```
HandlerFunction<ServerResponse> helloWorld =
  request -> ServerResponse.ok().bodyValue("Hello World");
```

Kotlin

```
val helloWorld = HandlerFunction<ServerResponse> { ServerResponse.ok().bodyValue("Hello World") }
```

That is convenient, but in an application we need multiple functions, and multiple inline
lambda’s can get messy.
Therefore, it is useful to group related handler functions together into a handler class, which
has a similar role as `@Controller` in an annotation-based application.
For example, the following class exposes a reactive `Person` repository:

Java

```
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

public class PersonHandler {

    private final PersonRepository repository;

    public PersonHandler(PersonRepository repository) {
        this.repository = repository;
    }

    public Mono<ServerResponse> listPeople(ServerRequest request) { (1)
        Flux<Person> people = repository.allPeople();
        return ok().contentType(APPLICATION_JSON).body(people, Person.class);
    }

    public Mono<ServerResponse> createPerson(ServerRequest request) { (2)
        Mono<Person> person = request.bodyToMono(Person.class);
        return ok().build(repository.savePerson(person));
    }

    public Mono<ServerResponse> getPerson(ServerRequest request) { (3)
        int personId = Integer.valueOf(request.pathVariable("id"));
        return repository.getPerson(personId)
            .flatMap(person -> ok().contentType(APPLICATION_JSON).bodyValue(person))
            .switchIfEmpty(ServerResponse.notFound().build());
    }
}
```

|**1**|                                                                                                                                                                   `listPeople` is a handler function that returns all `Person` objects found in the repository as<br/>JSON.                                                                                                                                                                   |
|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|`createPerson` is a handler function that stores a new `Person` contained in the request body.<br/>Note that `PersonRepository.savePerson(Person)` returns `Mono<Void>`: an empty `Mono` that emits<br/>a completion signal when the person has been read from the request and stored. So we use the`build(Publisher<Void>)` method to send a response when that completion signal is received (that is,<br/>when the `Person` has been saved).|
|**3**|                                                                        `getPerson` is a handler function that returns a single person, identified by the `id` path<br/>variable. We retrieve that `Person` from the repository and create a JSON response, if it is<br/>found. If it is not found, we use `switchIfEmpty(Mono<T>)` to return a 404 Not Found response.                                                                        |

Kotlin

```
class PersonHandler(private val repository: PersonRepository) {

    suspend fun listPeople(request: ServerRequest): ServerResponse { (1)
        val people: Flow<Person> = repository.allPeople()
        return ok().contentType(APPLICATION_JSON).bodyAndAwait(people);
    }

    suspend fun createPerson(request: ServerRequest): ServerResponse { (2)
        val person = request.awaitBody<Person>()
        repository.savePerson(person)
        return ok().buildAndAwait()
    }

    suspend fun getPerson(request: ServerRequest): ServerResponse { (3)
        val personId = request.pathVariable("id").toInt()
        return repository.getPerson(personId)?.let { ok().contentType(APPLICATION_JSON).bodyValueAndAwait(it) }
                ?: ServerResponse.notFound().buildAndAwait()

    }
}
```

|**1**|                                                                           `listPeople` is a handler function that returns all `Person` objects found in the repository as<br/>JSON.                                                                           |
|-----|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|                               `createPerson` is a handler function that stores a new `Person` contained in the request body.<br/>Note that `PersonRepository.savePerson(Person)` is a suspending function with no return type.                                |
|**3**|`getPerson` is a handler function that returns a single person, identified by the `id` path<br/>variable. We retrieve that `Person` from the repository and create a JSON response, if it is<br/>found. If it is not found, we return a 404 Not Found response.|

##### Validation

A functional endpoint can use Spring’s [validation facilities](core.html#validation) to
apply validation to the request body. For example, given a custom Spring[Validator](core.html#validation) implementation for a `Person`:

Java

```
public class PersonHandler {

    private final Validator validator = new PersonValidator(); (1)

    // ...

    public Mono<ServerResponse> createPerson(ServerRequest request) {
        Mono<Person> person = request.bodyToMono(Person.class).doOnNext(this::validate); (2)
        return ok().build(repository.savePerson(person));
    }

    private void validate(Person person) {
        Errors errors = new BeanPropertyBindingResult(person, "person");
        validator.validate(person, errors);
        if (errors.hasErrors()) {
            throw new ServerWebInputException(errors.toString()); (3)
        }
    }
}
```

|**1**|   Create `Validator` instance.    |
|-----|-----------------------------------|
|**2**|         Apply validation.         |
|**3**|Raise exception for a 400 response.|

Kotlin

```
class PersonHandler(private val repository: PersonRepository) {

    private val validator = PersonValidator() (1)

    // ...

    suspend fun createPerson(request: ServerRequest): ServerResponse {
        val person = request.awaitBody<Person>()
        validate(person) (2)
        repository.savePerson(person)
        return ok().buildAndAwait()
    }

    private fun validate(person: Person) {
        val errors: Errors = BeanPropertyBindingResult(person, "person");
        validator.validate(person, errors);
        if (errors.hasErrors()) {
            throw ServerWebInputException(errors.toString()) (3)
        }
    }
}
```

|**1**|   Create `Validator` instance.    |
|-----|-----------------------------------|
|**2**|         Apply validation.         |
|**3**|Raise exception for a 400 response.|

Handlers can also use the standard bean validation API (JSR-303) by creating and injecting
a global `Validator` instance based on `LocalValidatorFactoryBean`.
See [Spring Validation](core.html#validation-beanvalidation).

#### 1.5.3. `RouterFunction`

[Web MVC](web.html#webmvc-fn-router-functions)

Router functions are used to route the requests to the corresponding `HandlerFunction`.
Typically, you do not write router functions yourself, but rather use a method on the`RouterFunctions` utility class to create one.`RouterFunctions.route()` (no parameters) provides you with a fluent builder for creating a router
function, whereas `RouterFunctions.route(RequestPredicate, HandlerFunction)` offers a direct way
to create a router.

Generally, it is recommended to use the `route()` builder, as it provides
convenient short-cuts for typical mapping scenarios without requiring hard-to-discover
static imports.
For instance, the router function builder offers the method `GET(String, HandlerFunction)` to create a mapping for GET requests; and `POST(String, HandlerFunction)` for POSTs.

Besides HTTP method-based mapping, the route builder offers a way to introduce additional
predicates when mapping to requests.
For each HTTP method there is an overloaded variant that takes a `RequestPredicate` as a
parameter, though which additional constraints can be expressed.

##### Predicates

You can write your own `RequestPredicate`, but the `RequestPredicates` utility class
offers commonly used implementations, based on the request path, HTTP method, content-type,
and so on.
The following example uses a request predicate to create a constraint based on the `Accept`header:

Java

```
RouterFunction<ServerResponse> route = RouterFunctions.route()
    .GET("/hello-world", accept(MediaType.TEXT_PLAIN),
        request -> ServerResponse.ok().bodyValue("Hello World")).build();
```

Kotlin

```
val route = coRouter {
    GET("/hello-world", accept(TEXT_PLAIN)) {
        ServerResponse.ok().bodyValueAndAwait("Hello World")
    }
}
```

You can compose multiple request predicates together by using:

* `RequestPredicate.and(RequestPredicate)` — both must match.

* `RequestPredicate.or(RequestPredicate)` — either can match.

Many of the predicates from `RequestPredicates` are composed.
For example, `RequestPredicates.GET(String)` is composed from `RequestPredicates.method(HttpMethod)`and `RequestPredicates.path(String)`.
The example shown above also uses two request predicates, as the builder uses`RequestPredicates.GET` internally, and composes that with the `accept` predicate.

##### Routes

Router functions are evaluated in order: if the first route does not match, the
second is evaluated, and so on.
Therefore, it makes sense to declare more specific routes before general ones.
This is also important when registering router functions as Spring beans, as will
be described later.
Note that this behavior is different from the annotation-based programming model, where the
"most specific" controller method is picked automatically.

When using the router function builder, all defined routes are composed into one`RouterFunction` that is returned from `build()`.
There are also other ways to compose multiple router functions together:

* `add(RouterFunction)` on the `RouterFunctions.route()` builder

* `RouterFunction.and(RouterFunction)`

* `RouterFunction.andRoute(RequestPredicate, HandlerFunction)` — shortcut for`RouterFunction.and()` with nested `RouterFunctions.route()`.

The following example shows the composition of four routes:

Java

```
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;

PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);

RouterFunction<ServerResponse> otherRoute = ...

RouterFunction<ServerResponse> route = route()
    .GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
    .GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
    .POST("/person", handler::createPerson) (3)
    .add(otherRoute) (4)
    .build();
```

|**1**|`GET /person/{id}` with an `Accept` header that matches JSON is routed to`PersonHandler.getPerson`|
|-----|--------------------------------------------------------------------------------------------------|
|**2**|  `GET /person` with an `Accept` header that matches JSON is routed to`PersonHandler.listPeople`  |
|**3**|    `POST /person` with no additional predicates is mapped to`PersonHandler.createPerson`, and    |
|**4**|    `otherRoute` is a router function that is created elsewhere, and added to the route built.    |

Kotlin

```
import org.springframework.http.MediaType.APPLICATION_JSON

val repository: PersonRepository = ...
val handler = PersonHandler(repository);

val otherRoute: RouterFunction<ServerResponse> = coRouter {  }

val route = coRouter {
    GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
    GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
    POST("/person", handler::createPerson) (3)
}.and(otherRoute) (4)
```

|**1**|`GET /person/{id}` with an `Accept` header that matches JSON is routed to`PersonHandler.getPerson`|
|-----|--------------------------------------------------------------------------------------------------|
|**2**|  `GET /person` with an `Accept` header that matches JSON is routed to`PersonHandler.listPeople`  |
|**3**|    `POST /person` with no additional predicates is mapped to`PersonHandler.createPerson`, and    |
|**4**|    `otherRoute` is a router function that is created elsewhere, and added to the route built.    |

##### Nested Routes

It is common for a group of router functions to have a shared predicate, for instance a
shared path. In the example above, the shared predicate would be a path predicate that
matches `/person`, used by three of the routes. When using annotations, you would remove
this duplication by using a type-level `@RequestMapping` annotation that maps to`/person`. In WebFlux.fn, path predicates can be shared through the `path` method on the
router function builder. For instance, the last few lines of the example above can be
improved in the following way by using nested routes:

Java

```
RouterFunction<ServerResponse> route = route()
    .path("/person", builder -> builder (1)
        .GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
        .GET(accept(APPLICATION_JSON), handler::listPeople)
        .POST("/person", handler::createPerson))
    .build();
```

|**1**|Note that second parameter of `path` is a consumer that takes the a router builder.|
|-----|-----------------------------------------------------------------------------------|

Kotlin

```
val route = coRouter {
    "/person".nest {
        GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
        GET(accept(APPLICATION_JSON), handler::listPeople)
        POST("/person", handler::createPerson)
    }
}
```

Though path-based nesting is the most common, you can nest on any kind of predicate by using
the `nest` method on the builder.
The above still contains some duplication in the form of the shared `Accept`-header predicate.
We can further improve by using the `nest` method together with `accept`:

Java

```
RouterFunction<ServerResponse> route = route()
    .path("/person", b1 -> b1
        .nest(accept(APPLICATION_JSON), b2 -> b2
            .GET("/{id}", handler::getPerson)
            .GET(handler::listPeople))
        .POST("/person", handler::createPerson))
    .build();
```

Kotlin

```
val route = coRouter {
    "/person".nest {
        accept(APPLICATION_JSON).nest {
            GET("/{id}", handler::getPerson)
            GET(handler::listPeople)
            POST("/person", handler::createPerson)
        }
    }
}
```

#### 1.5.4. Running a Server

[Web MVC](web.html#webmvc-fn-running)

How do you run a router function in an HTTP server? A simple option is to convert a router
function to an `HttpHandler` by using one of the following:

* `RouterFunctions.toHttpHandler(RouterFunction)`

* `RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies)`

You can then use the returned `HttpHandler` with a number of server adapters by following[HttpHandler](#webflux-httphandler) for server-specific instructions.

A more typical option, also used by Spring Boot, is to run with a[`DispatcherHandler`](#webflux-dispatcher-handler)-based setup through the[WebFlux Config](#webflux-config), which uses Spring configuration to declare the
components required to process requests. The WebFlux Java configuration declares the following
infrastructure components to support functional endpoints:

* `RouterFunctionMapping`: Detects one or more `RouterFunction<?>` beans in the Spring
  configuration, [orders them](core.html#beans-factory-ordered), combines them through`RouterFunction.andOther`, and routes requests to the resulting composed `RouterFunction`.

* `HandlerFunctionAdapter`: Simple adapter that lets `DispatcherHandler` invoke
  a `HandlerFunction` that was mapped to a request.

* `ServerResponseResultHandler`: Handles the result from the invocation of a`HandlerFunction` by invoking the `writeTo` method of the `ServerResponse`.

The preceding components let functional endpoints fit within the `DispatcherHandler` request
processing lifecycle and also (potentially) run side by side with annotated controllers, if
any are declared. It is also how functional endpoints are enabled by the Spring Boot WebFlux
starter.

The following example shows a WebFlux Java configuration (see[DispatcherHandler](#webflux-dispatcher-handler) for how to run it):

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Bean
    public RouterFunction<?> routerFunctionA() {
        // ...
    }

    @Bean
    public RouterFunction<?> routerFunctionB() {
        // ...
    }

    // ...

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        // configure message conversion...
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // configure CORS...
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // configure view resolution for HTML rendering...
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    @Bean
    fun routerFunctionA(): RouterFunction<*> {
        // ...
    }

    @Bean
    fun routerFunctionB(): RouterFunction<*> {
        // ...
    }

    // ...

    override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
        // configure message conversion...
    }

    override fun addCorsMappings(registry: CorsRegistry) {
        // configure CORS...
    }

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        // configure view resolution for HTML rendering...
    }
}
```

#### 1.5.5. Filtering Handler Functions

[Web MVC](web.html#webmvc-fn-handler-filter-function)

You can filter handler functions by using the `before`, `after`, or `filter` methods on the routing
function builder.
With annotations, you can achieve similar functionality by using `@ControllerAdvice`, a `ServletFilter`, or both.
The filter will apply to all routes that are built by the builder.
This means that filters defined in nested routes do not apply to "top-level" routes.
For instance, consider the following example:

Java

```
RouterFunction<ServerResponse> route = route()
    .path("/person", b1 -> b1
        .nest(accept(APPLICATION_JSON), b2 -> b2
            .GET("/{id}", handler::getPerson)
            .GET(handler::listPeople)
            .before(request -> ServerRequest.from(request) (1)
                .header("X-RequestHeader", "Value")
                .build()))
        .POST("/person", handler::createPerson))
    .after((request, response) -> logResponse(response)) (2)
    .build();
```

|**1**| The `before` filter that adds a custom request header is only applied to the two GET routes. |
|-----|----------------------------------------------------------------------------------------------|
|**2**|The `after` filter that logs the response is applied to all routes, including the nested ones.|

Kotlin

```
val route = router {
    "/person".nest {
        GET("/{id}", handler::getPerson)
        GET("", handler::listPeople)
        before { (1)
            ServerRequest.from(it)
                    .header("X-RequestHeader", "Value").build()
        }
        POST("/person", handler::createPerson)
        after { _, response -> (2)
            logResponse(response)
        }
    }
}
```

|**1**| The `before` filter that adds a custom request header is only applied to the two GET routes. |
|-----|----------------------------------------------------------------------------------------------|
|**2**|The `after` filter that logs the response is applied to all routes, including the nested ones.|

The `filter` method on the router builder takes a `HandlerFilterFunction`: a
function that takes a `ServerRequest` and `HandlerFunction` and returns a `ServerResponse`.
The handler function parameter represents the next element in the chain.
This is typically the handler that is routed to, but it can also be another
filter if multiple are applied.

Now we can add a simple security filter to our route, assuming that we have a `SecurityManager` that
can determine whether a particular path is allowed.
The following example shows how to do so:

Java

```
SecurityManager securityManager = ...

RouterFunction<ServerResponse> route = route()
    .path("/person", b1 -> b1
        .nest(accept(APPLICATION_JSON), b2 -> b2
            .GET("/{id}", handler::getPerson)
            .GET(handler::listPeople))
        .POST("/person", handler::createPerson))
    .filter((request, next) -> {
        if (securityManager.allowAccessTo(request.path())) {
            return next.handle(request);
        }
        else {
            return ServerResponse.status(UNAUTHORIZED).build();
        }
    })
    .build();
```

Kotlin

```
val securityManager: SecurityManager = ...

val route = router {
        ("/person" and accept(APPLICATION_JSON)).nest {
            GET("/{id}", handler::getPerson)
            GET("", handler::listPeople)
            POST("/person", handler::createPerson)
            filter { request, next ->
                if (securityManager.allowAccessTo(request.path())) {
                    next(request)
                }
                else {
                    status(UNAUTHORIZED).build();
                }
            }
        }
    }
```

The preceding example demonstrates that invoking the `next.handle(ServerRequest)` is optional.
We only let the handler function be run when access is allowed.

Besides using the `filter` method on the router function builder, it is possible to apply a
filter to an existing router function via `RouterFunction.filter(HandlerFilterFunction)`.

|   |CORS support for functional endpoints is provided through a dedicated[`CorsWebFilter`](webflux-cors.html#webflux-cors-webfilter).|
|---|---------------------------------------------------------------------------------------------------------------------------------|

### 1.6. URI Links

[Web MVC](web.html#mvc-uri-building)

This section describes various options available in the Spring Framework to prepare URIs.

#### 1.6.1. UriComponents

Spring MVC and Spring WebFlux

`UriComponentsBuilder` helps to build URI’s from URI templates with variables, as the following example shows:

Java

```
UriComponents uriComponents = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")  (1)
        .queryParam("q", "{q}")  (2)
        .encode() (3)
        .build(); (4)

URI uri = uriComponents.expand("Westin", "123").toUri();  (5)
```

|**1**|        Static factory method with a URI template.         |
|-----|-----------------------------------------------------------|
|**2**|              Add or replace URI components.               |
|**3**|Request to have the URI template and URI variables encoded.|
|**4**|                 Build a `UriComponents`.                  |
|**5**|          Expand variables and obtain the `URI`.           |

Kotlin

```
val uriComponents = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")  (1)
        .queryParam("q", "{q}")  (2)
        .encode() (3)
        .build() (4)

val uri = uriComponents.expand("Westin", "123").toUri()  (5)
```

|**1**|        Static factory method with a URI template.         |
|-----|-----------------------------------------------------------|
|**2**|              Add or replace URI components.               |
|**3**|Request to have the URI template and URI variables encoded.|
|**4**|                 Build a `UriComponents`.                  |
|**5**|          Expand variables and obtain the `URI`.           |

The preceding example can be consolidated into one chain and shortened with `buildAndExpand`,
as the following example shows:

Java

```
URI uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")
        .queryParam("q", "{q}")
        .encode()
        .buildAndExpand("Westin", "123")
        .toUri();
```

Kotlin

```
val uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")
        .queryParam("q", "{q}")
        .encode()
        .buildAndExpand("Westin", "123")
        .toUri()
```

You can shorten it further by going directly to a URI (which implies encoding),
as the following example shows:

Java

```
URI uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")
        .queryParam("q", "{q}")
        .build("Westin", "123");
```

Kotlin

```
val uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}")
        .queryParam("q", "{q}")
        .build("Westin", "123")
```

You can shorten it further still with a full URI template, as the following example shows:

Java

```
URI uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}?q={q}")
        .build("Westin", "123");
```

Kotlin

```
val uri = UriComponentsBuilder
        .fromUriString("https://example.com/hotels/{hotel}?q={q}")
        .build("Westin", "123")
```

#### 1.6.2. UriBuilder

Spring MVC and Spring WebFlux

[`UriComponentsBuilder`](#web-uricomponents) implements `UriBuilder`. You can create a`UriBuilder`, in turn, with a `UriBuilderFactory`. Together, `UriBuilderFactory` and`UriBuilder` provide a pluggable mechanism to build URIs from URI templates, based on
shared configuration, such as a base URL, encoding preferences, and other details.

You can configure `RestTemplate` and `WebClient` with a `UriBuilderFactory`to customize the preparation of URIs. `DefaultUriBuilderFactory` is a default
implementation of `UriBuilderFactory` that uses `UriComponentsBuilder` internally and
exposes shared configuration options.

The following example shows how to configure a `RestTemplate`:

Java

```
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;

String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);

RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
```

Kotlin

```
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode

val baseUrl = "https://example.org"
val factory = DefaultUriBuilderFactory(baseUrl)
factory.encodingMode = EncodingMode.TEMPLATE_AND_VALUES

val restTemplate = RestTemplate()
restTemplate.uriTemplateHandler = factory
```

The following example configures a `WebClient`:

Java

```
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;

String baseUrl = "https://example.org";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);

WebClient client = WebClient.builder().uriBuilderFactory(factory).build();
```

Kotlin

```
// import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode

val baseUrl = "https://example.org"
val factory = DefaultUriBuilderFactory(baseUrl)
factory.encodingMode = EncodingMode.TEMPLATE_AND_VALUES

val client = WebClient.builder().uriBuilderFactory(factory).build()
```

In addition, you can also use `DefaultUriBuilderFactory` directly. It is similar to using`UriComponentsBuilder` but, instead of static factory methods, it is an actual instance
that holds configuration and preferences, as the following example shows:

Java

```
String baseUrl = "https://example.com";
DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(baseUrl);

URI uri = uriBuilderFactory.uriString("/hotels/{hotel}")
        .queryParam("q", "{q}")
        .build("Westin", "123");
```

Kotlin

```
val baseUrl = "https://example.com"
val uriBuilderFactory = DefaultUriBuilderFactory(baseUrl)

val uri = uriBuilderFactory.uriString("/hotels/{hotel}")
        .queryParam("q", "{q}")
        .build("Westin", "123")
```

#### 1.6.3. URI Encoding

Spring MVC and Spring WebFlux

`UriComponentsBuilder` exposes encoding options at two levels:

* [UriComponentsBuilder#encode()](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#encode--):
  Pre-encodes the URI template first and then strictly encodes URI variables when expanded.

* [UriComponents#encode()](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/util/UriComponents.html#encode--):
  Encodes URI components *after* URI variables are expanded.

Both options replace non-ASCII and illegal characters with escaped octets. However, the first option
also replaces characters with reserved meaning that appear in URI variables.

|   |Consider ";", which is legal in a path but has reserved meaning. The first option replaces<br/>";" with "%3B" in URI variables but not in the URI template. By contrast, the second option never<br/>replaces ";", since it is a legal character in a path.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

For most cases, the first option is likely to give the expected result, because it treats URI
variables as opaque data to be fully encoded, while the second option is useful if URI
variables do intentionally contain reserved characters. The second option is also useful
when not expanding URI variables at all since that will also encode anything that
incidentally looks like a URI variable.

The following example uses the first option:

Java

```
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
        .queryParam("q", "{q}")
        .encode()
        .buildAndExpand("New York", "foo+bar")
        .toUri();

// Result is "/hotel%20list/New%20York?q=foo%2Bbar"
```

Kotlin

```
val uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
        .queryParam("q", "{q}")
        .encode()
        .buildAndExpand("New York", "foo+bar")
        .toUri()

// Result is "/hotel%20list/New%20York?q=foo%2Bbar"
```

You can shorten the preceding example by going directly to the URI (which implies encoding),
as the following example shows:

Java

```
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
        .queryParam("q", "{q}")
        .build("New York", "foo+bar");
```

Kotlin

```
val uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
        .queryParam("q", "{q}")
        .build("New York", "foo+bar")
```

You can shorten it further still with a full URI template, as the following example shows:

Java

```
URI uri = UriComponentsBuilder.fromUriString("/hotel list/{city}?q={q}")
        .build("New York", "foo+bar");
```

Kotlin

```
val uri = UriComponentsBuilder.fromUriString("/hotel list/{city}?q={q}")
        .build("New York", "foo+bar")
```

The `WebClient` and the `RestTemplate` expand and encode URI templates internally through
the `UriBuilderFactory` strategy. Both can be configured with a custom strategy,
as the following example shows:

Java

```
String baseUrl = "https://example.com";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl)
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);

// Customize the RestTemplate..
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);

// Customize the WebClient..
WebClient client = WebClient.builder().uriBuilderFactory(factory).build();
```

Kotlin

```
val baseUrl = "https://example.com"
val factory = DefaultUriBuilderFactory(baseUrl).apply {
    encodingMode = EncodingMode.TEMPLATE_AND_VALUES
}

// Customize the RestTemplate..
val restTemplate = RestTemplate().apply {
    uriTemplateHandler = factory
}

// Customize the WebClient..
val client = WebClient.builder().uriBuilderFactory(factory).build()
```

The `DefaultUriBuilderFactory` implementation uses `UriComponentsBuilder` internally to
expand and encode URI templates. As a factory, it provides a single place to configure
the approach to encoding, based on one of the below encoding modes:

* `TEMPLATE_AND_VALUES`: Uses `UriComponentsBuilder#encode()`, corresponding to
  the first option in the earlier list, to pre-encode the URI template and strictly encode URI variables when
  expanded.

* `VALUES_ONLY`: Does not encode the URI template and, instead, applies strict encoding
  to URI variables through `UriUtils#encodeUriVariables` prior to expanding them into the
  template.

* `URI_COMPONENT`: Uses `UriComponents#encode()`, corresponding to the second option in the earlier list, to
  encode URI component value *after* URI variables are expanded.

* `NONE`: No encoding is applied.

The `RestTemplate` is set to `EncodingMode.URI_COMPONENT` for historic
reasons and for backwards compatibility. The `WebClient` relies on the default value
in `DefaultUriBuilderFactory`, which was changed from `EncodingMode.URI_COMPONENT` in
5.0.x to `EncodingMode.TEMPLATE_AND_VALUES` in 5.1.

### 1.7. CORS

[Web MVC](web.html#mvc-cors)

Spring WebFlux lets you handle CORS (Cross-Origin Resource Sharing). This section
describes how to do so.

#### 1.7.1. Introduction

[Web MVC](web.html#mvc-cors-intro)

For security reasons, browsers prohibit AJAX calls to resources outside the current origin.
For example, you could have your bank account in one tab and evil.com in another. Scripts
from evil.com should not be able to make AJAX requests to your bank API with your
credentials — for example, withdrawing money from your account!

Cross-Origin Resource Sharing (CORS) is a [W3C specification](https://www.w3.org/TR/cors/)implemented by [most browsers](https://caniuse.com/#feat=cors) that lets you specify
what kind of cross-domain requests are authorized, rather than using less secure and less
powerful workarounds based on IFRAME or JSONP.

#### 1.7.2. Processing

[Web MVC](web.html#mvc-cors-processing)

The CORS specification distinguishes between preflight, simple, and actual requests.
To learn how CORS works, you can read[this article](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), among
many others, or see the specification for more details.

Spring WebFlux `HandlerMapping` implementations provide built-in support for CORS. After successfully
mapping a request to a handler, a `HandlerMapping` checks the CORS configuration for the
given request and handler and takes further actions. Preflight requests are handled
directly, while simple and actual CORS requests are intercepted, validated, and have the
required CORS response headers set.

In order to enable cross-origin requests (that is, the `Origin` header is present and
differs from the host of the request), you need to have some explicitly declared CORS
configuration. If no matching CORS configuration is found, preflight requests are
rejected. No CORS headers are added to the responses of simple and actual CORS requests
and, consequently, browsers reject them.

Each `HandlerMapping` can be[configured](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/handler/AbstractHandlerMapping.html#setCorsConfigurations-java.util.Map-)individually with URL pattern-based `CorsConfiguration` mappings. In most cases, applications
use the WebFlux Java configuration to declare such mappings, which results in a single,
global map passed to all `HandlerMapping` implementations.

You can combine global CORS configuration at the `HandlerMapping` level with more
fine-grained, handler-level CORS configuration. For example, annotated controllers can use
class- or method-level `@CrossOrigin` annotations (other handlers can implement`CorsConfigurationSource`).

The rules for combining global and local configuration are generally additive — for example,
all global and all local origins. For those attributes where only a single value can be
accepted, such as `allowCredentials` and `maxAge`, the local overrides the global value. See[`CorsConfiguration#combine(CorsConfiguration)`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/cors/CorsConfiguration.html#combine-org.springframework.web.cors.CorsConfiguration-)for more details.

|   |To learn more from the source or to make advanced customizations, see:<br/><br/>* `CorsConfiguration`<br/><br/>* `CorsProcessor` and `DefaultCorsProcessor`<br/><br/>* `AbstractHandlerMapping`|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.7.3. `@CrossOrigin`

[Web MVC](web.html#mvc-cors-controller)

The [`@CrossOrigin`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html)annotation enables cross-origin requests on annotated controller methods, as the
following example shows:

Java

```
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    public Mono<Account> retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public Mono<Void> remove(@PathVariable Long id) {
        // ...
    }
}
```

Kotlin

```
@RestController
@RequestMapping("/account")
class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    suspend fun retrieve(@PathVariable id: Long): Account {
        // ...
    }

    @DeleteMapping("/{id}")
    suspend fun remove(@PathVariable id: Long) {
        // ...
    }
}
```

By default, `@CrossOrigin` allows:

* All origins.

* All headers.

* All HTTP methods to which the controller method is mapped.

`allowCredentials` is not enabled by default, since that establishes a trust level
that exposes sensitive user-specific information (such as cookies and CSRF tokens) and
should be used only where appropriate. When it is enabled either `allowOrigins` must be
set to one or more specific domain (but not the special value `"*"`) or alternatively
the `allowOriginPatterns` property may be used to match to a dynamic set of origins.

`maxAge` is set to 30 minutes.

`@CrossOrigin` is supported at the class level, too, and inherited by all methods.
The following example specifies a certain domain and sets `maxAge` to an hour:

Java

```
@CrossOrigin(origins = "https://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @GetMapping("/{id}")
    public Mono<Account> retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public Mono<Void> remove(@PathVariable Long id) {
        // ...
    }
}
```

Kotlin

```
@CrossOrigin("https://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
class AccountController {

    @GetMapping("/{id}")
    suspend fun retrieve(@PathVariable id: Long): Account {
        // ...
    }

    @DeleteMapping("/{id}")
    suspend fun remove(@PathVariable id: Long) {
        // ...
    }
}
```

You can use `@CrossOrigin` at both the class and the method level,
as the following example shows:

Java

```
@CrossOrigin(maxAge = 3600) (1)
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin("https://domain2.com") (2)
    @GetMapping("/{id}")
    public Mono<Account> retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public Mono<Void> remove(@PathVariable Long id) {
        // ...
    }
}
```

|**1**|Using `@CrossOrigin` at the class level. |
|-----|-----------------------------------------|
|**2**|Using `@CrossOrigin` at the method level.|

Kotlin

```
@CrossOrigin(maxAge = 3600) (1)
@RestController
@RequestMapping("/account")
class AccountController {

    @CrossOrigin("https://domain2.com") (2)
    @GetMapping("/{id}")
    suspend fun retrieve(@PathVariable id: Long): Account {
        // ...
    }

    @DeleteMapping("/{id}")
    suspend fun remove(@PathVariable id: Long) {
        // ...
    }
}
```

|**1**|Using `@CrossOrigin` at the class level. |
|-----|-----------------------------------------|
|**2**|Using `@CrossOrigin` at the method level.|

#### 1.7.4. Global Configuration

[Web MVC](web.html#mvc-cors-global)

In addition to fine-grained, controller method-level configuration, you probably want to
define some global CORS configuration, too. You can set URL-based `CorsConfiguration`mappings individually on any `HandlerMapping`. Most applications, however, use the
WebFlux Java configuration to do that.

By default global configuration enables the following:

* All origins.

* All headers.

* `GET`, `HEAD`, and `POST` methods.

`allowedCredentials` is not enabled by default, since that establishes a trust level
that exposes sensitive user-specific information( such as cookies and CSRF tokens) and
should be used only where appropriate. When it is enabled either `allowOrigins` must be
set to one or more specific domain (but not the special value `"*"`) or alternatively
the `allowOriginPatterns` property may be used to match to a dynamic set of origins.

`maxAge` is set to 30 minutes.

To enable CORS in the WebFlux Java configuration, you can use the `CorsRegistry` callback,
as the following example shows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/api/**")
            .allowedOrigins("https://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(true).maxAge(3600);

        // Add more mappings...
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun addCorsMappings(registry: CorsRegistry) {

        registry.addMapping("/api/**")
                .allowedOrigins("https://domain2.com")
                .allowedMethods("PUT", "DELETE")
                .allowedHeaders("header1", "header2", "header3")
                .exposedHeaders("header1", "header2")
                .allowCredentials(true).maxAge(3600)

        // Add more mappings...
    }
}
```

#### 1.7.5. CORS `WebFilter`

[Web MVC](web.html#mvc-cors-filter)

You can apply CORS support through the built-in[`CorsWebFilter`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/cors/reactive/CorsWebFilter.html), which is a
good fit with [functional endpoints](#webflux-fn).

|   |If you try to use the `CorsFilter` with Spring Security, keep in mind that Spring<br/>Security has[built-in support](https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors)for CORS.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

To configure the filter, you can declare a `CorsWebFilter` bean and pass a`CorsConfigurationSource` to its constructor, as the following example shows:

Java

```
@Bean
CorsWebFilter corsFilter() {

    CorsConfiguration config = new CorsConfiguration();

    // Possibly...
    // config.applyPermitDefaultValues()

    config.setAllowCredentials(true);
    config.addAllowedOrigin("https://domain1.com");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
```

Kotlin

```
@Bean
fun corsFilter(): CorsWebFilter {

    val config = CorsConfiguration()

    // Possibly...
    // config.applyPermitDefaultValues()

    config.allowCredentials = true
    config.addAllowedOrigin("https://domain1.com")
    config.addAllowedHeader("*")
    config.addAllowedMethod("*")

    val source = UrlBasedCorsConfigurationSource().apply {
        registerCorsConfiguration("/**", config)
    }
    return CorsWebFilter(source)
}
```

### 1.8. Web Security

[Web MVC](web.html#mvc-web-security)

The [Spring Security](https://projects.spring.io/spring-security/) project provides support
for protecting web applications from malicious exploits. See the Spring Security
reference documentation, including:

* [WebFlux Security](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#jc-webflux)

* [WebFlux Testing Support](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#test-webflux)

* [CSRF Protection](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#csrf)

* [Security Response Headers](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#headers)

### 1.9. View Technologies

[Web MVC](web.html#mvc-view)

The use of view technologies in Spring WebFlux is pluggable. Whether you decide to
use Thymeleaf, FreeMarker, or some other view technology is primarily a matter of a
configuration change. This chapter covers the view technologies integrated with Spring
WebFlux. We assume you are already familiar with [View Resolution](#webflux-viewresolution).

#### 1.9.1. Thymeleaf

[Web MVC](web.html#mvc-view-thymeleaf)

Thymeleaf is a modern server-side Java template engine that emphasizes natural HTML
templates that can be previewed in a browser by double-clicking, which is very
helpful for independent work on UI templates (for example, by a designer) without the need for a
running server. Thymeleaf offers an extensive set of features, and it is actively developed
and maintained. For a more complete introduction, see the[Thymeleaf](https://www.thymeleaf.org/) project home page.

The Thymeleaf integration with Spring WebFlux is managed by the Thymeleaf project. The
configuration involves a few bean declarations, such as`SpringResourceTemplateResolver`, `SpringWebFluxTemplateEngine`, and`ThymeleafReactiveViewResolver`. For more details, see[Thymeleaf+Spring](https://www.thymeleaf.org/documentation.html) and the WebFlux integration[announcement](http://forum.thymeleaf.org/Thymeleaf-3-0-8-JUST-PUBLISHED-td4030687.html).

#### 1.9.2. FreeMarker

[Web MVC](web.html#mvc-view-freemarker)

[Apache FreeMarker](https://freemarker.apache.org/) is a template engine for generating any
kind of text output from HTML to email and others. The Spring Framework has built-in
integration for using Spring WebFlux with FreeMarker templates.

##### View Configuration

[Web MVC](web.html#mvc-view-freemarker-contextconfig)

The following example shows how to configure FreeMarker as a view technology:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();
    }

    // Configure FreeMarker...

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates/freemarker");
        return configurer;
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        registry.freeMarker()
    }

    // Configure FreeMarker...

    @Bean
    fun freeMarkerConfigurer() = FreeMarkerConfigurer().apply {
        setTemplateLoaderPath("classpath:/templates/freemarker")
    }
}
```

Your templates need to be stored in the directory specified by the `FreeMarkerConfigurer`,
shown in the preceding example. Given the preceding configuration, if your controller
returns the view name, `welcome`, the resolver looks for the`classpath:/templates/freemarker/welcome.ftl` template.

##### FreeMarker Configuration

[Web MVC](web.html#mvc-views-freemarker)

You can pass FreeMarker 'Settings' and 'SharedVariables' directly to the FreeMarker`Configuration` object (which is managed by Spring) by setting the appropriate bean
properties on the `FreeMarkerConfigurer` bean. The `freemarkerSettings` property requires
a `java.util.Properties` object, and the `freemarkerVariables` property requires a`java.util.Map`. The following example shows how to use a `FreeMarkerConfigurer`:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    // ...

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        Map<String, Object> variables = new HashMap<>();
        variables.put("xml_escape", new XmlEscape());

        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates");
        configurer.setFreemarkerVariables(variables);
        return configurer;
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    // ...

    @Bean
    fun freeMarkerConfigurer() = FreeMarkerConfigurer().apply {
        setTemplateLoaderPath("classpath:/templates")
        setFreemarkerVariables(mapOf("xml_escape" to XmlEscape()))
    }
}
```

See the FreeMarker documentation for details of settings and variables as they apply to
the `Configuration` object.

##### Form Handling

[Web MVC](web.html#mvc-view-freemarker-forms)

Spring provides a tag library for use in JSPs that contains, among others, a`<spring:bind/>` element. This element primarily lets forms display values from
form-backing objects and show the results of failed validations from a `Validator` in the
web or business tier. Spring also has support for the same functionality in FreeMarker,
with additional convenience macros for generating form input elements themselves.

##### The Bind Macros#

[Web MVC](web.html#mvc-view-bind-macros)

A standard set of macros are maintained within the `spring-webflux.jar` file for
FreeMarker, so they are always available to a suitably configured application.

Some of the macros defined in the Spring templating libraries are considered internal
(private), but no such scoping exists in the macro definitions, making all macros visible
to calling code and user templates. The following sections concentrate only on the macros
you need to directly call from within your templates. If you wish to view the macro code
directly, the file is called `spring.ftl` and is in the`org.springframework.web.reactive.result.view.freemarker` package.

For additional details on binding support, see [Simple
Binding](web.html#mvc-view-simple-binding) for Spring MVC.

##### Form Macros#

For details on Spring’s form macro support for FreeMarker templates, consult the following
sections of the Spring MVC documentation.

* [Input Macros](web.html#mvc-views-form-macros)

* [Input Fields](web.html#mvc-views-form-macros-input)

* [Selection Fields](web.html#mvc-views-form-macros-select)

* [HTML Escaping](web.html#mvc-views-form-macros-html-escaping)

#### 1.9.3. Script Views

[Web MVC](web.html#mvc-view-script)

The Spring Framework has a built-in integration for using Spring WebFlux with any
templating library that can run on top of the[JSR-223](https://www.jcp.org/en/jsr/detail?id=223) Java scripting engine.
The following table shows the templating libraries that we have tested on different script engines:

|                                Scripting Library                                 |                  Scripting Engine                   |
|----------------------------------------------------------------------------------|-----------------------------------------------------|
|                     [Handlebars](https://handlebarsjs.com/)                      |[Nashorn](https://openjdk.java.net/projects/nashorn/)|
|                     [Mustache](https://mustache.github.io/)                      |[Nashorn](https://openjdk.java.net/projects/nashorn/)|
|                    [React](https://facebook.github.io/react/)                    |[Nashorn](https://openjdk.java.net/projects/nashorn/)|
|                        [EJS](https://www.embeddedjs.com/)                        |[Nashorn](https://openjdk.java.net/projects/nashorn/)|
|                [ERB](https://www.stuartellis.name/articles/erb/)                 |           [JRuby](https://www.jruby.org)            |
|[String templates](https://docs.python.org/2/library/string.html#template-strings)|          [Jython](https://www.jython.org/)          |
| [Kotlin Script templating](https://github.com/sdeleuze/kotlin-script-templating) |          [Kotlin](https://kotlinlang.org/)          |

|   |The basic rule for integrating any other script engine is that it must implement the`ScriptEngine` and `Invocable` interfaces.|
|---|------------------------------------------------------------------------------------------------------------------------------|

##### Requirements

[Web MVC](web.html#mvc-view-script-dependencies)

You need to have the script engine on your classpath, the details of which vary by script engine:

* The [Nashorn](https://openjdk.java.net/projects/nashorn/) JavaScript engine is provided with
  Java 8+. Using the latest update release available is highly recommended.

* [JRuby](https://www.jruby.org) should be added as a dependency for Ruby support.

* [Jython](https://www.jython.org) should be added as a dependency for Python support.

* `org.jetbrains.kotlin:kotlin-script-util` dependency and a `META-INF/services/javax.script.ScriptEngineFactory`file containing a `org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory`line should be added for Kotlin script support. See[this example](https://github.com/sdeleuze/kotlin-script-templating) for more detail.

You need to have the script templating library. One way to do that for JavaScript is
through [WebJars](https://www.webjars.org/).

##### Script Templates

[Web MVC](web.html#mvc-view-script-integrate)

You can declare a `ScriptTemplateConfigurer` bean to specify the script engine to use,
the script files to load, what function to call to render templates, and so on.
The following example uses Mustache templates and the Nashorn JavaScript engine:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.scriptTemplate();
    }

    @Bean
    public ScriptTemplateConfigurer configurer() {
        ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
        configurer.setEngineName("nashorn");
        configurer.setScripts("mustache.js");
        configurer.setRenderObject("Mustache");
        configurer.setRenderFunction("render");
        return configurer;
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        registry.scriptTemplate()
    }

    @Bean
    fun configurer() = ScriptTemplateConfigurer().apply {
        engineName = "nashorn"
        setScripts("mustache.js")
        renderObject = "Mustache"
        renderFunction = "render"
    }
}
```

The `render` function is called with the following parameters:

* `String template`: The template content

* `Map model`: The view model

* `RenderingContext renderingContext`: The[`RenderingContext`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/servlet/view/script/RenderingContext.html)that gives access to the application context, the locale, the template loader, and the
  URL (since 5.0)

`Mustache.render()` is natively compatible with this signature, so you can call it directly.

If your templating technology requires some customization, you can provide a script that
implements a custom render function. For example, [Handlerbars](https://handlebarsjs.com)needs to compile templates before using them and requires a[polyfill](https://en.wikipedia.org/wiki/Polyfill) in order to emulate some
browser facilities not available in the server-side script engine.
The following example shows how to set a custom render function:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.scriptTemplate();
    }

    @Bean
    public ScriptTemplateConfigurer configurer() {
        ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
        configurer.setEngineName("nashorn");
        configurer.setScripts("polyfill.js", "handlebars.js", "render.js");
        configurer.setRenderFunction("render");
        configurer.setSharedEngine(false);
        return configurer;
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        registry.scriptTemplate()
    }

    @Bean
    fun configurer() = ScriptTemplateConfigurer().apply {
        engineName = "nashorn"
        setScripts("polyfill.js", "handlebars.js", "render.js")
        renderFunction = "render"
        isSharedEngine = false
    }
}
```

|   |Setting the `sharedEngine` property to `false` is required when using non-thread-safe<br/>script engines with templating libraries not designed for concurrency, such as Handlebars or<br/>React running on Nashorn. In that case, Java SE 8 update 60 is required, due to[this bug](https://bugs.openjdk.java.net/browse/JDK-8076099), but it is generally<br/>recommended to use a recent Java SE patch release in any case.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

`polyfill.js` defines only the `window` object needed by Handlebars to run properly,
as the following snippet shows:

```
var window = {};
```

This basic `render.js` implementation compiles the template before using it. A production
ready implementation should also store and reused cached templates or pre-compiled templates.
This can be done on the script side, as well as any customization you need (managing
template engine configuration for example).
The following example shows how compile a template:

```
function render(template, model) {
    var compiledTemplate = Handlebars.compile(template);
    return compiledTemplate(model);
}
```

Check out the Spring Framework unit tests,[Java](https://github.com/spring-projects/spring-framework/tree/main/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script), and[resources](https://github.com/spring-projects/spring-framework/tree/main/spring-webflux/src/test/resources/org/springframework/web/reactive/result/view/script),
for more configuration examples.

#### 1.9.4. JSON and XML

[Web MVC](web.html#mvc-view-jackson)

For [Content Negotiation](#webflux-multiple-representations) purposes, it is useful to be able to alternate
between rendering a model with an HTML template or as other formats (such as JSON or XML),
depending on the content type requested by the client. To support doing so, Spring WebFlux
provides the `HttpMessageWriterView`, which you can use to plug in any of the available[Codecs](#webflux-codecs) from `spring-web`, such as `Jackson2JsonEncoder`, `Jackson2SmileEncoder`,
or `Jaxb2XmlEncoder`.

Unlike other view technologies, `HttpMessageWriterView` does not require a `ViewResolver`but is instead [configured](#webflux-config-view-resolvers) as a default view. You can
configure one or more such default views, wrapping different `HttpMessageWriter` instances
or `Encoder` instances. The one that matches the requested content type is used at runtime.

In most cases, a model contains multiple attributes. To determine which one to serialize,
you can configure `HttpMessageWriterView` with the name of the model attribute to use for
rendering. If the model contains only one attribute, that one is used.

### 1.10. HTTP Caching

[Web MVC](web.html#mvc-caching)

HTTP caching can significantly improve the performance of a web application. HTTP caching
revolves around the `Cache-Control` response header and subsequent conditional request
headers, such as `Last-Modified` and `ETag`. `Cache-Control` advises private (for example, browser)
and public (for example, proxy) caches how to cache and re-use responses. An `ETag` header is used
to make a conditional request that may result in a 304 (NOT\_MODIFIED) without a body,
if the content has not changed. `ETag` can be seen as a more sophisticated successor to
the `Last-Modified` header.

This section describes the HTTP caching related options available in Spring WebFlux.

#### 1.10.1. `CacheControl`

[Web MVC](web.html#mvc-caching-cachecontrol)

[`CacheControl`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/CacheControl.html) provides support for
configuring settings related to the `Cache-Control` header and is accepted as an argument
in a number of places:

* [Controllers](#webflux-caching-etag-lastmodified)

* [Static Resources](#webflux-caching-static-resources)

While [RFC 7234](https://tools.ietf.org/html/rfc7234#section-5.2.2) describes all possible
directives for the `Cache-Control` response header, the `CacheControl` type takes a
use case-oriented approach that focuses on the common scenarios, as the following example shows:

Java

```
// Cache for an hour - "Cache-Control: max-age=3600"
CacheControl ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS);

// Prevent caching - "Cache-Control: no-store"
CacheControl ccNoStore = CacheControl.noStore();

// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
CacheControl ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic();
```

Kotlin

```
// Cache for an hour - "Cache-Control: max-age=3600"
val ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS)

// Prevent caching - "Cache-Control: no-store"
val ccNoStore = CacheControl.noStore()

// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
val ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic()
```

#### 1.10.2. Controllers

[Web MVC](web.html#mvc-caching-etag-lastmodified)

Controllers can add explicit support for HTTP caching. We recommend doing so, since the`lastModified` or `ETag` value for a resource needs to be calculated before it can be compared
against conditional request headers. A controller can add an `ETag` and `Cache-Control`settings to a `ResponseEntity`, as the following example shows:

Java

```
@GetMapping("/book/{id}")
public ResponseEntity<Book> showBook(@PathVariable Long id) {

    Book book = findBook(id);
    String version = book.getVersion();

    return ResponseEntity
            .ok()
            .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
            .eTag(version) // lastModified is also available
            .body(book);
}
```

Kotlin

```
@GetMapping("/book/{id}")
fun showBook(@PathVariable id: Long): ResponseEntity<Book> {

    val book = findBook(id)
    val version = book.getVersion()

    return ResponseEntity
            .ok()
            .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
            .eTag(version) // lastModified is also available
            .body(book)
}
```

The preceding example sends a 304 (NOT\_MODIFIED) response with an empty body if the comparison
to the conditional request headers indicates the content has not changed. Otherwise, the`ETag` and `Cache-Control` headers are added to the response.

You can also make the check against conditional request headers in the controller,
as the following example shows:

Java

```
@RequestMapping
public String myHandleMethod(ServerWebExchange exchange, Model model) {

    long eTag = ... (1)

    if (exchange.checkNotModified(eTag)) {
        return null; (2)
    }

    model.addAttribute(...); (3)
    return "myViewName";
}
```

|**1**|                 Application-specific calculation.                  |
|-----|--------------------------------------------------------------------|
|**2**|Response has been set to 304 (NOT\_MODIFIED). No further processing.|
|**3**|                 Continue with request processing.                  |

Kotlin

```
@RequestMapping
fun myHandleMethod(exchange: ServerWebExchange, model: Model): String? {

    val eTag: Long = ... (1)

    if (exchange.checkNotModified(eTag)) {
        return null(2)
    }

    model.addAttribute(...) (3)
    return "myViewName"
}
```

|**1**|                 Application-specific calculation.                  |
|-----|--------------------------------------------------------------------|
|**2**|Response has been set to 304 (NOT\_MODIFIED). No further processing.|
|**3**|                 Continue with request processing.                  |

There are three variants for checking conditional requests against `eTag` values, `lastModified`values, or both. For conditional `GET` and `HEAD` requests, you can set the response to
304 (NOT\_MODIFIED). For conditional `POST`, `PUT`, and `DELETE`, you can instead set the response
to 412 (PRECONDITION\_FAILED) to prevent concurrent modification.

#### 1.10.3. Static Resources

[Web MVC](web.html#mvc-caching-static-resources)

You should serve static resources with a `Cache-Control` and conditional response headers
for optimal performance. See the section on configuring [Static Resources](#webflux-config-static-resources).

### 1.11. WebFlux Config

[Web MVC](web.html#mvc-config)

The WebFlux Java configuration declares the components that are required to process
requests with annotated controllers or functional endpoints, and it offers an API to
customize the configuration. That means you do not need to understand the underlying
beans created by the Java configuration. However, if you want to understand them,
you can see them in `WebFluxConfigurationSupport` or read more about what they are
in [Special Bean Types](#webflux-special-bean-types).

For more advanced customizations, not available in the configuration API, you can
gain full control over the configuration through the[Advanced Configuration Mode](#webflux-config-advanced-java).

#### 1.11.1. Enabling WebFlux Config

[Web MVC](web.html#mvc-config-enable)

You can use the `@EnableWebFlux` annotation in your Java config, as the following example shows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig {
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig
```

The preceding example registers a number of Spring WebFlux[infrastructure beans](#webflux-special-bean-types) and adapts to dependencies
available on the classpath — for JSON, XML, and others.

#### 1.11.2. WebFlux config API

[Web MVC](web.html#mvc-config-customize)

In your Java configuration, you can implement the `WebFluxConfigurer` interface,
as the following example shows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    // Implement configuration methods...
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    // Implement configuration methods...
}
```

#### 1.11.3. Conversion, formatting

[Web MVC](web.html#mvc-config-conversion)

By default, formatters for various number and date types are installed, along with support
for customization via `@NumberFormat` and `@DateTimeFormat` on fields.

To register custom formatters and converters in Java config, use the following:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // ...
    }

}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun addFormatters(registry: FormatterRegistry) {
        // ...
    }
}
```

By default Spring WebFlux considers the request Locale when parsing and formatting date
values. This works for forms where dates are represented as Strings with "input" form
fields. For "date" and "time" form fields, however, browsers use a fixed format defined
in the HTML spec. For such cases date and time formatting can be customized as follows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        registrar.registerFormatters(registry);
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun addFormatters(registry: FormatterRegistry) {
        val registrar = DateTimeFormatterRegistrar()
        registrar.setUseIsoFormat(true)
        registrar.registerFormatters(registry)
    }
}
```

|   |See [`FormatterRegistrar` SPI](core.html#format-FormatterRegistrar-SPI)and the `FormattingConversionServiceFactoryBean` for more information on when to<br/>use `FormatterRegistrar` implementations.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.11.4. Validation

[Web MVC](web.html#mvc-config-validation)

By default, if [Bean Validation](core.html#validation-beanvalidation-overview) is present
on the classpath (for example, the Hibernate Validator), the `LocalValidatorFactoryBean`is registered as a global [validator](core.html#validator) for use with `@Valid` and`@Validated` on `@Controller` method arguments.

In your Java configuration, you can customize the global `Validator` instance,
as the following example shows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public Validator getValidator() {
        // ...
    }

}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun getValidator(): Validator {
        // ...
    }

}
```

Note that you can also register `Validator` implementations locally,
as the following example shows:

Java

```
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(new FooValidator());
    }

}
```

Kotlin

```
@Controller
class MyController {

    @InitBinder
    protected fun initBinder(binder: WebDataBinder) {
        binder.addValidators(FooValidator())
    }
}
```

|   |If you need to have a `LocalValidatorFactoryBean` injected somewhere, create a bean and<br/>mark it with `@Primary` in order to avoid conflict with the one declared in the MVC config.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.11.5. Content Type Resolvers

[Web MVC](web.html#mvc-config-content-negotiation)

You can configure how Spring WebFlux determines the requested media types for`@Controller` instances from the request. By default, only the `Accept` header is checked,
but you can also enable a query parameter-based strategy.

The following example shows how to customize the requested content type resolution:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) {
        // ...
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureContentTypeResolver(builder: RequestedContentTypeResolverBuilder) {
        // ...
    }
}
```

#### 1.11.6. HTTP message codecs

[Web MVC](web.html#mvc-config-message-converters)

The following example shows how to customize how the request and response body are read and written:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.defaultCodecs().maxInMemorySize(512 * 1024);
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
        // ...
    }
}
```

`ServerCodecConfigurer` provides a set of default readers and writers. You can use it to add
more readers and writers, customize the default ones, or replace the default ones completely.

For Jackson JSON and XML, consider using[`Jackson2ObjectMapperBuilder`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.html),
which customizes Jackson’s default properties with the following ones:

* [`DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#FAIL_ON_UNKNOWN_PROPERTIES) is disabled.

* [`MapperFeature.DEFAULT_VIEW_INCLUSION`](https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/MapperFeature.html#DEFAULT_VIEW_INCLUSION) is disabled.

It also automatically registers the following well-known modules if they are detected on the classpath:

* [`jackson-datatype-joda`](https://github.com/FasterXML/jackson-datatype-joda): Support for Joda-Time types.

* [`jackson-datatype-jsr310`](https://github.com/FasterXML/jackson-datatype-jsr310): Support for Java 8 Date and Time API types.

* [`jackson-datatype-jdk8`](https://github.com/FasterXML/jackson-datatype-jdk8): Support for other Java 8 types, such as `Optional`.

* [`jackson-module-kotlin`](https://github.com/FasterXML/jackson-module-kotlin): Support for Kotlin classes and data classes.

#### 1.11.7. View Resolvers

[Web MVC](web.html#mvc-config-view-resolvers)

The following example shows how to configure view resolution:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // ...
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        // ...
    }
}
```

The `ViewResolverRegistry` has shortcuts for view technologies with which the Spring Framework
integrates. The following example uses FreeMarker (which also requires configuring the
underlying FreeMarker view technology):

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();
    }

    // Configure Freemarker...

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates");
        return configurer;
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        registry.freeMarker()
    }

    // Configure Freemarker...

    @Bean
    fun freeMarkerConfigurer() = FreeMarkerConfigurer().apply {
        setTemplateLoaderPath("classpath:/templates")
    }
}
```

You can also plug in any `ViewResolver` implementation, as the following example shows:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ViewResolver resolver = ... ;
        registry.viewResolver(resolver);
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        val resolver: ViewResolver = ...
        registry.viewResolver(resolver
    }
}
```

To support [Content Negotiation](#webflux-multiple-representations) and rendering other formats
through view resolution (besides HTML), you can configure one or more default views based
on the `HttpMessageWriterView` implementation, which accepts any of the available[Codecs](#webflux-codecs) from `spring-web`. The following example shows how to do so:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();

        Jackson2JsonEncoder encoder = new Jackson2JsonEncoder();
        registry.defaultViews(new HttpMessageWriterView(encoder));
    }

    // ...
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        registry.freeMarker()

        val encoder = Jackson2JsonEncoder()
        registry.defaultViews(HttpMessageWriterView(encoder))
    }

    // ...
}
```

See [View Technologies](#webflux-view) for more on the view technologies that are integrated with Spring WebFlux.

#### 1.11.8. Static Resources

[Web MVC](web.html#mvc-config-static-resources)

This option provides a convenient way to serve static resources from a list of[`Resource`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/io/Resource.html)-based locations.

In the next example, given a request that starts with `/resources`, the relative path is
used to find and serve static resources relative to `/static` on the classpath. Resources
are served with a one-year future expiration to ensure maximum use of the browser cache
and a reduction in HTTP requests made by the browser. The `Last-Modified` header is also
evaluated and, if present, a `304` status code is returned. The following list shows
the example:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public", "classpath:/static/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
    }

}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public", "classpath:/static/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
    }
}
```

The resource handler also supports a chain of[`ResourceResolver`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/resource/ResourceResolver.html) implementations and[`ResourceTransformer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/resource/ResourceTransformer.html) implementations,
which can be used to create a toolchain for working with optimized resources.

You can use the `VersionResourceResolver` for versioned resource URLs based on an MD5 hash
computed from the content, a fixed application version, or other information. A`ContentVersionStrategy` (MD5 hash) is a good choice with some notable exceptions (such as
JavaScript resources used with a module loader).

The following example shows how to use `VersionResourceResolver` in your Java configuration:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public/")
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }

}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public/")
                .resourceChain(true)
                .addResolver(VersionResourceResolver().addContentVersionStrategy("/**"))
    }

}
```

You can use `ResourceUrlProvider` to rewrite URLs and apply the full chain of resolvers and
transformers (for example, to insert versions). The WebFlux configuration provides a `ResourceUrlProvider`so that it can be injected into others.

Unlike Spring MVC, at present, in WebFlux, there is no way to transparently rewrite static
resource URLs, since there are no view technologies that can make use of a non-blocking chain
of resolvers and transformers. When serving only local resources, the workaround is to use`ResourceUrlProvider` directly (for example, through a custom element) and block.

Note that, when using both `EncodedResourceResolver` (for example, Gzip, Brotli encoded) and`VersionedResourceResolver`, they must be registered in that order, to ensure content-based
versions are always computed reliably based on the unencoded file.

[WebJars](https://www.webjars.org/documentation) are also supported through the`WebJarsResourceResolver` which is automatically registered when the`org.webjars:webjars-locator-core` library is present on the classpath. The resolver can
re-write URLs to include the version of the jar and can also match against incoming URLs
without versions — for example, from `/jquery/jquery.min.js` to`/jquery/1.2.0/jquery.min.js`.

|   |The Java configuration based on `ResourceHandlerRegistry` provides further options<br/>for fine-grained control, e.g. last-modified behavior and optimized resource resolution.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.11.9. Path Matching

[Web MVC](web.html#mvc-config-path-matching)

You can customize options related to path matching. For details on the individual options, see the[`PathMatchConfigurer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/reactive/config/PathMatchConfigurer.html) javadoc.
The following example shows how to use `PathMatchConfigurer`:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
            .setUseCaseSensitiveMatch(true)
            .setUseTrailingSlashMatch(false)
            .addPathPrefix("/api",
                    HandlerTypePredicate.forAnnotation(RestController.class));
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    @Override
    fun configurePathMatch(configurer: PathMatchConfigurer) {
        configurer
            .setUseCaseSensitiveMatch(true)
            .setUseTrailingSlashMatch(false)
            .addPathPrefix("/api",
                    HandlerTypePredicate.forAnnotation(RestController::class.java))
    }
}
```

|   |Spring WebFlux relies on a parsed representation of the request path called`RequestPath` for access to decoded path segment values, with semicolon content removed<br/>(that is, path or matrix variables). That means, unlike in Spring MVC, you need not indicate<br/>whether to decode the request path nor whether to remove semicolon content for<br/>path matching purposes.<br/><br/>Spring WebFlux also does not support suffix pattern matching, unlike in Spring MVC, where we<br/>are also [recommend](web.html#mvc-ann-requestmapping-suffix-pattern-match) moving away from<br/>reliance on it.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.11.10. WebSocketService

The WebFlux Java config declares of a `WebSocketHandlerAdapter` bean which provides
support for the invocation of WebSocket handlers. That means all that remains to do in
order to handle a WebSocket handshake request is to map a `WebSocketHandler` to a URL
via `SimpleUrlHandlerMapping`.

In some cases it may be necessary to create the `WebSocketHandlerAdapter` bean with a
provided `WebSocketService` service which allows configuring WebSocket server properties.
For example:

Java

```
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public WebSocketService getWebSocketService() {
        TomcatRequestUpgradeStrategy strategy = new TomcatRequestUpgradeStrategy();
        strategy.setMaxSessionIdleTimeout(0L);
        return new HandshakeWebSocketService(strategy);
    }
}
```

Kotlin

```
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

    @Override
    fun webSocketService(): WebSocketService {
        val strategy = TomcatRequestUpgradeStrategy().apply {
            setMaxSessionIdleTimeout(0L)
        }
        return HandshakeWebSocketService(strategy)
    }
}
```

#### 1.11.11. Advanced Configuration Mode

[Web MVC](web.html#mvc-config-advanced-java)

`@EnableWebFlux` imports `DelegatingWebFluxConfiguration` that:

* Provides default Spring configuration for WebFlux applications

* detects and delegates to `WebFluxConfigurer` implementations to customize that configuration.

For advanced mode, you can remove `@EnableWebFlux` and extend directly from`DelegatingWebFluxConfiguration` instead of implementing `WebFluxConfigurer`,
as the following example shows:

Java

```
@Configuration
public class WebConfig extends DelegatingWebFluxConfiguration {

    // ...
}
```

Kotlin

```
@Configuration
class WebConfig : DelegatingWebFluxConfiguration {

    // ...
}
```

You can keep existing methods in `WebConfig`, but you can now also override bean declarations
from the base class and still have any number of other `WebMvcConfigurer` implementations on
the classpath.

### 1.12. HTTP/2

[Web MVC](web.html#mvc-http2)

HTTP/2 is supported with Reactor Netty, Tomcat, Jetty, and Undertow. However, there are
considerations related to server configuration. For more details, see the[HTTP/2 wiki page](https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support).

## 2. WebClient

Spring WebFlux includes a client to perform HTTP requests with. `WebClient` has a
functional, fluent API based on Reactor, see [Reactive Libraries](#webflux-reactive-libraries),
which enables declarative composition of asynchronous logic without the need to deal with
threads or concurrency. It is fully non-blocking, it supports streaming, and relies on
the same [codecs](#webflux-codecs) that are also used to encode and
decode request and response content on the server side.

`WebClient` needs an HTTP client library to perform requests with. There is built-in
support for the following:

* [Reactor Netty](https://github.com/reactor/reactor-netty)

* [Jetty Reactive HttpClient](https://github.com/jetty-project/jetty-reactive-httpclient)

* [Apache HttpComponents](https://hc.apache.org/index.html)

* Others can be plugged via `ClientHttpConnector`.

### 2.1. Configuration

The simplest way to create a `WebClient` is through one of the static factory methods:

* `WebClient.create()`

* `WebClient.create(String baseUrl)`

You can also use `WebClient.builder()` with further options:

* `uriBuilderFactory`: Customized `UriBuilderFactory` to use as a base URL.

* `defaultUriVariables`: default values to use when expanding URI templates.

* `defaultHeader`: Headers for every request.

* `defaultCookie`: Cookies for every request.

* `defaultRequest`: `Consumer` to customize every request.

* `filter`: Client filter for every request.

* `exchangeStrategies`: HTTP message reader/writer customizations.

* `clientConnector`: HTTP client library settings.

For example:

Java

```
WebClient client = WebClient.builder()
        .codecs(configurer -> ... )
        .build();
```

Kotlin

```
val webClient = WebClient.builder()
        .codecs { configurer -> ... }
        .build()
```

Once built, a `WebClient` is immutable. However, you can clone it and build a
modified copy as follows:

Java

```
WebClient client1 = WebClient.builder()
        .filter(filterA).filter(filterB).build();

WebClient client2 = client1.mutate()
        .filter(filterC).filter(filterD).build();

// client1 has filterA, filterB

// client2 has filterA, filterB, filterC, filterD
```

Kotlin

```
val client1 = WebClient.builder()
        .filter(filterA).filter(filterB).build()

val client2 = client1.mutate()
        .filter(filterC).filter(filterD).build()

// client1 has filterA, filterB

// client2 has filterA, filterB, filterC, filterD
```

#### 2.1.1. MaxInMemorySize

Codecs have [limits](#webflux-codecs-limits) for buffering data in
memory to avoid application memory issues. By default those are set to 256KB.
If that’s not enough you’ll get the following error:

```
org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer
```

To change the limit for default codecs, use the following:

Java

```
WebClient webClient = WebClient.builder()
        .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
        .build();
```

Kotlin

```
val webClient = WebClient.builder()
        .codecs { configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024) }
        .build()
```

#### 2.1.2. Reactor Netty

To customize Reactor Netty settings, provide a pre-configured `HttpClient`:

Java

```
HttpClient httpClient = HttpClient.create().secure(sslSpec -> ...);

WebClient webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();
```

Kotlin

```
val httpClient = HttpClient.create().secure { ... }

val webClient = WebClient.builder()
    .clientConnector(ReactorClientHttpConnector(httpClient))
    .build()
```

##### Resources

By default, `HttpClient` participates in the global Reactor Netty resources held in`reactor.netty.http.HttpResources`, including event loop threads and a connection pool.
This is the recommended mode, since fixed, shared resources are preferred for event loop
concurrency. In this mode global resources remain active until the process exits.

If the server is timed with the process, there is typically no need for an explicit
shutdown. However, if the server can start or stop in-process (for example, a Spring MVC
application deployed as a WAR), you can declare a Spring-managed bean of type`ReactorResourceFactory` with `globalResources=true` (the default) to ensure that the Reactor
Netty global resources are shut down when the Spring `ApplicationContext` is closed,
as the following example shows:

Java

```
@Bean
public ReactorResourceFactory reactorResourceFactory() {
    return new ReactorResourceFactory();
}
```

Kotlin

```
@Bean
fun reactorResourceFactory() = ReactorResourceFactory()
```

You can also choose not to participate in the global Reactor Netty resources. However,
in this mode, the burden is on you to ensure that all Reactor Netty client and server
instances use shared resources, as the following example shows:

Java

```
@Bean
public ReactorResourceFactory resourceFactory() {
    ReactorResourceFactory factory = new ReactorResourceFactory();
    factory.setUseGlobalResources(false); (1)
    return factory;
}

@Bean
public WebClient webClient() {

    Function<HttpClient, HttpClient> mapper = client -> {
        // Further customizations...
    };

    ClientHttpConnector connector =
            new ReactorClientHttpConnector(resourceFactory(), mapper); (2)

    return WebClient.builder().clientConnector(connector).build(); (3)
}
```

|**1**|             Create resources independent of global ones.              |
|-----|-----------------------------------------------------------------------|
|**2**|Use the `ReactorClientHttpConnector` constructor with resource factory.|
|**3**|           Plug the connector into the `WebClient.Builder`.            |

Kotlin

```
@Bean
fun resourceFactory() = ReactorResourceFactory().apply {
    isUseGlobalResources = false (1)
}

@Bean
fun webClient(): WebClient {

    val mapper: (HttpClient) -> HttpClient = {
        // Further customizations...
    }

    val connector = ReactorClientHttpConnector(resourceFactory(), mapper) (2)

    return WebClient.builder().clientConnector(connector).build() (3)
}
```

|**1**|             Create resources independent of global ones.              |
|-----|-----------------------------------------------------------------------|
|**2**|Use the `ReactorClientHttpConnector` constructor with resource factory.|
|**3**|           Plug the connector into the `WebClient.Builder`.            |

##### Timeouts

To configure a connection timeout:

Java

```
import io.netty.channel.ChannelOption;

HttpClient httpClient = HttpClient.create()
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

WebClient webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();
```

Kotlin

```
import io.netty.channel.ChannelOption

val httpClient = HttpClient.create()
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

val webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();
```

To configure a read or write timeout:

Java

```
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

HttpClient httpClient = HttpClient.create()
        .doOnConnected(conn -> conn
                .addHandlerLast(new ReadTimeoutHandler(10))
                .addHandlerLast(new WriteTimeoutHandler(10)));

// Create WebClient...
```

Kotlin

```
import io.netty.handler.timeout.ReadTimeoutHandler
import io.netty.handler.timeout.WriteTimeoutHandler

val httpClient = HttpClient.create()
        .doOnConnected { conn -> conn
                .addHandlerLast(new ReadTimeoutHandler(10))
                .addHandlerLast(new WriteTimeoutHandler(10))
        }

// Create WebClient...
```

To configure a response timeout for all requests:

Java

```
HttpClient httpClient = HttpClient.create()
        .responseTimeout(Duration.ofSeconds(2));

// Create WebClient...
```

Kotlin

```
val httpClient = HttpClient.create()
        .responseTimeout(Duration.ofSeconds(2));

// Create WebClient...
```

To configure a response timeout for a specific request:

Java

```
WebClient.create().get()
        .uri("https://example.org/path")
        .httpRequest(httpRequest -> {
            HttpClientRequest reactorRequest = httpRequest.getNativeRequest();
            reactorRequest.responseTimeout(Duration.ofSeconds(2));
        })
        .retrieve()
        .bodyToMono(String.class);
```

Kotlin

```
WebClient.create().get()
        .uri("https://example.org/path")
        .httpRequest { httpRequest: ClientHttpRequest ->
            val reactorRequest = httpRequest.getNativeRequest<HttpClientRequest>()
            reactorRequest.responseTimeout(Duration.ofSeconds(2))
        }
        .retrieve()
        .bodyToMono(String::class.java)
```

#### 2.1.3. Jetty

The following example shows how to customize Jetty `HttpClient` settings:

Java

```
HttpClient httpClient = new HttpClient();
httpClient.setCookieStore(...);

WebClient webClient = WebClient.builder()
        .clientConnector(new JettyClientHttpConnector(httpClient))
        .build();
```

Kotlin

```
val httpClient = HttpClient()
httpClient.cookieStore = ...

val webClient = WebClient.builder()
        .clientConnector(new JettyClientHttpConnector(httpClient))
        .build();
```

By default, `HttpClient` creates its own resources (`Executor`, `ByteBufferPool`, `Scheduler`),
which remain active until the process exits or `stop()` is called.

You can share resources between multiple instances of the Jetty client (and server) and
ensure that the resources are shut down when the Spring `ApplicationContext` is closed by
declaring a Spring-managed bean of type `JettyResourceFactory`, as the following example
shows:

Java

```
@Bean
public JettyResourceFactory resourceFactory() {
    return new JettyResourceFactory();
}

@Bean
public WebClient webClient() {

    HttpClient httpClient = new HttpClient();
    // Further customizations...

    ClientHttpConnector connector =
            new JettyClientHttpConnector(httpClient, resourceFactory()); (1)

    return WebClient.builder().clientConnector(connector).build(); (2)
}
```

|**1**|Use the `JettyClientHttpConnector` constructor with resource factory.|
|-----|---------------------------------------------------------------------|
|**2**|          Plug the connector into the `WebClient.Builder`.           |

Kotlin

```
@Bean
fun resourceFactory() = JettyResourceFactory()

@Bean
fun webClient(): WebClient {

    val httpClient = HttpClient()
    // Further customizations...

    val connector = JettyClientHttpConnector(httpClient, resourceFactory()) (1)

    return WebClient.builder().clientConnector(connector).build() (2)
}
```

|**1**|Use the `JettyClientHttpConnector` constructor with resource factory.|
|-----|---------------------------------------------------------------------|
|**2**|          Plug the connector into the `WebClient.Builder`.           |

#### 2.1.4. HttpComponents

The following example shows how to customize Apache HttpComponents `HttpClient` settings:

Java

```
HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
clientBuilder.setDefaultRequestConfig(...);
CloseableHttpAsyncClient client = clientBuilder.build();
ClientHttpConnector connector = new HttpComponentsClientHttpConnector(client);

WebClient webClient = WebClient.builder().clientConnector(connector).build();
```

Kotlin

```
val client = HttpAsyncClients.custom().apply {
    setDefaultRequestConfig(...)
}.build()
val connector = HttpComponentsClientHttpConnector(client)
val webClient = WebClient.builder().clientConnector(connector).build()
```

### 2.2. `retrieve()`

The `retrieve()` method can be used to declare how to extract the response. For example:

Java

```
WebClient client = WebClient.create("https://example.org");

Mono<ResponseEntity<Person>> result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .toEntity(Person.class);
```

Kotlin

```
val client = WebClient.create("https://example.org")

val result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .toEntity<Person>().awaitSingle()
```

Or to get only the body:

Java

```
WebClient client = WebClient.create("https://example.org");

Mono<Person> result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToMono(Person.class);
```

Kotlin

```
val client = WebClient.create("https://example.org")

val result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .awaitBody<Person>()
```

To get a stream of decoded objects:

Java

```
Flux<Quote> result = client.get()
        .uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM)
        .retrieve()
        .bodyToFlux(Quote.class);
```

Kotlin

```
val result = client.get()
        .uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM)
        .retrieve()
        .bodyToFlow<Quote>()
```

By default, 4xx or 5xx responses result in an `WebClientResponseException`, including
sub-classes for specific HTTP status codes. To customize the handling of error
responses, use `onStatus` handlers as follows:

Java

```
Mono<Person> result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError, response -> ...)
        .onStatus(HttpStatus::is5xxServerError, response -> ...)
        .bodyToMono(Person.class);
```

Kotlin

```
val result = client.get()
        .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError) { ... }
        .onStatus(HttpStatus::is5xxServerError) { ... }
        .awaitBody<Person>()
```

### 2.3. Exchange

The `exchangeToMono()` and `exchangeToFlux()` methods (or `awaitExchange { }` and `exchangeToFlow { }` in Kotlin)
are useful for more advanced cases that require more control, such as to decode the response differently
depending on the response status:

Java

```
Mono<Person> entityMono = client.get()
        .uri("/persons/1")
        .accept(MediaType.APPLICATION_JSON)
        .exchangeToMono(response -> {
            if (response.statusCode().equals(HttpStatus.OK)) {
                return response.bodyToMono(Person.class);
            }
            else {
                // Turn to error
                return response.createException().flatMap(Mono::error);
            }
        });
```

Kotlin

```
val entity = client.get()
  .uri("/persons/1")
  .accept(MediaType.APPLICATION_JSON)
  .awaitExchange {
        if (response.statusCode() == HttpStatus.OK) {
             return response.awaitBody<Person>()
        }
        else {
             throw response.createExceptionAndAwait()
        }
  }
```

When using the above, after the returned `Mono` or `Flux` completes, the response body
is checked and if not consumed it is released to prevent memory and connection leaks.
Therefore the response cannot be decoded further downstream. It is up to the provided
function to declare how to decode the response if needed.

### 2.4. Request Body

The request body can be encoded from any asynchronous type handled by `ReactiveAdapterRegistry`,
like `Mono` or Kotlin Coroutines `Deferred` as the following example shows:

Java

```
Mono<Person> personMono = ... ;

Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .body(personMono, Person.class)
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
val personDeferred: Deferred<Person> = ...

client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .body<Person>(personDeferred)
        .retrieve()
        .awaitBody<Unit>()
```

You can also have a stream of objects be encoded, as the following example shows:

Java

```
Flux<Person> personFlux = ... ;

Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_STREAM_JSON)
        .body(personFlux, Person.class)
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
val people: Flow<Person> = ...

client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .body(people)
        .retrieve()
        .awaitBody<Unit>()
```

Alternatively, if you have the actual value, you can use the `bodyValue` shortcut method,
as the following example shows:

Java

```
Person person = ... ;

Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(person)
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
val person: Person = ...

client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(person)
        .retrieve()
        .awaitBody<Unit>()
```

#### 2.4.1. Form Data

To send form data, you can provide a `MultiValueMap<String, String>` as the body. Note that the
content is automatically set to `application/x-www-form-urlencoded` by the`FormHttpMessageWriter`. The following example shows how to use `MultiValueMap<String, String>`:

Java

```
MultiValueMap<String, String> formData = ... ;

Mono<Void> result = client.post()
        .uri("/path", id)
        .bodyValue(formData)
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
val formData: MultiValueMap<String, String> = ...

client.post()
        .uri("/path", id)
        .bodyValue(formData)
        .retrieve()
        .awaitBody<Unit>()
```

You can also supply form data in-line by using `BodyInserters`, as the following example shows:

Java

```
import static org.springframework.web.reactive.function.BodyInserters.*;

Mono<Void> result = client.post()
        .uri("/path", id)
        .body(fromFormData("k1", "v1").with("k2", "v2"))
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
import org.springframework.web.reactive.function.BodyInserters.*

client.post()
        .uri("/path", id)
        .body(fromFormData("k1", "v1").with("k2", "v2"))
        .retrieve()
        .awaitBody<Unit>()
```

#### 2.4.2. Multipart Data

To send multipart data, you need to provide a `MultiValueMap<String, ?>` whose values are
either `Object` instances that represent part content or `HttpEntity` instances that represent the content and
headers for a part. `MultipartBodyBuilder` provides a convenient API to prepare a
multipart request. The following example shows how to create a `MultiValueMap<String, ?>`:

Java

```
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("fieldPart", "fieldValue");
builder.part("filePart1", new FileSystemResource("...logo.png"));
builder.part("jsonPart", new Person("Jason"));
builder.part("myPart", part); // Part from a server request

MultiValueMap<String, HttpEntity<?>> parts = builder.build();
```

Kotlin

```
val builder = MultipartBodyBuilder().apply {
    part("fieldPart", "fieldValue")
    part("filePart1", new FileSystemResource("...logo.png"))
    part("jsonPart", new Person("Jason"))
    part("myPart", part) // Part from a server request
}

val parts = builder.build()
```

In most cases, you do not have to specify the `Content-Type` for each part. The content
type is determined automatically based on the `HttpMessageWriter` chosen to serialize it
or, in the case of a `Resource`, based on the file extension. If necessary, you can
explicitly provide the `MediaType` to use for each part through one of the overloaded
builder `part` methods.

Once a `MultiValueMap` is prepared, the easiest way to pass it to the `WebClient` is
through the `body` method, as the following example shows:

Java

```
MultipartBodyBuilder builder = ...;

Mono<Void> result = client.post()
        .uri("/path", id)
        .body(builder.build())
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
val builder: MultipartBodyBuilder = ...

client.post()
        .uri("/path", id)
        .body(builder.build())
        .retrieve()
        .awaitBody<Unit>()
```

If the `MultiValueMap` contains at least one non-`String` value, which could also
represent regular form data (that is, `application/x-www-form-urlencoded`), you need not
set the `Content-Type` to `multipart/form-data`. This is always the case when using`MultipartBodyBuilder`, which ensures an `HttpEntity` wrapper.

As an alternative to `MultipartBodyBuilder`, you can also provide multipart content,
inline-style, through the built-in `BodyInserters`, as the following example shows:

Java

```
import static org.springframework.web.reactive.function.BodyInserters.*;

Mono<Void> result = client.post()
        .uri("/path", id)
        .body(fromMultipartData("fieldPart", "value").with("filePart", resource))
        .retrieve()
        .bodyToMono(Void.class);
```

Kotlin

```
import org.springframework.web.reactive.function.BodyInserters.*

client.post()
        .uri("/path", id)
        .body(fromMultipartData("fieldPart", "value").with("filePart", resource))
        .retrieve()
        .awaitBody<Unit>()
```

### 2.5. Filters

You can register a client filter (`ExchangeFilterFunction`) through the `WebClient.Builder`in order to intercept and modify requests, as the following example shows:

Java

```
WebClient client = WebClient.builder()
        .filter((request, next) -> {

            ClientRequest filtered = ClientRequest.from(request)
                    .header("foo", "bar")
                    .build();

            return next.exchange(filtered);
        })
        .build();
```

Kotlin

```
val client = WebClient.builder()
        .filter { request, next ->

            val filtered = ClientRequest.from(request)
                    .header("foo", "bar")
                    .build()

            next.exchange(filtered)
        }
        .build()
```

This can be used for cross-cutting concerns, such as authentication. The following example uses
a filter for basic authentication through a static factory method:

Java

```
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = WebClient.builder()
        .filter(basicAuthentication("user", "password"))
        .build();
```

Kotlin

```
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication

val client = WebClient.builder()
        .filter(basicAuthentication("user", "password"))
        .build()
```

Filters can be added or removed by mutating an existing `WebClient` instance, resulting
in a new `WebClient` instance that does not affect the original one. For example:

Java

```
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = webClient.mutate()
        .filters(filterList -> {
            filterList.add(0, basicAuthentication("user", "password"));
        })
        .build();
```

Kotlin

```
val client = webClient.mutate()
        .filters { it.add(0, basicAuthentication("user", "password")) }
        .build()
```

`WebClient` is a thin facade around the chain of filters followed by an`ExchangeFunction`. It provides a workflow to make requests, to encode to and from higher
level objects, and it helps to ensure that response content is always consumed.
When filters handle the response in some way, extra care must be taken to always consume
its content or to otherwise propagate it downstream to the `WebClient` which will ensure
the same. Below is a filter that handles the `UNAUTHORIZED` status code but ensures that
any response content, whether expected or not, is released:

Java

```
public ExchangeFilterFunction renewTokenFilter() {
    return (request, next) -> next.exchange(request).flatMap(response -> {
        if (response.statusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
            return response.releaseBody()
                    .then(renewToken())
                    .flatMap(token -> {
                        ClientRequest newRequest = ClientRequest.from(request).build();
                        return next.exchange(newRequest);
                    });
        } else {
            return Mono.just(response);
        }
    });
}
```

Kotlin

```
fun renewTokenFilter(): ExchangeFilterFunction? {
    return ExchangeFilterFunction { request: ClientRequest?, next: ExchangeFunction ->
        next.exchange(request!!).flatMap { response: ClientResponse ->
            if (response.statusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
                [email protected] response.releaseBody()
                        .then(renewToken())
                        .flatMap { token: String? ->
                            val newRequest = ClientRequest.from(request).build()
                            next.exchange(newRequest)
                        }
            } else {
                [email protected] Mono.just(response)
            }
        }
    }
}
```

### 2.6. Attributes

You can add attributes to a request. This is convenient if you want to pass information
through the filter chain and influence the behavior of filters for a given request.
For example:

Java

```
WebClient client = WebClient.builder()
        .filter((request, next) -> {
            Optional<Object> usr = request.attribute("myAttribute");
            // ...
        })
        .build();

client.get().uri("https://example.org/")
        .attribute("myAttribute", "...")
        .retrieve()
        .bodyToMono(Void.class);

    }
```

Kotlin

```
val client = WebClient.builder()
        .filter { request, _ ->
            val usr = request.attributes()["myAttribute"];
            // ...
        }
        .build()

    client.get().uri("https://example.org/")
            .attribute("myAttribute", "...")
            .retrieve()
            .awaitBody<Unit>()
```

Note that you can configure a `defaultRequest` callback globally at the`WebClient.Builder` level which lets you insert attributes into all requests,
which could be used for example in a Spring MVC application to populate
request attributes based on `ThreadLocal` data.

### 2.7. Context

[Attributes](#webflux-client-attributes) provide a convenient way to pass information to the filter
chain but they only influence the current request. If you want to pass information that
propagates to additional requests that are nested, e.g. via `flatMap`, or executed after,
e.g. via `concatMap`, then you’ll need to use the Reactor `Context`.

The Reactor `Context` needs to be populated at the end of a reactive chain in order to
apply to all operations. For example:

Java

```
WebClient client = WebClient.builder()
        .filter((request, next) ->
                Mono.deferContextual(contextView -> {
                    String value = contextView.get("foo");
                    // ...
                }))
        .build();

client.get().uri("https://example.org/")
        .retrieve()
        .bodyToMono(String.class)
        .flatMap(body -> {
                // perform nested request (context propagates automatically)...
        })
        .contextWrite(context -> context.put("foo", ...));
```

### 2.8. Synchronous Use

`WebClient` can be used in synchronous style by blocking at the end for the result:

Java

```
Person person = client.get().uri("/person/{id}", i).retrieve()
    .bodyToMono(Person.class)
    .block();

List<Person> persons = client.get().uri("/persons").retrieve()
    .bodyToFlux(Person.class)
    .collectList()
    .block();
```

Kotlin

```
val person = runBlocking {
    client.get().uri("/person/{id}", i).retrieve()
            .awaitBody<Person>()
}

val persons = runBlocking {
    client.get().uri("/persons").retrieve()
            .bodyToFlow<Person>()
            .toList()
}
```

However if multiple calls need to be made, it’s more efficient to avoid blocking on each
response individually, and instead wait for the combined result:

Java

```
Mono<Person> personMono = client.get().uri("/person/{id}", personId)
        .retrieve().bodyToMono(Person.class);

Mono<List<Hobby>> hobbiesMono = client.get().uri("/person/{id}/hobbies", personId)
        .retrieve().bodyToFlux(Hobby.class).collectList();

Map<String, Object> data = Mono.zip(personMono, hobbiesMono, (person, hobbies) -> {
            Map<String, String> map = new LinkedHashMap<>();
            map.put("person", person);
            map.put("hobbies", hobbies);
            return map;
        })
        .block();
```

Kotlin

```
val data = runBlocking {
        val personDeferred = async {
            client.get().uri("/person/{id}", personId)
                    .retrieve().awaitBody<Person>()
        }

        val hobbiesDeferred = async {
            client.get().uri("/person/{id}/hobbies", personId)
                    .retrieve().bodyToFlow<Hobby>().toList()
        }

        mapOf("person" to personDeferred.await(), "hobbies" to hobbiesDeferred.await())
    }
```

The above is merely one example. There are lots of other patterns and operators for putting
together a reactive pipeline that makes many remote calls, potentially some nested,
inter-dependent, without ever blocking until the end.

|   |With `Flux` or `Mono`, you should never have to block in a Spring MVC or Spring WebFlux controller.<br/>Simply return the resulting reactive type from the controller method. The same principle apply to<br/>Kotlin Coroutines and Spring WebFlux, just use suspending function or return `Flow` in your<br/>controller method .|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 2.9. Testing

To test code that uses the `WebClient`, you can use a mock web server, such as the[OkHttp MockWebServer](https://github.com/square/okhttp#mockwebserver). To see an example
of its use, check out[`WebClientIntegrationTests`](https://github.com/spring-projects/spring-framework/tree/main/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java)in the Spring Framework test suite or the[`static-server`](https://github.com/square/okhttp/tree/master/samples/static-server)sample in the OkHttp repository.

## 3. WebSockets

[Same as in the Servlet stack](web.html#websocket)

This part of the reference documentation covers support for reactive-stack WebSocket
messaging.

### 3.1. Introduction to WebSocket

The WebSocket protocol, [RFC 6455](https://tools.ietf.org/html/rfc6455), provides a standardized
way to establish a full-duplex, two-way communication channel between client and server
over a single TCP connection. It is a different TCP protocol from HTTP but is designed to
work over HTTP, using ports 80 and 443 and allowing re-use of existing firewall rules.

A WebSocket interaction begins with an HTTP request that uses the HTTP `Upgrade` header
to upgrade or, in this case, to switch to the WebSocket protocol. The following example
shows such an interaction:

```
GET /spring-websocket-portfolio/portfolio HTTP/1.1
Host: localhost:8080
Upgrade: websocket (1)
Connection: Upgrade (2)
Sec-WebSocket-Key: Uc9l9TMkWGbHFD2qnFHltg==
Sec-WebSocket-Protocol: v10.stomp, v11.stomp
Sec-WebSocket-Version: 13
Origin: http://localhost:8080
```

|**1**|     The `Upgrade` header.     |
|-----|-------------------------------|
|**2**|Using the `Upgrade` connection.|

Instead of the usual 200 status code, a server with WebSocket support returns output
similar to the following:

```
HTTP/1.1 101 Switching Protocols (1)
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 1qVdfYHU9hPOl4JYYNXF623Gzn0=
Sec-WebSocket-Protocol: v10.stomp
```

|**1**|Protocol switch|
|-----|---------------|

After a successful handshake, the TCP socket underlying the HTTP upgrade request remains
open for both the client and the server to continue to send and receive messages.

A complete introduction of how WebSockets work is beyond the scope of this document.
See RFC 6455, the WebSocket chapter of HTML5, or any of the many introductions and
tutorials on the Web.

Note that, if a WebSocket server is running behind a web server (e.g. nginx), you
likely need to configure it to pass WebSocket upgrade requests on to the WebSocket
server. Likewise, if the application runs in a cloud environment, check the
instructions of the cloud provider related to WebSocket support.

#### 3.1.1. HTTP Versus WebSocket

Even though WebSocket is designed to be HTTP-compatible and starts with an HTTP request,
it is important to understand that the two protocols lead to very different
architectures and application programming models.

In HTTP and REST, an application is modeled as many URLs. To interact with the application,
clients access those URLs, request-response style. Servers route requests to the
appropriate handler based on the HTTP URL, method, and headers.

By contrast, in WebSockets, there is usually only one URL for the initial connect.
Subsequently, all application messages flow on that same TCP connection. This points to
an entirely different asynchronous, event-driven, messaging architecture.

WebSocket is also a low-level transport protocol, which, unlike HTTP, does not prescribe
any semantics to the content of messages. That means that there is no way to route or process
a message unless the client and the server agree on message semantics.

WebSocket clients and servers can negotiate the use of a higher-level, messaging protocol
(for example, STOMP), through the `Sec-WebSocket-Protocol` header on the HTTP handshake request.
In the absence of that, they need to come up with their own conventions.

#### 3.1.2. When to Use WebSockets

WebSockets can make a web page be dynamic and interactive. However, in many cases,
a combination of Ajax and HTTP streaming or long polling can provide a simple and
effective solution.

For example, news, mail, and social feeds need to update dynamically, but it may be
perfectly okay to do so every few minutes. Collaboration, games, and financial apps, on
the other hand, need to be much closer to real-time.

Latency alone is not a deciding factor. If the volume of messages is relatively low (for example,
monitoring network failures) HTTP streaming or polling can provide an effective solution.
It is the combination of low latency, high frequency, and high volume that make the best
case for the use of WebSocket.

Keep in mind also that over the Internet, restrictive proxies that are outside of your control
may preclude WebSocket interactions, either because they are not configured to pass on the`Upgrade` header or because they close long-lived connections that appear idle. This
means that the use of WebSocket for internal applications within the firewall is a more
straightforward decision than it is for public facing applications.

### 3.2. WebSocket API

[Same as in the Servlet stack](web.html#websocket-server)

The Spring Framework provides a WebSocket API that you can use to write client- and
server-side applications that handle WebSocket messages.

#### 3.2.1. Server

[Same as in the Servlet stack](web.html#websocket-server-handler)

To create a WebSocket server, you can first create a `WebSocketHandler`.
The following example shows how to do so:

Java

```
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;

public class MyWebSocketHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // ...
    }
}
```

Kotlin

```
import org.springframework.web.reactive.socket.WebSocketHandler
import org.springframework.web.reactive.socket.WebSocketSession

class MyWebSocketHandler : WebSocketHandler {

    override fun handle(session: WebSocketSession): Mono<Void> {
        // ...
    }
}
```

Then you can map it to a URL:

Java

```
@Configuration
class WebConfig {

    @Bean
    public HandlerMapping handlerMapping() {
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/path", new MyWebSocketHandler());
        int order = -1; // before annotated controllers

        return new SimpleUrlHandlerMapping(map, order);
    }
}
```

Kotlin

```
@Configuration
class WebConfig {

    @Bean
    fun handlerMapping(): HandlerMapping {
        val map = mapOf("/path" to MyWebSocketHandler())
        val order = -1 // before annotated controllers

        return SimpleUrlHandlerMapping(map, order)
    }
}
```

If using the [WebFlux Config](#webflux-config) there is nothing
further to do, or otherwise if not using the WebFlux config you’ll need to declare a`WebSocketHandlerAdapter` as shown below:

Java

```
@Configuration
class WebConfig {

    // ...

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}
```

Kotlin

```
@Configuration
class WebConfig {

    // ...

    @Bean
    fun handlerAdapter() =  WebSocketHandlerAdapter()
}
```

#### 3.2.2. `WebSocketHandler`

The `handle` method of `WebSocketHandler` takes `WebSocketSession` and returns `Mono<Void>`to indicate when application handling of the session is complete. The session is handled
through two streams, one for inbound and one for outbound messages. The following table
describes the two methods that handle the streams:

|          `WebSocketSession` method           |                                                                      Description                                                                      |
|----------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
|      `Flux<WebSocketMessage> receive()`      |                              Provides access to the inbound message stream and completes when the connection is closed.                               |
|`Mono<Void> send(Publisher<WebSocketMessage>)`|Takes a source for outgoing messages, writes the messages, and returns a `Mono<Void>` that<br/>completes when the source completes and writing is done.|

A `WebSocketHandler` must compose the inbound and outbound streams into a unified flow and
return a `Mono<Void>` that reflects the completion of that flow. Depending on application
requirements, the unified flow completes when:

* Either the inbound or the outbound message stream completes.

* The inbound stream completes (that is, the connection closed), while the outbound stream is infinite.

* At a chosen point, through the `close` method of `WebSocketSession`.

When inbound and outbound message streams are composed together, there is no need to
check if the connection is open, since Reactive Streams signals end activity.
The inbound stream receives a completion or error signal, and the outbound stream
receives a cancellation signal.

The most basic implementation of a handler is one that handles the inbound stream. The
following example shows such an implementation:

Java

```
class ExampleHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        return session.receive()            (1)
                .doOnNext(message -> {
                    // ...                  (2)
                })
                .concatMap(message -> {
                    // ...                  (3)
                })
                .then();                    (4)
    }
}
```

|**1**|               Access the stream of inbound messages.               |
|-----|--------------------------------------------------------------------|
|**2**|                  Do something with each message.                   |
|**3**|Perform nested asynchronous operations that use the message content.|
|**4**|   Return a `Mono<Void>` that completes when receiving completes.   |

Kotlin

```
class ExampleHandler : WebSocketHandler {

    override fun handle(session: WebSocketSession): Mono<Void> {
        return session.receive()            (1)
                .doOnNext {
                    // ...                  (2)
                }
                .concatMap {
                    // ...                  (3)
                }
                .then()                     (4)
    }
}
```

|**1**|               Access the stream of inbound messages.               |
|-----|--------------------------------------------------------------------|
|**2**|                  Do something with each message.                   |
|**3**|Perform nested asynchronous operations that use the message content.|
|**4**|   Return a `Mono<Void>` that completes when receiving completes.   |

|   |For nested, asynchronous operations, you may need to call `message.retain()` on underlying<br/>servers that use pooled data buffers (for example, Netty). Otherwise, the data buffer may be<br/>released before you have had a chance to read the data. For more background, see[Data Buffers and Codecs](core.html#databuffers).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The following implementation combines the inbound and outbound streams:

Java

```
class ExampleHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {

        Flux<WebSocketMessage> output = session.receive()               (1)
                .doOnNext(message -> {
                    // ...
                })
                .concatMap(message -> {
                    // ...
                })
                .map(value -> session.textMessage("Echo " + value));    (2)

        return session.send(output);                                    (3)
    }
}
```

|**1**|                    Handle the inbound message stream.                    |
|-----|--------------------------------------------------------------------------|
|**2**|         Create the outbound message, producing a combined flow.          |
|**3**|Return a `Mono<Void>` that does not complete while we continue to receive.|

Kotlin

```
class ExampleHandler : WebSocketHandler {

    override fun handle(session: WebSocketSession): Mono<Void> {

        val output = session.receive()                      (1)
                .doOnNext {
                    // ...
                }
                .concatMap {
                    // ...
                }
                .map { session.textMessage("Echo $it") }    (2)

        return session.send(output)                         (3)
    }
}
```

|**1**|                    Handle the inbound message stream.                    |
|-----|--------------------------------------------------------------------------|
|**2**|         Create the outbound message, producing a combined flow.          |
|**3**|Return a `Mono<Void>` that does not complete while we continue to receive.|

Inbound and outbound streams can be independent and be joined only for completion,
as the following example shows:

Java

```
class ExampleHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {

        Mono<Void> input = session.receive()                                (1)
                .doOnNext(message -> {
                    // ...
                })
                .concatMap(message -> {
                    // ...
                })
                .then();

        Flux<String> source = ... ;
        Mono<Void> output = session.send(source.map(session::textMessage)); (2)

        return Mono.zip(input, output).then();                              (3)
    }
}
```

|**1**|                          Handle inbound message stream.                          |
|-----|----------------------------------------------------------------------------------|
|**2**|                             Send outgoing messages.                              |
|**3**|Join the streams and return a `Mono<Void>` that completes when either stream ends.|

Kotlin

```
class ExampleHandler : WebSocketHandler {

    override fun handle(session: WebSocketSession): Mono<Void> {

        val input = session.receive()                                   (1)
                .doOnNext {
                    // ...
                }
                .concatMap {
                    // ...
                }
                .then()

        val source: Flux<String> = ...
        val output = session.send(source.map(session::textMessage))     (2)

        return Mono.zip(input, output).then()                           (3)
    }
}
```

|**1**|                          Handle inbound message stream.                          |
|-----|----------------------------------------------------------------------------------|
|**2**|                             Send outgoing messages.                              |
|**3**|Join the streams and return a `Mono<Void>` that completes when either stream ends.|

#### 3.2.3. `DataBuffer`

`DataBuffer` is the representation for a byte buffer in WebFlux. The Spring Core part of
the reference has more on that in the section on[Data Buffers and Codecs](core.html#databuffers). The key point to understand is that on some
servers like Netty, byte buffers are pooled and reference counted, and must be released
when consumed to avoid memory leaks.

When running on Netty, applications must use `DataBufferUtils.retain(dataBuffer)` if they
wish to hold on input data buffers in order to ensure they are not released, and
subsequently use `DataBufferUtils.release(dataBuffer)` when the buffers are consumed.

#### 3.2.4. Handshake

[Same as in the Servlet stack](web.html#websocket-server-handshake)

`WebSocketHandlerAdapter` delegates to a `WebSocketService`. By default, that is an instance
of `HandshakeWebSocketService`, which performs basic checks on the WebSocket request and
then uses `RequestUpgradeStrategy` for the server in use. Currently, there is built-in
support for Reactor Netty, Tomcat, Jetty, and Undertow.

`HandshakeWebSocketService` exposes a `sessionAttributePredicate` property that allows
setting a `Predicate<String>` to extract attributes from the `WebSession` and insert them
into the attributes of the `WebSocketSession`.

#### 3.2.5. Server Configation

[Same as in the Servlet stack](web.html#websocket-server-runtime-configuration)

The `RequestUpgradeStrategy` for each server exposes configuration specific to the
underlying WebSocket server engine. When using the WebFlux Java config you can customize
such properties as shown in the corresponding section of the[WebFlux Config](#webflux-config-websocket-service), or otherwise if
not using the WebFlux config, use the below:

Java

```
@Configuration
class WebConfig {

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter(webSocketService());
    }

    @Bean
    public WebSocketService webSocketService() {
        TomcatRequestUpgradeStrategy strategy = new TomcatRequestUpgradeStrategy();
        strategy.setMaxSessionIdleTimeout(0L);
        return new HandshakeWebSocketService(strategy);
    }
}
```

Kotlin

```
@Configuration
class WebConfig {

    @Bean
    fun handlerAdapter() =
            WebSocketHandlerAdapter(webSocketService())

    @Bean
    fun webSocketService(): WebSocketService {
        val strategy = TomcatRequestUpgradeStrategy().apply {
            setMaxSessionIdleTimeout(0L)
        }
        return HandshakeWebSocketService(strategy)
    }
}
```

Check the upgrade strategy for your server to see what options are available. Currently,
only Tomcat and Jetty expose such options.

#### 3.2.6. CORS

[Same as in the Servlet stack](web.html#websocket-server-allowed-origins)

The easiest way to configure CORS and restrict access to a WebSocket endpoint is to
have your `WebSocketHandler` implement `CorsConfigurationSource` and return a`CorsConfiguration` with allowed origins, headers, and other details. If you cannot do
that, you can also set the `corsConfigurations` property on the `SimpleUrlHandler` to
specify CORS settings by URL pattern. If both are specified, they are combined by using the`combine` method on `CorsConfiguration`.

#### 3.2.7. Client

Spring WebFlux provides a `WebSocketClient` abstraction with implementations for
Reactor Netty, Tomcat, Jetty, Undertow, and standard Java (that is, JSR-356).

|   |The Tomcat client is effectively an extension of the standard Java one with some extra<br/>functionality in the `WebSocketSession` handling to take advantage of the Tomcat-specific<br/>API to suspend receiving messages for back pressure.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

To start a WebSocket session, you can create an instance of the client and use its `execute`methods:

Java

```
WebSocketClient client = new ReactorNettyWebSocketClient();

URI url = new URI("ws://localhost:8080/path");
client.execute(url, session ->
        session.receive()
                .doOnNext(System.out::println)
                .then());
```

Kotlin

```
val client = ReactorNettyWebSocketClient()

        val url = URI("ws://localhost:8080/path")
        client.execute(url) { session ->
            session.receive()
                    .doOnNext(::println)
            .then()
        }
```

Some clients, such as Jetty, implement `Lifecycle` and need to be stopped and started
before you can use them. All clients have constructor options related to configuration
of the underlying WebSocket client.

## 4. Testing

[Same in Spring MVC](web.html#testing)

The `spring-test` module provides mock implementations of `ServerHttpRequest`,`ServerHttpResponse`, and `ServerWebExchange`.
See [Spring Web Reactive](testing.html#mock-objects-web-reactive) for a
discussion of mock objects.

[`WebTestClient`](testing.html#webtestclient) builds on these mock request and
response objects to provide support for testing WebFlux applications without an HTTP
server. You can use the `WebTestClient` for end-to-end integration tests, too.

## 5. RSocket

This section describes Spring Framework’s support for the RSocket protocol.

### 5.1. Overview

RSocket is an application protocol for multiplexed, duplex communication over TCP,
WebSocket, and other byte stream transports, using one of the following interaction
models:

* `Request-Response` — send one message and receive one back.

* `Request-Stream` — send one message and receive a stream of messages back.

* `Channel` — send streams of messages in both directions.

* `Fire-and-Forget` — send a one-way message.

Once the initial connection is made, the "client" vs "server" distinction is lost as
both sides become symmetrical and each side can initiate one of the above interactions.
This is why in the protocol calls the participating sides "requester" and "responder"
while the above interactions are called "request streams" or simply "requests".

These are the key features and benefits of the RSocket protocol:

* [Reactive Streams](https://www.reactive-streams.org/) semantics across network boundary — for streaming requests such as `Request-Stream` and `Channel`, back pressure signals
  travel between requester and responder, allowing a requester to slow down a responder at
  the source, hence reducing reliance on network layer congestion control, and the need
  for buffering at the network level or at any level.

* Request throttling — this feature is named "Leasing" after the `LEASE` frame that
  can be sent from each end to limit the total number of requests allowed by other end
  for a given time. Leases are renewed periodically.

* Session resumption — this is designed for loss of connectivity and requires some state
  to be maintained. The state management is transparent for applications, and works well
  in combination with back pressure which can stop a producer when possible and reduce
  the amount of state required.

* Fragmentation and re-assembly of large messages.

* Keepalive (heartbeats).

RSocket has [implementations](https://github.com/rsocket) in multiple languages. The[Java library](https://github.com/rsocket/rsocket-java) is built on [Project Reactor](https://projectreactor.io/),
and [Reactor Netty](https://github.com/reactor/reactor-netty) for the transport. That means
signals from Reactive Streams Publishers in your application propagate transparently
through RSocket across the network.

#### 5.1.1. The Protocol

One of the benefits of RSocket is that it has well defined behavior on the wire and an
easy to read [specification](https://rsocket.io/docs/Protocol) along with some protocol[extensions](https://github.com/rsocket/rsocket/tree/master/Extensions). Therefore it is
a good idea to read the spec, independent of language implementations and higher level
framework APIs. This section provides a succinct overview to establish some context.

**Connecting**

Initially a client connects to a server via some low level streaming transport such
as TCP or WebSocket and sends a `SETUP` frame to the server to set parameters for the
connection.

The server may reject the `SETUP` frame, but generally after it is sent (for the client)
and received (for the server), both sides can begin to make requests, unless `SETUP`indicates use of leasing semantics to limit the number of requests, in which case
both sides must wait for a `LEASE` frame from the other end to permit making requests.

**Making Requests**

Once a connection is established, both sides may initiate a request through one of the
frames `REQUEST_RESPONSE`, `REQUEST_STREAM`, `REQUEST_CHANNEL`, or `REQUEST_FNF`. Each of
those frames carries one message from the requester to the responder.

The responder may then return `PAYLOAD` frames with response messages, and in the case
of `REQUEST_CHANNEL` the requester may also send `PAYLOAD` frames with more request
messages.

When a request involves a stream of messages such as `Request-Stream` and `Channel`,
the responder must respect demand signals from the requester. Demand is expressed as a
number of messages. Initial demand is specified in `REQUEST_STREAM` and`REQUEST_CHANNEL` frames. Subsequent demand is signaled via `REQUEST_N` frames.

Each side may also send metadata notifications, via the `METADATA_PUSH` frame, that do not
pertain to any individual request but rather to the connection as a whole.

**Message Format**

RSocket messages contain data and metadata. Metadata can be used to send a route, a
security token, etc. Data and metadata can be formatted differently. Mime types for each
are declared in the `SETUP` frame and apply to all requests on a given connection.

While all messages can have metadata, typically metadata such as a route are per-request
and therefore only included in the first message on a request, i.e. with one of the frames`REQUEST_RESPONSE`, `REQUEST_STREAM`, `REQUEST_CHANNEL`, or `REQUEST_FNF`.

Protocol extensions define common metadata formats for use in applications:

* [Composite Metadata](https://github.com/rsocket/rsocket/blob/master/Extensions/CompositeMetadata.md)-- multiple,
  independently formatted metadata entries.

* [Routing](https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md) — the route for a request.

#### 5.1.2. Java Implementation

The [Java implementation](https://github.com/rsocket/rsocket-java) for RSocket is built on[Project Reactor](https://projectreactor.io/). The transports for TCP and WebSocket are
built on [Reactor Netty](https://github.com/reactor/reactor-netty). As a Reactive Streams
library, Reactor simplifies the job of implementing the protocol. For applications it is
a natural fit to use `Flux` and `Mono` with declarative operators and transparent back
pressure support.

The API in RSocket Java is intentionally minimal and basic. It focuses on protocol
features and leaves the application programming model (e.g. RPC codegen vs other) as a
higher level, independent concern.

The main contract[io.rsocket.RSocket](https://github.com/rsocket/rsocket-java/blob/master/rsocket-core/src/main/java/io/rsocket/RSocket.java)models the four request interaction types with `Mono` representing a promise for a
single message, `Flux` a stream of messages, and `io.rsocket.Payload` the actual
message with access to data and metadata as byte buffers. The `RSocket` contract is used
symmetrically. For requesting, the application is given an `RSocket` to perform
requests with. For responding, the application implements `RSocket` to handle requests.

This is not meant to be a thorough introduction. For the most part, Spring applications
will not have to use its API directly. However it may be important to see or experiment
with RSocket independent of Spring. The RSocket Java repository contains a number of[sample apps](https://github.com/rsocket/rsocket-java/tree/master/rsocket-examples) that
demonstrate its API and protocol features.

#### 5.1.3. Spring Support

The `spring-messaging` module contains the following:

* [RSocketRequester](#rsocket-requester) — fluent API to make requests through an `io.rsocket.RSocket`with data and metadata encoding/decoding.

* [Annotated Responders](#rsocket-annot-responders) — `@MessageMapping` annotated handler methods for
  responding.

The `spring-web` module contains `Encoder` and `Decoder` implementations such as Jackson
CBOR/JSON, and Protobuf that RSocket applications will likely need. It also contains the`PathPatternParser` that can be plugged in for efficient route matching.

Spring Boot 2.2 supports standing up an RSocket server over TCP or WebSocket, including
the option to expose RSocket over WebSocket in a WebFlux server. There is also client
support and auto-configuration for an `RSocketRequester.Builder` and `RSocketStrategies`.
See the[RSocket section](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-rsocket)in the Spring Boot reference for more details.

Spring Security 5.2 provides RSocket support.

Spring Integration 5.2 provides inbound and outbound gateways to interact with RSocket
clients and servers. See the Spring Integration Reference Manual for more details.

Spring Cloud Gateway supports RSocket connections.

### 5.2. RSocketRequester

`RSocketRequester` provides a fluent API to perform RSocket requests, accepting and
returning objects for data and metadata instead of low level data buffers. It can be used
symmetrically, to make requests from clients and to make requests from servers.

#### 5.2.1. Client Requester

To obtain an `RSocketRequester` on the client side is to connect to a server which involves
sending an RSocket `SETUP` frame with connection settings. `RSocketRequester` provides a
builder that helps to prepare an `io.rsocket.core.RSocketConnector` including connection
settings for the `SETUP` frame.

This is the most basic way to connect with default settings:

Java

```
RSocketRequester requester = RSocketRequester.builder().tcp("localhost", 7000);

URI url = URI.create("https://example.org:8080/rsocket");
RSocketRequester requester = RSocketRequester.builder().webSocket(url);
```

Kotlin

```
val requester = RSocketRequester.builder().tcp("localhost", 7000)

URI url = URI.create("https://example.org:8080/rsocket");
val requester = RSocketRequester.builder().webSocket(url)
```

The above does not connect immediately. When requests are made, a shared connection is
established transparently and used.

##### Connection Setup

`RSocketRequester.Builder` provides the following to customize the initial `SETUP` frame:

* `dataMimeType(MimeType)` — set the mime type for data on the connection.

* `metadataMimeType(MimeType)` — set the mime type for metadata on the connection.

* `setupData(Object)` — data to include in the `SETUP`.

* `setupRoute(String, Object…​)` — route in the metadata to include in the `SETUP`.

* `setupMetadata(Object, MimeType)` — other metadata to include in the `SETUP`.

For data, the default mime type is derived from the first configured `Decoder`. For
metadata, the default mime type is[composite metadata](https://github.com/rsocket/rsocket/blob/master/Extensions/CompositeMetadata.md) which allows multiple
metadata value and mime type pairs per request. Typically both don’t need to be changed.

Data and metadata in the `SETUP` frame is optional. On the server side,[@ConnectMapping](#rsocket-annot-connectmapping) methods can be used to handle the start of a
connection and the content of the `SETUP` frame. Metadata may be used for connection
level security.

##### Strategies

`RSocketRequester.Builder` accepts `RSocketStrategies` to configure the requester.
You’ll need to use this to provide encoders and decoders for (de)-serialization of data and
metadata values. By default only the basic codecs from `spring-core` for `String`,`byte[]`, and `ByteBuffer` are registered. Adding `spring-web` provides access to more that
can be registered as follows:

Java

```
RSocketStrategies strategies = RSocketStrategies.builder()
    .encoders(encoders -> encoders.add(new Jackson2CborEncoder()))
    .decoders(decoders -> decoders.add(new Jackson2CborDecoder()))
    .build();

RSocketRequester requester = RSocketRequester.builder()
    .rsocketStrategies(strategies)
    .tcp("localhost", 7000);
```

Kotlin

```
val strategies = RSocketStrategies.builder()
        .encoders { it.add(Jackson2CborEncoder()) }
        .decoders { it.add(Jackson2CborDecoder()) }
        .build()

val requester = RSocketRequester.builder()
        .rsocketStrategies(strategies)
        .tcp("localhost", 7000)
```

`RSocketStrategies` is designed for re-use. In some scenarios, e.g. client and server in
the same application, it may be preferable to declare it in Spring configuration.

##### Client Responders

`RSocketRequester.Builder` can be used to configure responders to requests from the
server.

You can use annotated handlers for client-side responding based on the same
infrastructure that’s used on a server, but registered programmatically as follows:

Java

```
RSocketStrategies strategies = RSocketStrategies.builder()
    .routeMatcher(new PathPatternRouteMatcher())  (1)
    .build();

SocketAcceptor responder =
    RSocketMessageHandler.responder(strategies, new ClientHandler()); (2)

RSocketRequester requester = RSocketRequester.builder()
    .rsocketConnector(connector -> connector.acceptor(responder)) (3)
    .tcp("localhost", 7000);
```

|**1**|Use `PathPatternRouteMatcher`, if `spring-web` is present, for efficient<br/>route matching.|
|-----|--------------------------------------------------------------------------------------------|
|**2**|  Create a responder from a class with `@MessageMaping` and/or `@ConnectMapping` methods.   |
|**3**|                                  Register the responder.                                   |

Kotlin

```
val strategies = RSocketStrategies.builder()
        .routeMatcher(PathPatternRouteMatcher())  (1)
        .build()

val responder =
    RSocketMessageHandler.responder(strategies, new ClientHandler()); (2)

val requester = RSocketRequester.builder()
        .rsocketConnector { it.acceptor(responder) } (3)
        .tcp("localhost", 7000)
```

|**1**|Use `PathPatternRouteMatcher`, if `spring-web` is present, for efficient<br/>route matching.|
|-----|--------------------------------------------------------------------------------------------|
|**2**|  Create a responder from a class with `@MessageMaping` and/or `@ConnectMapping` methods.   |
|**3**|                                  Register the responder.                                   |

Note the above is only a shortcut designed for programmatic registration of client
responders. For alternative scenarios, where client responders are in Spring configuration,
you can still declare `RSocketMessageHandler` as a Spring bean and then apply as follows:

Java

```
ApplicationContext context = ... ;
RSocketMessageHandler handler = context.getBean(RSocketMessageHandler.class);

RSocketRequester requester = RSocketRequester.builder()
    .rsocketConnector(connector -> connector.acceptor(handler.responder()))
    .tcp("localhost", 7000);
```

Kotlin

```
import org.springframework.beans.factory.getBean

val context: ApplicationContext = ...
val handler = context.getBean<RSocketMessageHandler>()

val requester = RSocketRequester.builder()
        .rsocketConnector { it.acceptor(handler.responder()) }
        .tcp("localhost", 7000)
```

For the above you may also need to use `setHandlerPredicate` in `RSocketMessageHandler` to
switch to a different strategy for detecting client responders, e.g. based on a custom
annotation such as `@RSocketClientResponder` vs the default `@Controller`. This
is necessary in scenarios with client and server, or multiple clients in the same
application.

See also [Annotated Responders](#rsocket-annot-responders), for more on the programming model.

##### Advanced

`RSocketRequesterBuilder` provides a callback to expose the underlying`io.rsocket.core.RSocketConnector` for further configuration options for keepalive
intervals, session resumption, interceptors, and more. You can configure options
at that level as follows:

Java

```
RSocketRequester requester = RSocketRequester.builder()
    .rsocketConnector(connector -> {
        // ...
    })
    .tcp("localhost", 7000);
```

Kotlin

```
val requester = RSocketRequester.builder()
        .rsocketConnector {
            //...
        }
        .tcp("localhost", 7000)
```

#### 5.2.2. Server Requester

To make requests from a server to connected clients is a matter of obtaining the
requester for the connected client from the server.

In [Annotated Responders](#rsocket-annot-responders), `@ConnectMapping` and `@MessageMapping` methods support an`RSocketRequester` argument. Use it to access the requester for the connection. Keep in
mind that `@ConnectMapping` methods are essentially handlers of the `SETUP` frame which
must be handled before requests can begin. Therefore, requests at the very start must be
decoupled from handling. For example:

Java

```
@ConnectMapping
Mono<Void> handle(RSocketRequester requester) {
    requester.route("status").data("5")
        .retrieveFlux(StatusReport.class)
        .subscribe(bar -> { (1)
            // ...
        });
    return ... (2)
}
```

|**1**|Start the request asynchronously, independent from handling.|
|-----|------------------------------------------------------------|
|**2**|    Perform handling and return completion `Mono<Void>`.    |

Kotlin

```
@ConnectMapping
suspend fun handle(requester: RSocketRequester) {
    GlobalScope.launch {
        requester.route("status").data("5").retrieveFlow<StatusReport>().collect { (1)
            // ...
        }
    }
    /// ... (2)
}
```

|**1**|Start the request asynchronously, independent from handling.|
|-----|------------------------------------------------------------|
|**2**|        Perform handling in the suspending function.        |

#### 5.2.3. Requests

Once you have a [client](#rsocket-requester-client) or[server](#rsocket-requester-server) requester, you can make requests as follows:

Java

```
ViewBox viewBox = ... ;

Flux<AirportLocation> locations = requester.route("locate.radars.within") (1)
        .data(viewBox) (2)
        .retrieveFlux(AirportLocation.class); (3)
```

|**1**|Specify a route to include in the metadata of the request message.|
|-----|------------------------------------------------------------------|
|**2**|              Provide data for the request message.               |
|**3**|                  Declare the expected response.                  |

Kotlin

```
val viewBox: ViewBox = ...

val locations = requester.route("locate.radars.within") (1)
        .data(viewBox) (2)
        .retrieveFlow<AirportLocation>() (3)
```

|**1**|Specify a route to include in the metadata of the request message.|
|-----|------------------------------------------------------------------|
|**2**|              Provide data for the request message.               |
|**3**|                  Declare the expected response.                  |

The interaction type is determined implicitly from the cardinality of the input and
output. The above example is a `Request-Stream` because one value is sent and a stream
of values is received. For the most part you don’t need to think about this as long as the
choice of input and output matches an RSocket interaction type and the types of input and
output expected by the responder. The only example of an invalid combination is many-to-one.

The `data(Object)` method also accepts any Reactive Streams `Publisher`, including`Flux` and `Mono`, as well as any other producer of value(s) that is registered in the`ReactiveAdapterRegistry`. For a multi-value `Publisher` such as `Flux` which produces the
same types of values, consider using one of the overloaded `data` methods to avoid having
type checks and `Encoder` lookup on every element:

```
data(Object producer, Class<?> elementClass);
data(Object producer, ParameterizedTypeReference<?> elementTypeRef);
```

The `data(Object)` step is optional. Skip it for requests that don’t send data:

Java

```
Mono<AirportLocation> location = requester.route("find.radar.EWR"))
    .retrieveMono(AirportLocation.class);
```

Kotlin

```
import org.springframework.messaging.rsocket.retrieveAndAwait

val location = requester.route("find.radar.EWR")
    .retrieveAndAwait<AirportLocation>()
```

Extra metadata values can be added if using[composite metadata](https://github.com/rsocket/rsocket/blob/master/Extensions/CompositeMetadata.md) (the default) and if the
values are supported by a registered `Encoder`. For example:

Java

```
String securityToken = ... ;
ViewBox viewBox = ... ;
MimeType mimeType = MimeType.valueOf("message/x.rsocket.authentication.bearer.v0");

Flux<AirportLocation> locations = requester.route("locate.radars.within")
        .metadata(securityToken, mimeType)
        .data(viewBox)
        .retrieveFlux(AirportLocation.class);
```

Kotlin

```
import org.springframework.messaging.rsocket.retrieveFlow

val requester: RSocketRequester = ...

val securityToken: String = ...
val viewBox: ViewBox = ...
val mimeType = MimeType.valueOf("message/x.rsocket.authentication.bearer.v0")

val locations = requester.route("locate.radars.within")
        .metadata(securityToken, mimeType)
        .data(viewBox)
        .retrieveFlow<AirportLocation>()
```

For `Fire-and-Forget` use the `send()` method that returns `Mono<Void>`. Note that the `Mono`indicates only that the message was successfully sent, and not that it was handled.

For `Metadata-Push` use the `sendMetadata()` method with a `Mono<Void>` return value.

### 5.3. Annotated Responders

RSocket responders can be implemented as `@MessageMapping` and `@ConnectMapping` methods.`@MessageMapping` methods handle individual requests while `@ConnectMapping` methods handle
connection-level events (setup and metadata push). Annotated responders are supported
symmetrically, for responding from the server side and for responding from the client side.

#### 5.3.1. Server Responders

To use annotated responders on the server side, add `RSocketMessageHandler` to your Spring
configuration to detect `@Controller` beans with `@MessageMapping` and `@ConnectMapping`methods:

Java

```
@Configuration
static class ServerConfig {

    @Bean
    public RSocketMessageHandler rsocketMessageHandler() {
        RSocketMessageHandler handler = new RSocketMessageHandler();
        handler.routeMatcher(new PathPatternRouteMatcher());
        return handler;
    }
}
```

Kotlin

```
@Configuration
class ServerConfig {

    @Bean
    fun rsocketMessageHandler() = RSocketMessageHandler().apply {
        routeMatcher = PathPatternRouteMatcher()
    }
}
```

Then start an RSocket server through the Java RSocket API and plug the`RSocketMessageHandler` for the responder as follows:

Java

```
ApplicationContext context = ... ;
RSocketMessageHandler handler = context.getBean(RSocketMessageHandler.class);

CloseableChannel server =
    RSocketServer.create(handler.responder())
        .bind(TcpServerTransport.create("localhost", 7000))
        .block();
```

Kotlin

```
import org.springframework.beans.factory.getBean

val context: ApplicationContext = ...
val handler = context.getBean<RSocketMessageHandler>()

val server = RSocketServer.create(handler.responder())
        .bind(TcpServerTransport.create("localhost", 7000))
        .awaitSingle()
```

`RSocketMessageHandler` supports[composite](https://github.com/rsocket/rsocket/blob/master/Extensions/CompositeMetadata.md) and[routing](https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md) metadata by default. You can set its[MetadataExtractor](#rsocket-metadata-extractor) if you need to switch to a
different mime type or register additional metadata mime types.

You’ll need to set the `Encoder` and `Decoder` instances required for metadata and data
formats to support. You’ll likely need the `spring-web` module for codec implementations.

By default `SimpleRouteMatcher` is used for matching routes via `AntPathMatcher`.
We recommend plugging in the `PathPatternRouteMatcher` from `spring-web` for
efficient route matching. RSocket routes can be hierarchical but are not URL paths.
Both route matchers are configured to use "." as separator by default and there is no URL
decoding as with HTTP URLs.

`RSocketMessageHandler` can be configured via `RSocketStrategies` which may be useful if
you need to share configuration between a client and a server in the same process:

Java

```
@Configuration
static class ServerConfig {

    @Bean
    public RSocketMessageHandler rsocketMessageHandler() {
        RSocketMessageHandler handler = new RSocketMessageHandler();
        handler.setRSocketStrategies(rsocketStrategies());
        return handler;
    }

    @Bean
    public RSocketStrategies rsocketStrategies() {
        return RSocketStrategies.builder()
            .encoders(encoders -> encoders.add(new Jackson2CborEncoder()))
            .decoders(decoders -> decoders.add(new Jackson2CborDecoder()))
            .routeMatcher(new PathPatternRouteMatcher())
            .build();
    }
}
```

Kotlin

```
@Configuration
class ServerConfig {

    @Bean
    fun rsocketMessageHandler() = RSocketMessageHandler().apply {
        rSocketStrategies = rsocketStrategies()
    }

    @Bean
    fun rsocketStrategies() = RSocketStrategies.builder()
            .encoders { it.add(Jackson2CborEncoder()) }
            .decoders { it.add(Jackson2CborDecoder()) }
            .routeMatcher(PathPatternRouteMatcher())
            .build()
}
```

#### 5.3.2. Client Responders

Annotated responders on the client side need to be configured in the`RSocketRequester.Builder`. For details, see[Client Responders](#rsocket-requester-client-responder).

#### 5.3.3. @MessageMapping

Once [server](#rsocket-annot-responders-server) or[client](#rsocket-annot-responders-client) responder configuration is in place,`@MessageMapping` methods can be used as follows:

Java

```
@Controller
public class RadarsController {

    @MessageMapping("locate.radars.within")
    public Flux<AirportLocation> radars(MapRequest request) {
        // ...
    }
}
```

Kotlin

```
@Controller
class RadarsController {

    @MessageMapping("locate.radars.within")
    fun radars(request: MapRequest): Flow<AirportLocation> {
        // ...
    }
}
```

The above `@MessageMapping` method responds to a Request-Stream interaction having the
route "locate.radars.within". It supports a flexible method signature with the option to
use the following method arguments:

|       Method Argument        |                                                                                                                                           Description                                                                                                                                            |
|------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|          `@Payload`          |The payload of the request. This can be a concrete value of asynchronous types like`Mono` or `Flux`.<br/><br/>**Note:** Use of the annotation is optional. A method argument that is not a simple type<br/>and is not any of the other supported arguments, is assumed to be the expected payload.|
|      `RSocketRequester`      |                                                                                                                         Requester for making requests to the remote end.                                                                                                                         |
|    `@DestinationVariable`    |                                                                                       Value extracted from the route based on variables in the mapping pattern, e.g.`@MessageMapping("find.radar.{id}")`.                                                                                        |
|          `@Header`           |                                                                                            Metadata value registered for extraction as described in [MetadataExtractor](#rsocket-metadata-extractor).                                                                                            |
|`@Headers Map<String, Object>`|                                                                                         All metadata values registered for extraction as described in [MetadataExtractor](#rsocket-metadata-extractor).                                                                                          |

The return value is expected to be one or more Objects to be serialized as response
payloads. That can be asynchronous types like `Mono` or `Flux`, a concrete value, or
either `void` or a no-value asynchronous type such as `Mono<Void>`.

The RSocket interaction type that an `@MessageMapping` method supports is determined from
the cardinality of the input (i.e. `@Payload` argument) and of the output, where
cardinality means the following:

|Cardinality|                                                                          Description                                                                          |
|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     1     |                                       Either an explicit value, or a single-value asynchronous type such as `Mono<T>`.                                        |
|   Many    |                                                      A multi-value asynchronous type such as `Flux<T>`.                                                       |
|     0     |For input this means the method does not have an `@Payload` argument.<br/><br/> For output this is `void` or a no-value asynchronous type such as `Mono<Void>`.|

The table below shows all input and output cardinality combinations and the corresponding
interaction type(s):

|Input Cardinality|Output Cardinality|        Interaction Types        |
|-----------------|------------------|---------------------------------|
|      0, 1       |        0         |Fire-and-Forget, Request-Response|
|      0, 1       |        1         |        Request-Response         |
|      0, 1       |       Many       |         Request-Stream          |
|      Many       |    0, 1, Many    |         Request-Channel         |

#### 5.3.4. @ConnectMapping

`@ConnectMapping` handles the `SETUP` frame at the start of an RSocket connection, and
any subsequent metadata push notifications through the `METADATA_PUSH` frame, i.e.`metadataPush(Payload)` in `io.rsocket.RSocket`.

`@ConnectMapping` methods support the same arguments as[@MessageMapping](#rsocket-annot-messagemapping) but based on metadata and data from the `SETUP` and`METADATA_PUSH` frames. `@ConnectMapping` can have a pattern to narrow handling to
specific connections that have a route in the metadata, or if no patterns are declared
then all connections match.

`@ConnectMapping` methods cannot return data and must be declared with `void` or`Mono<Void>` as the return value. If handling returns an error for a new
connection then the connection is rejected. Handling must not be held up to make
requests to the `RSocketRequester` for the connection. See[Server Requester](#rsocket-requester-server) for details.

### 5.4. MetadataExtractor

Responders must interpret metadata.[Composite metadata](https://github.com/rsocket/rsocket/blob/master/Extensions/CompositeMetadata.md) allows independently
formatted metadata values (e.g. for routing, security, tracing) each with its own mime
type. Applications need a way to configure metadata mime types to support, and a way
to access extracted values.

`MetadataExtractor` is a contract to take serialized metadata and return decoded
name-value pairs that can then be accessed like headers by name, for example via `@Header`in annotated handler methods.

`DefaultMetadataExtractor` can be given `Decoder` instances to decode metadata. Out of
the box it has built-in support for["message/x.rsocket.routing.v0"](https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md) which it decodes to`String` and saves under the "route" key. For any other mime type you’ll need to provide
a `Decoder` and register the mime type as follows:

Java

```
DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(metadataDecoders);
extractor.metadataToExtract(fooMimeType, Foo.class, "foo");
```

Kotlin

```
import org.springframework.messaging.rsocket.metadataToExtract

val extractor = DefaultMetadataExtractor(metadataDecoders)
extractor.metadataToExtract<Foo>(fooMimeType, "foo")
```

Composite metadata works well to combine independent metadata values. However the
requester might not support composite metadata, or may choose not to use it. For this,`DefaultMetadataExtractor` may needs custom logic to map the decoded value to the output
map. Here is an example where JSON is used for metadata:

Java

```
DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(metadataDecoders);
extractor.metadataToExtract(
    MimeType.valueOf("application/vnd.myapp.metadata+json"),
    new ParameterizedTypeReference<Map<String,String>>() {},
    (jsonMap, outputMap) -> {
        outputMap.putAll(jsonMap);
    });
```

Kotlin

```
import org.springframework.messaging.rsocket.metadataToExtract

val extractor = DefaultMetadataExtractor(metadataDecoders)
extractor.metadataToExtract<Map<String, String>>(MimeType.valueOf("application/vnd.myapp.metadata+json")) { jsonMap, outputMap ->
    outputMap.putAll(jsonMap)
}
```

When configuring `MetadataExtractor` through `RSocketStrategies`, you can let`RSocketStrategies.Builder` create the extractor with the configured decoders, and
simply use a callback to customize registrations as follows:

Java

```
RSocketStrategies strategies = RSocketStrategies.builder()
    .metadataExtractorRegistry(registry -> {
        registry.metadataToExtract(fooMimeType, Foo.class, "foo");
        // ...
    })
    .build();
```

Kotlin

```
import org.springframework.messaging.rsocket.metadataToExtract

val strategies = RSocketStrategies.builder()
        .metadataExtractorRegistry { registry: MetadataExtractorRegistry ->
            registry.metadataToExtract<Foo>(fooMimeType, "foo")
            // ...
        }
        .build()
```

## 6. Reactive Libraries

`spring-webflux` depends on `reactor-core` and uses it internally to compose asynchronous
logic and to provide Reactive Streams support. Generally, WebFlux APIs return `Flux` or`Mono` (since those are used internally) and leniently accept any Reactive Streams`Publisher` implementation as input. The use of `Flux` versus `Mono` is important, because
it helps to express cardinality — for example, whether a single or multiple asynchronous
values are expected, and that can be essential for making decisions (for example, when
encoding or decoding HTTP messages).

For annotated controllers, WebFlux transparently adapts to the reactive library chosen
by the application. This is done with the help of the[`ReactiveAdapterRegistry`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/ReactiveAdapterRegistry.html)which provides pluggable support for reactive library and other asynchronous types.
The registry has built-in support for RxJava 3, Kotlin coroutines and SmallRye Mutiny,
but you can register other third-party adapters as well.

|   |As of Spring Framework 5.3.11, support for RxJava 1 and 2 is deprecated, following<br/>RxJava’s own EOL advice and the upgrade recommendation towards RxJava 3.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------|

For functional APIs (such as [Functional Endpoints](#webflux-fn), the `WebClient`, and others), the general
rules for WebFlux APIs apply — `Flux` and `Mono` as return values and a Reactive Streams`Publisher` as input. When a `Publisher`, whether custom or from another reactive library,
is provided, it can be treated only as a stream with unknown semantics (0..N). If, however,
the semantics are known, you can wrap it with `Flux` or `Mono.from(Publisher)` instead
of passing the raw `Publisher`.

For example, given a `Publisher` that is not a `Mono`, the Jackson JSON message writer
expects multiple values. If the media type implies an infinite stream (for example,`application/json+stream`), values are written and flushed individually. Otherwise,
values are buffered into a list and rendered as a JSON array.