Quellcode durchsuchen

内容协商 contentNegotiation 的使用

zhang vor 2 Jahren
Ursprung
Commit
1e8d3f61f1

+ 4 - 0
pom.xml

@@ -166,6 +166,10 @@
166 166
             <scope>system</scope>
167 167
             <systemPath>${project.basedir}/src/main/resources/lib/doudian-sdk-java-1.0.0-20220509171318.jar</systemPath>
168 168
         </dependency>
169
+        <dependency>
170
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
171
+            <artifactId>jackson-dataformat-xml</artifactId>
172
+        </dependency>
169 173
     </dependencies>
170 174
 
171 175
     <!-- 阿里云maven仓库 -->

+ 43 - 0
src/main/java/com/api/config/WebMvcConfig.java

@@ -8,16 +8,26 @@
8 8
 
9 9
 package com.api.config;
10 10
 
11
+import com.api.converter.CustomMessageConverter;
12
+import com.api.form.ChildConvertForm;
11 13
 import com.common.interceptor.AuthorizationInterceptor;
12 14
 import com.api.resolver.LoginUserHandlerMethodArgumentResolver;
13 15
 import org.springframework.beans.factory.annotation.Autowired;
14 16
 import org.springframework.context.annotation.Configuration;
17
+import org.springframework.core.convert.converter.Converter;
18
+import org.springframework.format.FormatterRegistry;
19
+import org.springframework.http.MediaType;
20
+import org.springframework.http.converter.HttpMessageConverter;
21
+import org.springframework.web.accept.ParameterContentNegotiationStrategy;
15 22
 import org.springframework.web.method.support.HandlerMethodArgumentResolver;
23
+import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
16 24
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
17 25
 import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
18 26
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
19 27
 import org.springframework.web.util.UrlPathHelper;
20 28
 
29
+import java.util.Arrays;
30
+import java.util.HashMap;
21 31
 import java.util.List;
22 32
 
