Review student assignment management system

Let the background respond to the front end immediately, the front end does not wait for the processing process

Description: There is an e-mail reminder function in the student homework management system. If it is not processed, the front end will wait for the return result and will not pop up a prompt of sending success until the email has been sent.
1. Use try{}finally{} (will be faster)

try{
    
    
	return ApiResult.success("发送成功");
}finally{
    
    
	//发送邮件代码...
}

Use the try{}finally{} statement to let the try statement directly return the result first, and then execute the mailing code at the end.

2. Use multiple threads (return results in seconds)

new thread(()->{
    
    
	//发送邮件代码...
}).start();
return ApiResult.success("发送成功");

The mail sending code originally executed by the main thread is handed over to other threads for processing, and the main thread directly returns the result.

Send an Ajax request as soon as the page is loaded

Insert picture description here

$(document).ready(function () {
    
     //此处页面打开即请求api
        $.ajax({
    
    
            type: 'GET',
            url: '/ssm/homework/getHomeWork',
            dataType: "json",
            async: false,
            success: function (data) {
    
    
             
                }
            }
        });
    });

I used to refresh a few times before displaying the data. It turned out to be adding async:false to change the asynchronous request into a synchronous request. I used to think that adding $(document).ready() can be loaded. Detailed explanation of Ajax parameters

SpringBoot hot deployment

Add spring-boot-devtools in pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
</dependency>

If you change the code, you need to press Ctrl + Shift + F9 to complete the hot deployment. Previously, only know that devtools can be used for hot deployment. SpringBoot implements hot deployment in IDEA

413 (Request Entity Too Large)

When uploading the file, it reported 413 to
modify the Nginx configuration file

server {
    
      
    ...  
    client_max_body_size 20m;  
    ...  
}

You can also modify the configuration file of tomcat (modified in application.properties)

server.tomcat.max-http-form-post-size=-1

Set the maximum capacity of post requests as unlimited

Optimize SQL

Create index

Optimize limit statement

select * from operation_log 1 limit 3000000 , 10;

select * from operation_log t , (select id from operation_log order by id limit
3000000,10) b where t.id = b.id ;

File download method

1. Using the ResponseEntity type provided by springmvc, you can use it to easily define the returned HttpHeaders and HttpStatus. (Single file)

@RequestMapping("/download")  
	    public ResponseEntity<byte[]> export(String fileName,String filePath) throws IOException {
    
      
	    	
	        HttpHeaders headers = new HttpHeaders();    
	        File file = new File(filePath);
	        
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    
	        headers.setContentDispositionFormData("attachment", fileName);    
	       
	        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                                              headers, HttpStatus.CREATED);    
	    } 

2. Download and package multiple files into a zip package

//批量文件压缩后下载
	@RequestMapping("/downLoad2")
	public ResponseEntity<byte[]> download2(HttpServletRequest request) throws IOException {
    
    
		
		//需要压缩的文件
		List<String> list = new ArrayList<String>();
		list.add("test.txt");
		list.add("test2.txt");
		
		//压缩后的文件
		String resourcesName = "test.zip";
		
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:/"+resourcesName));
		InputStream input = null;
		
		for (String str : list) {
    
    
			String name = "D:/"+str;
			input = new FileInputStream(new File(name));  
            zipOut.putNextEntry(new ZipEntry(str));  
            int temp = 0;  
            while((temp = input.read()) != -1){
    
      
                zipOut.write(temp);  
            }  
            input.close();
		}
		zipOut.close();
		File file = new File("D:/"+resourcesName);
		HttpHeaders headers = new HttpHeaders();
		String filename = new String(resourcesName.getBytes("utf-8"),"iso-8859-1");
		headers.setContentDispositionFormData("attachment", filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}

Front-end code:
1. Use Ajax request

<button type="button" onclick="download()">导出</button>
function download() {
    
    
  var url = 'download/?filename=aaa.txt';
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);    // 也可以使用POST方式,根据接口
  xhr.responseType = "blob";  // 返回类型blob
  // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
  xhr.onload = function () {
    
    
    // 请求完成
    if (this.status === 200) {
    
    
      // 返回200
      var blob = this.response;
      var reader = new FileReader();
      reader.readAsDataURL(blob);  // 转换为base64,可以直接放入a表情href
      reader.onload = function (e) {
    
    
        // 转换完成,创建一个a标签用于下载
        var a = document.createElement('a');
        a.download = 'data.xlsx';
        a.href = e.target.result;
        $("body").append(a);  // 修复firefox中无法触发click
        a.click();
        $(a).remove();
      }
    }
  };
  // 发送ajax请求
  xhr.send()
}

2. Submit using hidden forms (recommended)

var form = $("<form>");
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action",rootPath + "T_academic_essay/DownloadZipFile.do");
var input1 = $("<input>");
input1.attr("type","hidden");
input1.attr("name","strZipPath");
input1.attr("value",strZipPath);
$("body").append(form);
form.append(input1);
form.submit();
form.remove();

Guess you like

Origin blog.csdn.net/weixin_41699562/article/details/105002897