Jrebel plug-in implements hot deployment and file upload

1. What is jrebel?

1.1 Introduction

JRebel is a Java development tool and a plug-in for real-time code reloading. Its main function is to apply modified Java code to running applications in real time without restarting the application, thereby speeding up the development cycle and improving development efficiency.

Live code reloading: JRebel can monitor developers' modifications to Java code and apply these modifications to running applications in real time without restarting the application. This way, developers can immediately see the effects of their code changes, saving time on recompiling and deploying.

Supports multiple frameworks and servers: JRebel supports multiple Java frameworks and servers, including Spring, Hibernate, Java EE, Tomcat, Jetty, etc. Whether you are developing web applications or enterprise-level applications, JRebel can be integrated with commonly used development frameworks and servers to provide real-time code reloading.

High compatibility: JRebel is compatible with most Java development tools and integrated development environments (IDEs), such as Eclipse, IntelliJ IDEA, NetBeans, etc. Developers can use the JRebel plug-in in their favorite IDE without switching to another tool.

Fast Deployment: JRebel can speed up application deployment because it only needs to apply modified code to the running application without restarting the entire application. This is especially useful for large applications and complex deployment environments.

Supports multiple development scenarios: JRebel can be applied to various development scenarios, including local development, remote development, cloud development, etc. Whether it is stand-alone development or distributed development, JRebel can provide real-time code reloading.

        Overall, JRebel is a powerful Java development tool that enables developers to quickly apply their modifications to Java code without restarting the application through the function of real-time code reloading. This greatly improves development efficiency, reduces the development cycle, and allows developers to focus more on writing and debugging code.


1.2How to download jrebel 

Open IDEA, select File—>Settings—>Plugins—>enter jrebel in the search box

1.3 Download jrebel service and enable it

First download the service and enter the GitHub website Release v1.4 · ilanyu/ReverseProxy · GitHub

 

 Select 386.exe or adm64.exe to download

Double click the file after downloading

 After starting, you can open the idea for activation. If you do not open the service, the following error will appear:

1.4 Generate GUID online

 Generate GUID URL online: GUID online erstellen

If it fails, just refresh the GUID and replace it! 

 

1.5 JRebel activation 

Server address: https://127.0.0.1:8888/{GUID}

 The appearance of this interface indicates success

After success, you can start the project through JRebel. After modifying the Java code in this way, the time-consuming operation of restarting the server is no longer needed.

1.6 Related settings

1. Set to offline working mode 

After setting it to offline mode, there is no need to start the ReverseProxy_windows_amd64 service. This interface appears to represent and adjust it to offline mode.

2. Set up automatic compilation

To implement hot deployment, you first need to set up Intellij as follows:

        Since JRebel monitors changes in class files in real time to achieve hot deployment, the automatic mutation function needs to be turned on in the idea environment to make modifications at any time and take effect at any time.

 Notes ❗You
        need to open the Jrebel service before starting the project through Jrebel, otherwise an error will occur. Do not close the service after starting the project correctly. Turn off the server (tomcat) first and then turn off the Jrebel service. If you need to use offline mode, you cannot turn off the jrebel service first. After setting up, turning off tomcat, and finally turning off the Jrebel service, you no longer need to turn on the Jrebel service and you can start the project directly through Jrebel.

2. File upload and download

2..1 Import pom dependencies

 <commons-fileupload.version>1.3.3</commons-fileupload.version>
   
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-fileupload.version}</version>
    </dependency>

2.2 Configuration file upload parser

Add a file upload parser in the spring-mvc.xml file.

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 文件最大大小(字节) 1024*1024*50=50M-->
    <property name="maxUploadSize" value="52428800"></property>
    <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
    <property name="resolveLazily" value="true"/>
</bean>

    This code configures a bean named "multipartResolver" to handle file uploads. By setting the "defaultEncoding" attribute, "maxUploadSize" attribute, and "resolveLazily" attribute, you can specify the character encoding, maximum upload size, and delayed file parsing behavior when uploading files. In this way, the Spring framework will perform corresponding parsing and restrictions based on these configurations when processing file uploads. 


2.3 File upload form settings


        Define a simple file upload form page and set the enctype attribute to specify the encoding type of the form data as "multipart/form-data", which is the encoding type used to support file uploads. Then set the uploaded file to be named "imgFile" for acceptance by the background, and finally upload the file to the specified URL.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath }">
    <title>文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
    <label>编号:</label><input type="text" name="id" readonly="readonly" value="${param.id}"/><br/>
    <label>图片:</label><input type="file" name="imgFile"/><br/>
    <input type="submit" value="上传图片"/>
