2019.4.7

package Dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DB.DB;
import Entity.Station;

public class Dao {
	public List<Station> getStationByName(String name) {
		String sql = "select * from sjzsubway where name ='" + name + "'";
		Connection conn = DB.getConn();
		Statement state = null;
		ResultSet rs = null;
		
		List<Station> list = new ArrayList<>();
		Station bean = null;
		try {
			state = conn.createStatement();
			rs = state.executeQuery(sql);
			while (rs.next()) {
				int id = rs.getInt("id");
				bean = new Station(id,name);
				list.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DB.close(rs, state, conn);
		}
		
		return list;
	}
	public List<Station> getStationById(int array[]) {
		String[] sql = new String[20] ;
		Connection conn = DB.getConn();
		Statement state = null;
		ResultSet rs = null;
		
		List<Station> list = new ArrayList<>();
		Station bean = null;
		
		try {
		  for(int i = 0; i < array.length;i++) {
			sql[i] = "select * from sjzsubway where id  = '" + array[i] + "'";
			state = conn.createStatement();
			rs = state.executeQuery(sql[i]);
			while (rs.next()) {
				String name = rs.getString("name");
				bean = new Station(array[i],name);
				list.add(bean);
			}
		  }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DB.close(rs, state, conn);
		}
		
		return list;
	}
	public List<Station> getSameAll(int number) {
		String sql = "select * from sjzsubway where id like'" + number + "__'";
		Connection conn = DB.getConn();
		Statement state = null;
		ResultSet rs = null;
		
		List<Station> list = new ArrayList<>();
		Station bean = null;
		try {
			state = conn.createStatement();
			rs = state.executeQuery(sql);
			while (rs.next()) {
				String name  = rs.getString("name");
				int id = rs.getInt("id");
				bean = new Station(id,name);
				list.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DB.close(rs, state, conn);
		}
		return list;
	}
	
	

}

  

package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {

	public static String db_url = "jdbc:mysql://localhost:3306/info_s";
	public static String db_user = "root";
	public static String db_pass = "z376371066.";
	
	public static Connection getConn () {
		Connection conn = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			conn = DriverManager.getConnection(db_url, db_user, db_pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	
	/**
	 * 关闭连接
	 * @param state
	 * @param conn
	 */
	public static void close (Statement state, Connection conn) {
		if (state != null) {
			try {
				state.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close (ResultSet rs, Statement state, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (state != null) {
			try {
				state.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws SQLException {
		Connection conn = getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="select * from sjzsubway";
		pstmt = conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		if(rs.next()){
			System.out.println("空");
		}else{
			System.out.println("不空");
		}
	}

}

  

package Entity;

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

}

  

package Servlet;

import java.io.IOException;
import java.util.ArrayList;
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 Dao.Dao;
import Entity.Station;

/**
 * Servlet implementation class StationServlet
 */
@WebServlet("/StationServlet")
public class StationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    Dao dao = new Dao();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		if ("chaxun".equals(method)) {
			chaxun(req,resp);
		}
	}
    
	
	private void chaxun(HttpServletRequest req, HttpServletResponse resp)throws IOException, ServletException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf-8");
		String startname = req.getParameter("startname");
		String endname = req.getParameter("endname");
		List<Station> stations1 = dao.getStationByName(startname);
		List<Station> stations2 = dao.getStationByName(endname);
		int num = 0;
		int[] rute = new int[100] ;
    	for(int m = 0; m < stations1.size();m++) {
    		for (int i = 0; i < stations2.size(); i++) {//不需要换乘
        		if(((stations2.get(i).getId())/100==(stations1.get(m).getId())/100)&&stations2.get(i).getId()>stations1.get(m).getId()) {
        			for(int j =stations1.get(m).getId();j<= stations2.get(i).getId();j++) {
        				rute[num] = j;
        				num++;
        			}
        		}
        		else if(((stations2.get(i).getId())/100==(stations1.get(m).getId())/100)&&stations2.get(i).getId()<stations1.get(m).getId()) {
        			for(int j =stations1.get(m).getId();j>= stations2.get(i).getId();j--) {
        				rute[num] = j;
        				num++;
        			}
        		}
        		else {//需要换乘一次
        			int numid1 = 0,numid2 = 0;
					int[] id1 = new int [5];
					int[] id2 = new int [5];
					int sum=0;
					int number = 0;
					for(int xx = 0; xx < stations1.size();xx++) {
						for(int x = 0; x < stations2.size();x++) {
							number=stations2.get(x).getId()/100;
							List<Station> samerute  = dao.getSameAll(number);//查询与终点站一条路线的所有站点的信息
							for(int y = 0; y < samerute.size();y++) {
								List<Station> samerute1  = dao.getStationByName(samerute.get(y).getName());
								for(int z = 0; z < samerute1.size();z++) {
									if((samerute1.get(z).getId()/100==stations1.get(xx).getId()/100)) {//查询终点线路上与起始站具有相同编码开头的站点名称,即中转站信息
								   
									String name = samerute1.get(z).getName();
									List<Station> ids = dao.getStationByName(name);
									System.out.println("国防费烦烦烦烦烦烦");
									for(int a = 0; a < ids.size();a++) {
										if(ids.get(a).getId()/100==stations1.get(z).getId()/100) {
											id1[numid1] = ids.get(a).getId();//与起始站编码开头相同的中转站的编号
											numid1++;
										}
										if(ids.get(a).getId()/100==stations2.get(z).getId()/100) {
											id2[numid2] = ids.get(a).getId();//与终点站编码开头相同的中转站的编号
											numid2++;
										}
										
									}
									System.out.println(id1[0]+"啊大家那几位你打就为大家我的"+id2[0]);
										if(id1[0]>stations1.get(z).getId()) {
											if(id2[0]>stations2.get(x).getId()) {
												for(int p = stations1.get(xx).getId();p<id1[0];p++) {
													rute[sum]=p;
													sum++;
													
												}
												for(int q =id2[0];q >=stations2.get(x).getId();q--  ) {
													rute[sum]=q;
													sum++;
												}
												
												
											}
											else if(id2[0]<stations2.get(x).getId()) {
												for(int p = stations1.get(xx).getId();p<id1[0];p++) {
													rute[sum]=p;
													sum++;
												}
												for(int q =id2[0];q <=stations2.get(x).getId();q++  ) {
													rute[sum]=q;
													sum++;
												}
												
											}
											
											
											
										}
										
										
										
										else if(id1[0]<stations1.get(z).getId()) {
											if(id2[0]>stations2.get(x).getId()) {
												for(int p = stations1.get(xx).getId();p>id1[0];p--) {
													rute[sum]=p;
													sum++;
												}
												for(int q =id2[0];q >=stations2.get(x).getId();q--  ) {
													rute[sum]=q;
													sum++;
												}
												
											}
											else if(id2[0]<stations2.get(x).getId()) {
												for(int p = stations1.get(xx).getId();p>id1[0];p--) {
													rute[sum]=p;
													sum++;
												}
												for(int q =id2[0];q <=stations2.get(x).getId();q++  ) {
													rute[sum]=q;
													sum++;
												}
												
											}
											
												
										}
										break;
									}
									break;
								}
								
							}
							
						}
					
					}
					
        			
        			
        		}
    	List<Station> luxian = dao.getStationById(rute);
    	
    	int sumi=0;
    	for(int ii= 1;ii<rute.length;ii++) {
    		if(rute[ii]!=0) {
    			sumi=sumi+1;
    		}
    	}
    	
    	req.setAttribute("luxian",luxian);
    	req.setAttribute("sumi",sumi);
		req.getRequestDispatcher("list.jsp").forward(req,resp);
	 }

	}
  }
}

  

<%@ 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>查询页面</title>
</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: black;">站点信息查询</h1>
		<form action="StationServlet?method=chaxun" method="post" onsubmit="return check()">
			
				<p>始发站<input type="text" id="startname" name="startname"/>
			
			
				<p>终点站<input type="text" id="endname" name="endname" />
			
			
			
				<p><button type="submit" class="b">查   询</button>
			
		</form>
			<a href="ditu.jsp" >查看地铁线路图</a>
	</div>

	<script type="text/javascript">
		function check() {
			var startname = document.getElementById("startname");;
			var endname = document.getElementById("endname");
			
			//非空
			if(startname.value == '') {
				alert('始发站不能为空');
				startname.focus();
				return false;
			}
			if(endname.value == '') {
				alert('终点站不能为空');
				endname.focus();
				return false;
			}
				
		}
	</script>

</body>
</html>

  

<%@ 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>查询结果页面</title>
</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: black;">站点信息列表</h1>
		<a href="index.jsp">返回查询界面</a>
		<h3 style="color: black;">共${sumi}站</h3>
		<table class="tb">
			<tr>
				<td>站点编号</td>
				<td>站点名称</td>
			</tr>
			<c:forEach items="${luxian}" var="item">
			
				<tr>
					<td>${item.id}</td>
					<td>${item.name}</td>	
				</tr>
			</c:forEach>
		</table>
	</div>
</body>
</html>

  

今天把有的站点录进了数据库,每个站点有两个属性,一个站点编号(一号线上的站点全是1开头的,2号线上的站点编号全是2开头的以此类推)站点名称。仍然是用了4层,DB层驱动数据库,Dao对数据库进行操作,Entity实体类,把站点作为一个对象,Servlet获取jsp输入框中的值,并进行值的传递。

今天将方法重新修改了,思路是:用户输入起始站名称和终点站的名称,Servlet层获取这两个变量,然后调用Dao层中的public List<Station> getStationByName(String name)方法分别获取起始站和终点站的信息,包括站点名称和站点编号。首先判断,这两个站点的编号里边是否存在相同开头的站点编号,如果存在,那么不许换乘,直达即可。如果没有相同开头的站点编号,那么这种情况下需要换乘。在看了许多种情况下发现,在不考虑路程远近的情况下,换乘一次就可以从起始站到终点站。首先,根据终点站的名称,查出他的编号,然后在通过站点编号查出与重点站在同一条线路上的所有站点的信息,在这些站点中查询与起始站具有相同编号开头的站点,这个站点便是中转站。获取中转站的信息,然后将他的所有与起始站和终点站的编号进行比较,便可得出路线。

存在的问题:由于算法不优化,for循环太多,存在很多的bug,线路重复输出,无法生成最优路径等问题,会在后期的过程中慢慢的优化算法。

posted @ 2019-04-07 17:23  HHHarden13  阅读(122)  评论(0编辑  收藏  举报