将Servlet代码更改为Spring Boot框架

问题描述 投票:0回答:1

我目前有一个apache tomcat服务器,它使用servlet以表格格式显示.csv数据,它不是很复杂。 我想尝试将我当前的设置转换为 Spring Boot 作为学习 Spring Boot 的一种方式。

我当前的代码获取文件存储的目录并创建文件列表,然后使用 CSVReader 读取每个 csv 文件。

本质上我想从文件中读取数据并将其显示在表格中。目前使用 .csv,但很乐意更改格式。

如果不创建与前一个类似的 servlet,我无法想出一种方法来实现此目的。有人能指出我正确的方向吗?我认为我的原始设计也没有分层逻辑,这可能需要一些重新设计才能与这个框架一起使用。

import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Collections;
import java.util.Arrays;
import java.io.File;
import java.time.LocalDate;

import com.opencsv.CSVReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TonerLevels
 */
@WebServlet(urlPatterns = {"/TonerLevels", "/"})
public class TonerLevels extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    
    public void init() throws ServletException {
        // Do required initialization
     }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("<script type=\"text/javascript\" src=\"/js/bootstrap.bundle.js\"></script>\n");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/bootstrap.css\"></link>\n");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/style.css\"></link>\n");
        out.println("<script type=\"text/javascript\" src=\"/js/script.js\"></script>\n");

        File[] fileList = fileList();       

        String title = "KHS Printers";
        String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
        String nav = "<nav data-bs-theme=\"dark\" class=\"navbar navbar-expand-lg bg-body-tertiary\">\r\n"+
             "  <div class=\"container-fluid\">\r\n"+
             "    <a class=\"navbar-brand\" >KHS Printers</a>\r\n"+
             "    <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\r\n"+
             "      <span class=\"navbar-toggler-icon\"></span>\r\n"+
             "    </button>\r\n"+
             "    <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\">\r\n"+
             "      <ul class=\"navbar-nav nav-pills me-auto mb-2 mb-lg-0\">\r\n"+
             "        <li class=\"nav-item\">\r\n"+
             "          <a class=\"nav-link active\" aria-current=\"page\" href=\"/TonerLevels\">Toner Levels</a>\r\n"+
             "        </li>\r\n"+
             "        <li class=\"nav-item\">\r\n"+
             "          <a class=\"nav-link\" href=\"/MonoPrints\">Mono Prints</a>\r\n"+
             "        </li>\r\n"+
             "    <li class=\"nav-item\">\r\n"+
             "          <a class=\"nav-link\" href=\"/MonoCopies\">Mono Copies</a>\r\n"+
             "        </li>\r\n"+
             "    <li class=\"nav-item\">\r\n"+
             "          <a class=\"nav-link\" href=\"/ColourPrints\">Colour Prints</a>\r\n"+
             "        </li>\r\n"+
             "    <li class=\"nav-item\">\r\n"+
             "          <a class=\"nav-link\" href=\"/ColourCopies\">Colour Copies</a>\r\n"+
             "        </li>\r\n"+
             "    <li class=\"nav-item dropdown\">\r\n"+
                 "      <a class=\"nav-link dropdown-toggle\" data-bs-toggle=\"dropdown\" href=\"#\" role=\"button\" aria-expanded=\"false\">Monthly Reports</a>\r\n"+
             "      <ul class=\"dropdown-menu\">\r\n"+
             "      <form action=\"Monthly\" method=\"post\">\r\n";
            if(fileList.length > 0){
                for(int i = 0; i < fileList.length; i++){
                    String name = fileList[i].getName();
                    LocalDate date = LocalDate.parse(name.substring(0,name.length()-4));
                    String month = date.getMonth().minus(1).toString();
                    String year = Integer.toString(date.getYear());
                    nav+="<li><button type=\"submit\" class=\"dropdown-item\" name=\"report\" value=\""+name+"\" href=\"/Monthly\">"+month+" "+year+"</button></li>\r\n";
                }
            }
            nav+=""+    
             "      </form>\r\n"+   
                 "      </ul>\r\n"+
             "    </li>\r\n"+
             "      </ul>\r\n"+
             "    </div>\r\n"+
             "  </div>\r\n"+
             "</nav>\r\n";
        String path = this.getClass().getClassLoader().getResource(".").getPath();
        path = path.replaceAll("%20", " ");
        try { 
            FileReader filereader = new FileReader(path+"printers/printers.csv");
            CSVReader csvReader = new CSVReader(filereader);
            String[] nextRecord;

            out.println(docType +
                "<html>\n" +
                    "<head><title>" + title + "</title>\n" +
                    "</head>\n" +
                    "<body onload=\"sortTable()\">\n" +
                        nav +               
                        "<table class=\"table table-dark table-hover\">\n");
                        int i = 0;
                        String regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$";
                        Pattern pattern = Pattern.compile(regex);

                        while ((nextRecord = csvReader.readNext()) != null) {   
                            if (i==0){
                                out.println("<thead>\n");
                                out.println("<tr>\n");
                                for (String cell : nextRecord) {
                                    if("Black".equals(cell) || "Yellow".equals(cell) || "Magenta".equals(cell) || "Cyan".equals(cell) || "K1".equals(cell) || "K2".equals(cell)){
                                        out.println("<th>" + cell + " %</th>\n");
                                    }
                                    else{
                                        out.println("<th>" + cell + "</th>\n");
                                    }
                                }
                                out.println();
                                out.println("</tr>\n");
                                out.println("</thead>\n");
                                out.println("<tbody class=\"table-group-divider\">\n");
                            }
                            else{
                                out.println("<tr>\n");
                                for (String cell : nextRecord) {
                                    Matcher matcher = pattern.matcher(cell);
                                    if(matcher.matches()){
                                        out.println("<td><a href=\"http://"+cell+"\"target=\"_blank\" rel=\"noopener noreferrer\">"+ cell +"</a></td>\n");
                                    }
                                    else if(cell.matches("-?(0|[1-9]\\d*)")){
                                        out.println("<td>" + Integer.parseInt(cell) + "</td>\n");
                                    }
                                    else {
                                        out.println("<td>" + cell + "</td>\n");
                                    }
                                }
                                out.println();
                                out.println("</tr>\n");
                            }
                            i++;
                        }
                        out.println("</tbody>\n");
                        out.println("</table>\n" +
                    "</body>\n" +
                "</html>\n"
                );
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

    private File[] fileList(){
        //get list of files in /printers/reports
        File catalinaBase = new File( System.getProperty( "catalina.base" ) ).getAbsoluteFile();
        File f = new File( catalinaBase, "/webapps/ROOT/WEB-INF/classes/printers/reports");
        File[] fileList = new File[0];
        if(f.isDirectory()) {
            fileList = f.listFiles();
            if(fileList.length > 0) {
                Arrays.sort(fileList, Collections.reverseOrder());
            }
        }
        return fileList;
    }

}

java spring spring-boot spring-mvc servlets
1个回答
0
投票

我最终将打印机数据保存为 json 并使用 Spring Boot / React。 我采取的步骤:

  • 使用 Jackson 将 json 反序列化为打印机对象列表(我制作的打印机类)
  • 将打印机对象列表用于rest api(Spring Boot的内置功能)
  • 在react中使用axios获取api(包含我的打印机的json)并将它们映射到react中的打印机类型

所以本质上 Spring Boot 会完成所有工作并公开我想通过 api 显示的内容,然后 React 将显示数据。

© www.soinside.com 2019 - 2024. All rights reserved.