Small problems encountered in Java development

1. The object field is missing

When the object is transferred to json for printing, it is found that the fields are missing, but the log printing of the data displays the fields normally.

log.info("直接打印整个对象...[{}]", JSONObject.toJSONString(acsDevice));

The field detected in the database contains server_Url
insert image description here
insert image description here
insert image description here
but not in the directly printed object.
insert image description here
insert image description here
Finally, it was found that it was a problem with the configuration file of mybatis. By default, mybatis corresponds to the meaning of the attribute name and the database field name, that is, both the data field and the attribute of the entity class should be server_url. But my database field here is server_url, the attribute is serverUrl, and the hump naming is adopted, so to set the attribute to enable the hump naming, the configuration is as follows:

map-underscore-to-camel-case: true

2. http returns a custom status code

The interface written by myself defines the returned status code, and returns 400 directly if there is an exception or other problems.

/**
 * 类描述:测试接口
 *
 * @ClassName TestController
 * @Author ward
 * @Date 2022-10-12 15:16
 */

@Controller
@RequestMapping("/test")
public class TestController {
    
    

    @RequestMapping("/error")
    @ResponseBody
    public String testError(HttpServletResponse httpServletResponse, String id) {
    
    
        String result = id + "已上线";
        httpServletResponse.setStatus(400);
        return result;
    }
}

insert image description here
insert image description here

Here you can see that you can customize it at will

3. Special characters in xml files

I wrote a few sqls today and found that >= and <= can be used in the database software, and an error will be reported when written in the mapper. Later, I found out that there are special escapes. The summary is as follows.

[&]——&amp;
[<]——&lt;
[>]——&gt;
["]——&quot;
[']——&apos;
original symbol escape symbol
& &amp;
< &lt;
> &gt;
>= &gt;=
<= &lt;=
&apos;
" &quot;

4. springboot startup error

insert image description here

Startup can sometimes report an error, and it seems to be a dependency conflict. At the same time, spring-boot-starter and spring-boot-starter-web are introduced. In fact, only spring-boot-starter-web needs to be introduced here, which includes spring-boot-starter.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>

5. The interface transmits Chinese garbled characters

When developing two project interfaces, when the interface of project A is called by project B, the Chinese data obtained by project B is garbled. After investigation, it is found that it is related to the Content-Type field of the http request.
The http request process includes the Accept request header (Request Header) and the Content-Type entity header (Response Header). I use hutool's http here, so add .header("Accept","text/plain ;charset=UTF-8") to solve the Chinese garbled problem, the core is still charset=UTF-8.
Here I directly print the header information of hutool:

{Accept=[text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8], 
User-Agent=[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/75.0.3770.142 Safari/537.36 Hutool], Accept-Encoding=[gzip, deflate], 
Accept-Language=[zh-CN,zh;q=0.8]}

Personal understanding: Accept is used on the client side, Content-Type is used on the server side, Chinese garbled characters can be set under the character set

result = HttpRequest.get(httpUrl)
                    .timeout(3000)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header("Accept","text/plain;charset=UTF-8")
                    .execute()
                    .body();

6. Lost temporary path

insert image description here

In the production environment of springboot, if there is no configuration directory for file upload, a temporary directory will be generated. In centos7, you can check the clearing time through the file /usr/lib/tmpfiles.d/tmp.conf. The default 10d is 10 days. In order to solve this problem, the path must be specified in the application parameter configuration.

vim /usr/lib/tmpfiles.d/tmp.conf

spring:
  profiles: produce
  servlet:
    multipart:
      max-request-size: 100MB
      max-file-size: 100MB
      location: /u01/tomcat/file/

insert image description here
insert image description here

7. The data format returned by request.getParameterMap

According to the java specification, the value returned by this method is a data type, that is, Map<String, String[]>, resulting in the value in the key-value pair of the data we finally obtained will be like this, "[123]", and then extracted Time is very troublesome. So I found a map conversion class to convert.

    /**
     * map转换类(<String,String[]>转<String,String>)
     */
    public Map<String, String> convertMap(HttpServletRequest request) {
    
    
        Map<String, String> returnMap = new HashMap<>();
        // 转换为Entry
        Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
        // 遍历
        for (Map.Entry<String, String[]> entry : entries) {
    
    
            String key = entry.getKey();
            StringBuffer value = new StringBuffer("");
            String[] val = entry.getValue();
            if (null != val && val.length > 0) {
    
    
                for (String v:val) {
    
    
                    value.append(v);
                }
            }
            returnMap.put(key, value.toString());
        }

        return returnMap;
    }

8. jsonArray to object

Matryoshka dolls often appear when doing interface docking, and the object contains jsonArray. Here, we must pay attention to carefulness and one-to-one correspondence. The objects created by yourself can only be more than those to be converted, not less. It is found that directly diyData = diyModel.getData is not easy to use after wrapping two layers. I will study it later when I have time.

//byte转String
String msg = new String(message.getPayload(), StandardCharsets.UTF_8);

DiyModel diyModel = JSONObject.parseObject(msg, DiyModel.class);

Guess you like

Origin blog.csdn.net/weixin_43487532/article/details/127287073