</form>
</body>
</html>

Configure table information and generate code

generatorConfig.xml :  

        <table schema="" tableName="img_upload" domainObjectName="UploadImg"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        </table>

Step 3: Create the business logic layer and implement the interface...

Step 4: Configuration file path information

resource.properties:

#本地路径
dir=D:/upload/
#服务器路径
server=/upload/

Write configuration file reading tool class

package com.xzs.utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 

public class PropertiesUtil {
 
    public static String getValue(String key) throws IOException {
        Properties p = new Properties();
        InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
        p.load(in);
        return p.getProperty(key);
    }
}

Step 5: Configure projects and mapping addresses 

 Write a controller

package com.xzs.web;
 
import com.xzs.biz.UploadImgBiz;
import com.xzs.model.UploadImg;
import com.xzs.utils.PageBean;
import com.xzs.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/file")
public class UploadImgController {
    @Autowired
    private UploadImgBiz uploadImgBiz;
 
    /*新增方法*/
    @RequestMapping("/add")
    public String save(UploadImg uploadImg, HttpServletRequest request) {
        uploadImgBiz.insertSelective(uploadImg);
        return "redirect:list";
    }
 
    /*删除方法*/
    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id") Integer id) {
        uploadImgBiz.deleteByPrimaryKey(id);
        return "redirect:/file/list";
    }
 
    /*修改方法*/
    @RequestMapping("/edit")
    public String edit(UploadImg uploadImg, HttpServletRequest request) {
        uploadImgBiz.updateByPrimaryKeySelective(uploadImg);
        return "redirect:list";
    }
 
    /*查询方法*/
    @RequestMapping("/list")
    public String list(UploadImg uploadImg, HttpServletRequest request) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<UploadImg> uploadImgs = uploadImgBiz.listPager(uploadImg, pageBean);
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("UploadImgs", UploadImgs);
//        modelAndView.addObject("pageBean", pageBean);
//        modelAndView.setViewName("UploadImg/list");
        request.setAttribute("uploadImgs", uploadImgs);
        request.setAttribute("pageBean", pageBean);
        return "file/list";
    }
 
    /*数据回显*/
    @RequestMapping("/preSave")
    public String preSave(UploadImg uploadImg, HttpServletRequest request) {
        if (uploadImg != null && uploadImg.getId() != null && uploadImg.getId() != 0) {
            UploadImg img = uploadImgBiz.selectByPrimaryKey(uploadImg.getId());
            request.setAttribute("img", img);
        }
        return "file/edit";
    }
 
    /*图片上传*/
    @RequestMapping("upload")
    public String upload(UploadImg img,MultipartFile imgFile) throws IOException {
        //读取配置文夹本地路径和服务器路径
        String dir = PropertiesUtil.getValue("dir");
        String server = PropertiesUtil.getValue("server");
 
        //利用MultipartFile类接受前端传递到后台的文件
        System.out.println("文件名:"+imgFile.getOriginalFilename());
        System.out.println("文件类型:"+imgFile.getContentType());
 
        //将文件转成流写入到服务器
        FileUtils.copyInputStreamToFile(imgFile.getInputStream(),new File(dir+imgFile.getOriginalFilename()));
 
        //通过对象将图片保存到数据库
        img.setImg(server+imgFile.getOriginalFilename());
        uploadImgBiz.updateByPrimaryKeySelective(img);
 
        return "redirect:list";
    }
}

Step 7: Write front-end jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="w" uri="http://jsp.veryedu.cn" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    <base href="${pageContext.request.contextPath }">
    <title>博客列表</title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }
 
        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }
 
        .page-item.go-input {
            margin: 0 10px;
        }
    </style>
</head>
<body>
<form class="form-inline"
      action="/file/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="name"
               placeholder="请输入用户名称">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查询</button>
    <a class="btn btn-primary mb-2" href="/file/preSave">新增</a>
</form>
 
<table class="table table-striped">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">用户</th>
        <th scope="col">图片</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="i" items="${uploadImgs }">
        <tr>
            <td>${i.id }</td>
            <td>${i.name }</td>
            <td>
                <img src="${i.img }" style="width: 200px;height: 100px;">
            </td>
            <td>
                <a href="/file/preSave?id=${i.id}">修改</a>
                <a href="/file/del/${i.id}">删除</a>
                <a href="/page/file/upload?id=${i.id}">图片上传</a>
                <a href="/file/download?id=${i.id}">图片下载</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<w:page pageBean="${pageBean }"></w:page>
 
</body>
</html>

Upload test

Image download

​​​​​​​

Guess you like

Origin blog.csdn.net/weixin_72997875/article/details/132801908