Data structure - bus line prompt system (Java background + excel table + web front end)

Keywords: PHP JSP Java Apache Javascript

General process of the system:

index.jsp input the station name (click "show site information", jump to list.jsp to read the table);
Background obtains id through station name; getIdbyname(String name)
The id is fed back to dijkstra(int vs,int vf) to find the shortest path and the vertex on the path (read the document to get the Graph);
dijkstra is still a number, so getNamebyid(int id) is also needed; use list < string > to return the site name on the shortest path

Finally, feedback to succeeded.jsp

Source code:

servlet layer:

import java.io.IOException;
import java.util.List;

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

import entity.Bus;
import service.busService;

/**
 * Servlet implementation class busServlet
 */
@WebServlet("/busServlet")
public class busServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    busService bus=new busService();
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if(method.equals("dijkstra"))
        {
            dijkstra(req,resp);
        }else if(method.equals("list"))
        {
            list(req,resp);
        }else if(method.equals("getIdbyname"))
        {
            getIdbyname(req,resp);
        }
    }

    private void getIdbyname(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * Get id by name
         * Used to determine whether the input station name has inventory in the table
         */    
        req.setCharacterEncoding("utf-8");
        String s = req.getParameter("start");
        String f = req.getParameter("final");
        int k1=bus.getIdbyname(s);
        int k2=bus.getIdbyname(f);
        if(k1!=-1&&k2!=-1) {//And operation, both sides are true at the same time
            req.setAttribute("message", "query was successful");//setAttribute Method is used to save content in an object and transfer it to jsp in
            req.getRequestDispatcher("busServlet?method=dijkstra").forward(req,resp);//getRequestDispatcher Method to go to the next page
        }else if(k1==-1||k2==-1){//Or operation, one on both sides is true
            req.setAttribute("message", "Station name is wrong, please make sure it is entered correctly");
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }
    private void list(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        List<Bus> buses = bus.readExcelList();
        req.setAttribute("buses", buses);
        req.getRequestDispatcher("list.jsp").forward(req,resp);    
    }
    
    private void dijkstra(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String s = req.getParameter("start");
        String f = req.getParameter("final");
        int vs=bus.getIdbyname(s);
        int vf=bus.getIdbyname(f);
        List<String> stations=bus.dijkstra(vs, vf);
        req.setAttribute("stations",stations);//setAttribute Method is used to save content in an object and transfer it to jsp in
        req.getRequestDispatcher("succeed.jsp").forward(req,resp);//getRequestDispatcher Method to go to the next page        
    }
    
    
}
busServlet

service layer:

import java.io.IOException;
import java.util.List;

import busRoute.Dao;
import entity.Bus;

public class busService {
    Dao dao=new Dao();
    public List<String> dijkstra(int vs,int vf) throws IOException {
        // TODO Automatically generated method stubs
        
        return Dao.dijkstra(vs,vf);
    }
    public List<Bus> readExcelList() throws IOException {
        // TODO Automatically generated method stubs
        return dao.readExcelList();
    }
    public int getIdbyname(String str) throws IOException {
        int t=dao.getIdbyname(str);
        return t;
    }

}
busService

entity level:

public class Bus {
    private String name;
    private int id;
    public void setName(String name) {
            this.name=name;
    }
    public String getName() {
            return name;
    }
    public void setId(int id) {
        this.id=id;
    }
    public int getId() {
        return id;
    }
    public Bus() {
    }
    public Bus(int b,String a) {
        name=a;
        id=b;
    }   
}
Bus

dao level:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import entity.Bus;

public class Dao{
    

    public List<Bus> readExcelList() throws IOException {
         /**
          * Read form
          * Output to front end
          */
             
             List<Bus> list = new ArrayList<>();
            String filePath="D://dns.xls";
            InputStream input = new FileInputStream(filePath);
            Workbook wb = null;
            wb = new HSSFWorkbook(input);
            //Get a worksheet object;
            Sheet sheet = wb.getSheetAt(0);
            int rsRows = sheet.getLastRowNum();// Obtain sheet Total rows in table
            
         // Traverse row
            //One for each line bus object
            Bus bus=null;
            for (int i=0;i<=rsRows;i++) {
                Row row = sheet.getRow(i);
                int id=0;
               String name=null;
                //Traversing row cells, known to have two columns;First column int type id,The second column String type name
                    Cell cell1 = row.getCell(0);
                    Cell cell2 = row.getCell(1);
                    //Be sure to check if it is empty
                    if(cell1==null||cell1.equals(null)||cell1.getCellType()==CellType.BLANK){
                        break;
                    }else {
                        //Numerical type
                        id=(int) cell1.getNumericCellValue();
                        
                    }
                    if(cell2==null||cell2.equals(null)||cell2.getCellType()==CellType.BLANK){
                         break;
                    }else {
                        //String type
                        name= cell2.getStringCellValue();
                    }
               bus=new Bus(id,name);
               list.add(bus);
                    }      
            wb.close();//Close
             return list;                    
        }
    