23 33
 /**
@@ -49,4 +59,37 @@ public class WebMvcConfig implements WebMvcConfigurer {
49 59
         urlPathHelper.setRemoveSemicolonContent(false);
50 60
         configurer.setUrlPathHelper(urlPathHelper);
51 61
     }
62
+
63
+    @Override
64
+    public void addFormatters(FormatterRegistry registry) {
65
+        registry.addConverter(new Converter<String, ChildConvertForm>() {
66
+            @Override
67
+            public ChildConvertForm convert(String s) {
68
+                if(!s.isEmpty()) {
69
+                    String[] split = s.split(",");
70
+                    ChildConvertForm childConvertForm = new ChildConvertForm();
71
+                    childConvertForm.setChildName(split[0]);
72
+                    childConvertForm.setChildAge(Integer.parseInt(split[1]));
73
+                    return childConvertForm;
74
+                }
75
+                return null;
76
+            }
77
+        });
78
+    }
79
+
80
+    @Override
81
+    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
82
+        converters.add(new CustomMessageConverter());
83
+    }
84
+
85
+    @Override
86
+    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
87
+        HashMap<String, MediaType> stringMediaTypeHashMap = new HashMap<>();
88
+        stringMediaTypeHashMap.put("json",MediaType.APPLICATION_JSON);
89
+        stringMediaTypeHashMap.put("xml",MediaType.APPLICATION_XML);
90
+        stringMediaTypeHashMap.put("zxy",MediaType.parseMediaType("application/x-zxy"));
91
+        ParameterContentNegotiationStrategy parameterContentNegotiationStrategy =
92
+                new ParameterContentNegotiationStrategy(stringMediaTypeHashMap);
93
+        configurer.strategies(Arrays.asList(parameterContentNegotiationStrategy));
94
+    }
52 95
 }

+ 1 - 0
src/main/java/com/api/controller/ApiTestController.java

@@ -78,6 +78,7 @@ public class ApiTestController extends AbsctactController {
78 78
     @ApiOperation("忽略Token验证测试")
79 79
     public R notToken1(@RequestParam Map<String,String> testQuery){
80 80
 //        return R.ok().put("msg", "无需token也能访问。。。");
81
+        System.out.println("notoken");
81 82
         return R.ok().put( "无需token也能访问。。。");
82 83
     }
83 84
 //    @GetMapping("notToken")

+ 53 - 0
src/main/java/com/api/controller/ModelAndMapController.java

@@ -0,0 +1,53 @@
1
+package com.api.controller;
2
+
3
+import com.api.form.LoginForm;
4
+import org.springframework.stereotype.Controller;
5
+import org.springframework.ui.Model;
6
+import org.springframework.web.bind.annotation.*;
7
+
8
+import javax.servlet.http.Cookie;
9
+import javax.servlet.http.HttpServletRequest;
10
+import javax.servlet.http.HttpServletResponse;
11
+import java.util.Map;
12
+
13
+@Controller
14
+@RequestMapping("/ModelAndMap")
15
+public class ModelAndMapController {
16
+    @GetMapping("/goto")
17
+    public String goTo(
18
+            Map<String,Object> map,
19
+            Model model,
20
+            HttpServletResponse response,
21
+            HttpServletRequest request) {
22
+        map.put("m1","v1");
23
+        model.addAttribute("m2","v2");
24
+        Cookie cookie = new Cookie("cookie_key", "cookieValue");
25
+        cookie.setDomain("localhost");
26
+        response.addCookie(cookie);
27
+        request.setAttribute("zhang","xiaoyu");
28
+        return "forward:/ModelAndMap/success";
29
+    }
30
+    @GetMapping("/success")
31
+    @ResponseBody
32
+    public LoginForm success(@RequestAttribute("zhang") String zhang,
33
+                          HttpServletRequest request) {
34
+        LoginForm loginForm = new LoginForm();
35
+        loginForm.setMobile("mobile");
36
+        loginForm.setPassword("zxys");
37
+        return loginForm;
38
+    }
39
+    @GetMapping("getTest")
40
+    @ResponseBody
41
+    public LoginForm getTest() {
42
+        LoginForm loginForm = new LoginForm();
43
+        loginForm.setMobile("mobile");
44
+        loginForm.setPassword("zxys");
45
+        return loginForm;
46
+    }
47
+    @PostMapping("postTest")
48
+    @ResponseBody
49
+    public LoginForm postTest(LoginForm loginForm) {
50
+        return loginForm;
51
+    }
52
+
53
+}

+ 1 - 1
src/main/java/com/api/controller/RequestController.java

@@ -31,6 +31,6 @@ public class RequestController {
31 31
                          @MatrixVariable("name")List<String> names) {
32 32
         System.out.println(low);
33 33
         System.out.println(names);
34
-        return null;
34
+        return low;
35 35
     }
36 36
 }

+ 42 - 0
src/main/java/com/api/converter/CustomMessageConverter.java

@@ -0,0 +1,42 @@
1
+package com.api.converter;
2
+
3
+import com.api.form.LoginForm;
4
+import org.springframework.http.HttpInputMessage;
5
+import org.springframework.http.HttpOutputMessage;
6
+import org.springframework.http.MediaType;
7
+import org.springframework.http.converter.HttpMessageConverter;
8
+import org.springframework.http.converter.HttpMessageNotReadableException;
9
+import org.springframework.http.converter.HttpMessageNotWritableException;
10
+
11
+import java.io.IOException;
12
+import java.io.OutputStream;
13
+import java.util.List;
14
+
15
+public class CustomMessageConverter implements HttpMessageConverter<LoginForm> {
16
+    @Override
17
+    public boolean canRead(Class<?> aClass, MediaType mediaType) {
18
+        return false;
19
+    }
20
+
21
+    @Override
22
+    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
23
+        return aClass.isAssignableFrom(LoginForm.class);
24
+    }
25
+
26
+    @Override
27
+    public List<MediaType> getSupportedMediaTypes() {
28
+        return MediaType.parseMediaTypes("application/x-zxy");
29
+    }
30
+
31
+    @Override
32
+    public LoginForm read(Class<? extends LoginForm> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
33
+        return null;
34
+    }
35
+
36
+    @Override
37
+    public void write(LoginForm loginForm, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
38
+        String str = loginForm.getMobile()+","+ loginForm.getPassword();
39
+        OutputStream body = httpOutputMessage.getBody();
40
+        body.write(str.getBytes());
41
+    }
42
+}

+ 9 - 0
src/main/java/com/api/form/ChildConvertForm.java

@@ -0,0 +1,9 @@
1
+package com.api.form;
2
+
3
+import lombok.Data;
4
+
5
+@Data
6
+public class ChildConvertForm {
7
+    private String childName;
8
+    private Integer childAge;
9
+}

+ 2 - 0
src/main/java/com/api/form/LoginForm.java

@@ -30,4 +30,6 @@ public class LoginForm {
30 30
     @NotBlank(message="密码不能为空")
31 31
     private String password;
32 32
 
33
+    private ChildConvertForm childConvertForm;
34
+
33 35
 }

+ 3 - 0
src/main/resources/application.yml

@@ -33,6 +33,9 @@ spring:
33 33
   http:
34 34
     encoding:
35 35
       charset: UTF-8
36
+  mvc:
37
+    contentnegotiation:
38
+      favor-parameter: true
36 39
 renren:
37 40
   redis:
38 41
     open: false  # 是否开启redis缓存  true开启   false关闭