    public static  List<String>  readTxtFile(String filePath) {
        /**
         * Read document
         * @param filePath
         * @return
         */
                List<String> list = new ArrayList<String>();
                try {
                    String encoding = "UTF-8";
                    File file = new File(filePath);
                    if (file.isFile() && file.exists()) { 
                        InputStreamReader read = new InputStreamReader(
                                new FileInputStream(file), encoding);
                        BufferedReader bufferedReader = new BufferedReader(read);
                        String lineTxt = null;
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            if (!lineTxt.startsWith("#"))
                                list.add(lineTxt);
                        }
                        read.close();
                    } else {
                        System.out.println("cannot find file");
                    }
                } catch (Exception e) {
                    System.out.println("Error");
                    e.printStackTrace();
                }
                return list;
          
            }
    
    
    public static String[][] createArray(String filePath){
        /**
         * Read document to generate 2D array
         * @param filePath
         * @return
         */
            List<String> list = readTxtFile(filePath);
            System.out.println("Read successful");
            String[][] array = new String[list.size()][];
            for(int i=0;i<list.size();i++){
                array[i] = new String[list.size()];
                String linetxt=list.get(i);
                String[] myArray = linetxt.replaceAll("\\s+", "@").split("@");
                for(int j=0;j<myArray.length;j++){
                        array[i][j]=myArray[j];                                        
                }
            }
            return array;
        }
    
    
    public static int[][] str2int(String[][] str){//String Type conversion to int type
        int a,b;
        a = str.length;
        b = str[0].length;
        int result[][] = new int[a][b];
        for(int i = 0 ; i < a ; ++ i)
            for(int j = 0 ; j < b ; ++ j) {
                result[i][j] = Integer.parseInt(str[i][j]);
            }
                
        return result;
    }
    
    public static List<String> dijkstra(int vs,int vf) throws IOException {
        /**
        * Dijkstra Shortest path.
        * That is, the shortest path from "node vs" in the figure to other nodes.
        * @param vs Starting node
        * @param Graph chart
        * Store the vertex and distance on the shortest path into the generic set list, and return
        * Note that Integer cannot be int
         */
        List<String> list= new ArrayList<String>();//Save the vertex and distance in the shortest path list,Return
        String[][] str= createArray("D:\\text.txt");
        //Will read String Type 2-D array converted to int type       
        int[][]Graph =str2int(str);    
        int NUM = Graph[0].length;
        
        int[] prenode = new int[NUM];//Array of precursor nodes
        
        
        int[] path = new int[NUM];//Shortest distance array
        
        
        boolean[] flag = new boolean[NUM];// Whether the node has found the shortest path
         
        int vnear = 0;//distance vs Nearest node
        
        //Initialization
        for (int i = 0; i <path.length; i++) {
            prenode[i] = i;
            path[i] = Graph[vs][i];//vertex i The shortest path of is vertex vs reach i Right
            flag[i] = false;
        }
 
        flag[vs] = true;//vs Self initialization
        
        //ergodic Graph.length-1 Find the shortest path of each vertex
        for (int v = 1; v < Graph.length; v++) {
            // Find the current distance in each cycle vs Nearest vertex vnear And the shortest distance min
            int min = 100000;//100000 Express infinity
            for (int j = 0; j < Graph.length; j++) {
                if (!flag[j] && path[j] < min) {
                    min = path[j];
                    vnear = j;
                }
            }
            //Labeled vertex vnear Get the shortest path for
            flag[vnear] = true;
            
            // according to vnear To update vs Precursor and shortest path to all other nodes
            for (int k = 0; k < Graph.length; k++) {
                if (!flag[k] && (min + Graph[vnear][k]) < path[k]) {
                    prenode[k] = vnear;
                    path[k] = min + Graph[vnear][k];
                }
            }
        }
        //Save predecessors in turn
        for(int i=0;i<9&&prenode[vf]!=vs;i++) {
            list.add(getNamebyid(vf));
            vf=prenode[vf];
        }
        list.add(getNamebyid(vs));
        list.add(path[vf]+"");//+""The effect is to int Translate into String type
        return list;
    }
    
    public int getIdbyname(String name)throws IOException  {
        //adopt name Get id
        int x=-1;
        String filePath="D://dns.xls";
         InputStream input = new FileInputStream(filePath);
            Workbook wb = null;
            wb = new HSSFWorkbook(input);
            //Get a worksheet object;
            Sheet sheet = wb.getSheetAt(0);
            int rsRows = sheet.getLastRowNum();// Obtain sheet Total rows in table            
             // Traverse row
        for (int i=0;i<=rsRows;i++) {
            Row row = sheet.getRow(i);
            int id=0;
            String flag=null;
            //Traversing row cells, known to have two columns;First column int type id,The second column String type name
                Cell cell1 = row.getCell(0);
                Cell cell2 = row.getCell(1);
                if(cell1==null||cell1.equals(null)||cell1.getCellType()==CellType.BLANK){
                    break;
                }else {
                    //Numerical type
                    id=(int) cell1.getNumericCellValue();
                    
                };
                if(cell2==null||cell2.equals(null)||cell2.getCellType()==CellType.BLANK){
                     break;
                }else {
                    //String type
                    flag= cell2.getStringCellValue();
                };    
                String a=new String(flag); 
                String b=new String(name);
                if(a.equals(b)){
                    x=id;
                };
        }                    
        wb.close();//Remember to close down.
        return x;
    }
    
    public static String getNamebyid(int id) throws IOException {
        //adopt id Get name
        String str=null;
        String filePath="D://dns.xls";
        InputStream input = new FileInputStream(filePath);
        Workbook wb = null;
        wb = new HSSFWorkbook(input);
        //Get a worksheet object;
        Sheet sheet = wb.getSheetAt(0);
        int rsRows = sheet.getLastRowNum();// Obtain sheet Total rows in table            
         // Traverse row

        for (int i=0;i<=rsRows;i++) {
            int flag=0;
            String name=null;
            Row row = sheet.getRow(i);
            //Traverse row cell
            Cell cell1= row.getCell(0);
            Cell cell2 = row.getCell(1);
            if(cell1==null||cell1.equals(null)||cell1.getCellType()==CellType.BLANK){
                break;
            }else {
                //Numerical type
                flag=(int) cell1.getNumericCellValue();
                
            }
            if(cell2==null||cell2.equals(null)||cell2.getCellType()==CellType.BLANK){
                 break;
            }else {
                //String type
                name= cell2.getStringCellValue();
            }
            if(flag==id){
                str=name;
            }
        }
        
        wb.close();//Remember to close down.    
        return str;
}
}
Dao

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>home page</title>
<style >
.a{
        font-size: 26px;
        margin-top: 20px;
    }
</style>
</head>
<body>
<%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
     
%>
     <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>");
         </script>
<%} %>
<div align="center">
        <h1 style="color: red;">Bus routes</h1>
        <a href="busServlet?method=list">Show site information</a>
        <form action="busServlet?method=getIdbyname" method="post" onsubmit="return check()">
            <div >
                //Starting point<input type="text" id="start" name="start"/>
            </div>
            <div >
                //End<input type="text" id="final" name="final" />
            </div>
            <div >
                <button type="submit" >Determine</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        function check() {
            var a = document.getElementById("start");
            var b= document.getElementById("final");
            //Not empty
            if(a.value == '') {
                alert('The starting point is empty.');
                a.focus();
                return false;
            }
            if(b.value == '') {
                alert('The end is empty.');
                b.focus();
                return false;
            }
        }
    </script>
</body>
</html>
index.jsp

list.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List table contents</title>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
    .tb, td {
        border: 1px solid black;
        font-size: 22px;
    }
</style>
</head>
<body>
    <%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
     
    %>
         <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>");
         </script>
    <%} %>
    <div align="center">
        <h1 style="color: red;">Site list</h1>
        <a href="index.jsp">Back home page</a>
        <table class="tb">
            <tr>
                <td>site id</td>
                <td>Site name</td>
            </tr>
            <c:forEach items="${buses}" var="item">
                <tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
</html>
list.jsp

 succeed.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Shortest path</title>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
    .tb, td {
        border: 1px solid black;
        font-size: 22px;
    }
</style>
</head>
<body>
    <%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
     
    %>
         <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>");
         </script>
    <%} %>
    <div align="center">
        <h1 style="color: red;">Shortest path</h1>
        <a href="index.jsp">Back home page</a>
        <table class="tb">
            <tr>
                <td>Site reverse order</td>
            </tr>
            <c:forEach items="${stations}" var="item">
                <tr>
                    <td>${item}</td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
</html>
succeed.jsp

 

Project layout: (it is basically the same as the operation of connecting to the database, except that when I do it, I do not build another excel util package similar to connecting to the database, but directly connect to the dao layer; my friends can try to build excel util package, which will be much more convenient.)

 

 

Running screenshot:

Home page: index.jsp

 

Click "show site information": list.jsp

Enter start point, end point:

Check input site name:

Output shortest path: succeeded.jsp

Posted by Francky683 on Sat, 02 Nov 2019 18:01:02 -0700