1. 程式人生 > 實用技巧 >springboot展示頁面(及關於ajax中頁面不跳轉問題)

springboot展示頁面(及關於ajax中頁面不跳轉問題)

bulid.gradle

dependencies {

	compile 'org.springframework.boot:spring-boot-starter-web:2.3.4.RELEASE'
	compile 'org.apache.httpcomponents:httpclient:4.3.5'
	compile 'org.json:json:20180130'
	testImplementation('org.springframework.boot:spring-boot-starter-test:2.3.4.RELEASE') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

 application.properties

#\u81ea\u5b9a\u4e49\u7684\u5c5e\u6027\uff0c\u6307\u5b9a\u4e86\u4e00\u4e2a\u8def\u5f84\uff0c\u6ce8\u610f\u8981\u4ee5/\u7ed3\u5c3e
web.upload-path=./resource/static
#\u8868\u793a\u6240\u6709\u7684\u8bbf\u95ee\u90fd\u7ecf\u8fc7\u9759\u6001\u8d44\u6e90\u8def\u5f84
spring.mvc.static-path-pattern=/**

spring.resources.static-locations=file:${web.upload-path},classpath:/static/

  application.yml

server:
  port: 8081  

html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>任務監控</title>
<link type="text/css" href="bootstrap/css/bootstrap.min.css"
	rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>


<style type="text/css">
body {
	text-align: center;
}

.tabTitlesContainer {
	text-align: center;
	font-size: 20px;
	cursor: hand;
	width: 100%;
	border-width: thin;
}

.tabTitleUnSelected {
	background-color: fuchsia;
	width: 100px;
}

.tabTitleUnSelected:hover {
	background-color: Orange;
}

.tabTitleSelected {
	background-color: blue;
	width: 100px;
}

#tabPagesContainer {
	text-align: left;
	width: 100%;
}

.tabPageUnSelected {
	background-color: Orange;
	display: none;
}

.tabPageSelected {
	background-color: white;
	display: block;
	padding-top: 20px;
}

.tabPage {
	min-height: 800px;
	height: 100%;
}

.my-table {
	
}
</style>
</head>
<body>
	<div>
		<h3>任務監控</h3>
	</div>
	<table class="tabTitlesContainer">
		<tr id="tabTitles">
			<td class="tabTitleSelected" onclick="tabPageControl(0)">最近任務</td>
			<td class="tabTitleUnSelected" onclick="tabPageControl(1)">異常任務</td>
			<td class="tabTitleUnSelected" onclick="tabPageControl(2)">本機情況</td>
		</tr>
	</table>
	<div id="tabPagesContainer">
		<div class="tabPageSelected">
			<div class="tabPage">
				<div class="my-table">
					<div class="table-responsive">
						<table id="my-table" class="table table-striped table-bordered">
							<thead>
								<tr>
									<th>#</th>
									<th>屬性</th>
									<th>值</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>1</td>
									<td>狀態</td>
									<td>正在查詢</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
<script type="text/javascript">

//我們可以根據jquery來進行自動獲取專案路徑,獲取方法如下
function getRootPath() {
  // 1、獲取當前全路徑
  var curWwwPath = window.location.href;
  console.log(curWwwPath);
  // 獲取當前相對路徑: /springmvc/page/frame/test.html
  var pathName = window.location.pathname;
  console.log(pathName);
  // 獲取主機地址,如: http://localhost:8080
  var local = curWwwPath.substring(0,curWwwPath.indexOf(pathName));  
  console.log(local);
  // 獲取帶"/"的專案名,如:/springmvc  
  var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); 
  console.log(projectName);
  var rootPath = local + projectName;  
  console.log(rootPath);
  //return rootPath;
  return projectName;
}
	var contextPath = getRootPath();
	
	var url = sessionStorage.getItem('server_url');
	var sid = sessionStorage.getItem('sid');
	console.log("sid=" + sid);
	if (sid == null || sid == '') {
		confirm('未登入,跳轉登入頁');
		window.location.href = "login.html";
	}else{
		getWorkItem();
	}
	
	
	function tabPageControl(n) {
		for (var i = 0; i < tabTitles.cells.length; i++) {
			tabTitles.cells[i].className = "tabTitleUnSelected";
		}
		tabTitles.cells[n].className = "tabTitleSelected";
		
		if(n==2){
			getSystemInfo();
		}else if(n==0){
			getWorkItem();
		}else if(n==1){
			getExcetionWorkItem();
		}
	}
	
	function getSystemInfo(){
		$('#my-table').html("<thead>"+
				"<tr>"+
				"<th>#</th>"+
				"<th>狀態</th>"+
				"<th>正在查詢</th>"+
				"</tr>"+
				"</thead>");
		$.ajax({
			url:contextPath + '/systemInfo',
			async:true,
			dataType:'json',
			contentType:'application/json',
			success:function(res){
				console.log(res);
				var html = '<thead> '+
				'<tr>'+
				'<th>'+"序號"+'</th>'+
				'<th>'+"屬性"+'</th>'+
				'<th>'+"值"+'</th>'+
				'</tr>'+
				'</thead>';
				var thbody = '<thbody>';
				//var data = $.parseJSON(res);
				//console.log(data);
				var i = 1;
				$.each(res,function(key,value){
					thbody+='<tr><td>'+(i++)+'</td>'+
					'<td>'+key+'</td>'+
					'<td>'+value+'</td></tr>';
				});
				thbody+='</thbody>';
				
				$('#my-table').html(html+thbody);
			},
			error:function(e){
				console.log('請求失敗:'+e);
			}
		});
	}
	
	function stop(item){
		if(item.state!='Running'){
			alert("只對執行中的任務有效")
			return false;
		}
		
	}
	
	function getWorkItem(){
		
		$.ajax({
			url:contextPath +'/workitem/list?url='+url+"&sid="+sid+"&hostName=",
			async:false,
			dataType:'json',
			contentType:'application/json',
			success:function(res){
				console.log(res);
				var html = '<thead> '+
				'<tr>'+
				'<th>'+"序號"+'</th>'+
				'<th>'+"任務名稱"+'</th>'+
				'<th>'+"活動名稱"+'</th>'+
				'<th>'+"處理者"+'</th>'+
				'<th>'+"狀態"+'</th>'+
				'<th>'+"進度"+'</th>'+
				'<th>'+"優先順序"+'</th>'+
				'<th>'+"建立者"+'</th>'+
				'<th>'+"建立時間"+'</th>'+
				'<th>'+"開始時間"+'</th>'+
				'<th>'+"結束時間"+'</th>'+
				'<th>'+"操作"+'</th>'+
				'</tr>'+
				'</thead>';
				var thbody = '<thbody>';
				$.each(res,function(n,item){
					thbody+='<tr id='+item.id+'>'+
					'<td>'+(n+1)+'</td>'+
					'<td>'+item.name+'</td>'+
					'<td>'+item.activityDefineName+'</td>'+
					'<td>'+item.worker+'</td>'+
					'<td>'+item.state+'</td>'+
					'<td>'+item.progress+'</td>'+
					'<td>'+item.priority+'</td>'+
					'<td>'+item.createdBy+'</td>'+
					'<td>'+item.createdTime+'</td>'+
					'<td>'+item.startTime+'</td>'+
					'<td>'+item.stopTime+'</td>'+
					'<td><button onclick="stop()"></button></td>'+
					'</tr>';
				});
				thbody+='</thbody>';
				
				$('#my-table').html(html+thbody);
			},
			error:function(e){
				confirm('請求失敗,跳轉登入頁')?window.location.href = "login.html":console.log("do noting");
				console.log('請求失敗:'+e);
			}
		});
	}
	
	function getExcetionWorkItem(){
		$.ajax({
			url:contextPath +'/workitem/list?url='+url+"&sid="+sid+"&status=Exception"+"&hostName=",
			async:false,
			dataType:'json',
			contentType:'application/json',
			success:function(res){
				console.log(res);
				var html = '<thead> '+
				'<tr>'+
				'<th>'+"序號"+'</th>'+
				'<th>'+"任務名稱"+'</th>'+
				'<th>'+"活動名稱"+'</th>'+
				'<th>'+"處理者"+'</th>'+
				'<th>'+"狀態"+'</th>'+
				'<th>'+"進度"+'</th>'+
				'<th>'+"優先順序"+'</th>'+
				'<th>'+"建立者"+'</th>'+
				'<th>'+"建立時間"+'</th>'+
				'<th>'+"開始時間"+'</th>'+
				'<th>'+"結束時間"+'</th>'+
				'<th>'+"操作"+'</th>'+
				'</tr>'+
				'</thead>';
				var thbody = '<thbody>';
				$.each(res,function(n,item){
					thbody+='<tr id='+item.id+'>'+
					'<td>'+(n+1)+'</td>'+
					'<td>'+item.name+'</td>'+
					'<td>'+item.activityDefineName+'</td>'+
					'<td>'+item.worker+'</td>'+
					'<td>'+item.state+'</td>'+
					'<td>'+item.progress+'</td>'+
					'<td>'+item.priority+'</td>'+
					'<td>'+item.createdBy+'</td>'+
					'<td>'+item.createdTime+'</td>'+
					'<td>'+item.startTime+'</td>'+
					'<td>'+item.stopTime+'</td>'+
					'<td><button onclick="stop()"></button></td>'+
					'</tr>';
				});
				thbody+='</thbody>';
				
				$('#my-table').html(html+thbody);
			},
			error:function(e){
				confirm('請求失敗,跳轉登入頁')?window.location.href = "login.html":console.log("do noting");
				console.log('請求失敗:'+e);
			}
		});
	}
	
	
</script>

</html>

  登入頁:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登入頁面</title>
<!-- Bootstrap 核心 CSS 檔案 -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!--font-awesome 核心我CSS 檔案-->
<link href="bootstrap/css/font-awesome.css" rel="stylesheet">
<!-- 在bootstrap.min.js 之前引入 -->
<script src="js/jquery.js"></script>
<!-- Bootstrap 核心 JavaScript 檔案 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!--jquery.validate-->

<style type="text/css">
body {
    background: url(img/bg.jpg) no-repeat;
    background-size: cover;
    font-size: 16px;
}

.form {
    background: rgba(255, 255, 255, 0.2);
    width: 100%;
    margin: 50px auto;
    padding: 100px;
}
#login_form { 
    width:30%;
    margin-left:35%;
    text-align: center;
}
input{
    text-align: center;
}
</style>
</head>
<body>
    <div class="container">
        <div class="form row">
            <form class="form-horizontal"
                id="login_form">
                <h3 class="form-title">登入</h3>
                <div>
                    <div class="form-group">
                        <label class="">系統地址</label>
                        <input class="form-control" type="text"
                            name="systemurl" autofocus="autofocus"
                            maxlength="100" value="http://127.0.0.1/central"/>
                    </div>
                    
                    <div class="form-group">
                        <label>使用者名稱</label>
                        <input class="form-control" type="text"
                            name="username" autofocus="autofocus"
                            maxlength="20" />
                    </div>
                    <div class="form-group">
                        <label>密碼</label>
                        <input class="form-control" type="password"
                            name="password" maxlength="20" />
                    </div>
                    <div class="form-group">
                        <input type="button" onclick="login()" class="btn btn-success"
                            value="登入 " />
                    </div>
                </div>
            </form>
        </div>
    </div>
</body>
<script type="text/javascript">

$('input[name="systemurl"]').val(sessionStorage.getItem("server_url"));
$('input[name="username"]').val(sessionStorage.getItem("userId"));
$('input[name="password"]').val(sessionStorage.getItem("password"));
function getRootPath() {
    
      // 1、獲取當前全路徑
      var curWwwPath = window.location.href;
      console.log(curWwwPath);
      // 獲取當前相對路徑: /springmvc/page/frame/test.html
      var pathName = window.location.pathname;
      console.log(pathName);
      // 獲取主機地址,如: http://localhost:8080
      var local = curWwwPath.substring(0,curWwwPath.indexOf(pathName));  
      console.log(local);
      // 獲取帶"/"的專案名,如:/springmvc  
      var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); 
      console.log(projectName);
      var rootPath = local + projectName;  
      console.log(rootPath);
      //return rootPath;
      return projectName;
    }
var contextPath = getRootPath();


    function login(){
        var url = $('input[name="systemurl"]').val();
        var userId = $('input[name="username"]').val();
        var password = $('input[name="password"]').val();
        if(url=='' || userId=='' || password==''){
            alert("都不可空!!!");
            return;
        }
        sessionStorage.setItem("server_url",url);
        sessionStorage.setItem("userId",userId);
        sessionStorage.setItem("password",password);
        
        $.ajax({
            url:contextPath + '/logon?url='+url+"&userId="+userId+"&password="+password,
            async:false,
            type:"POST",
            //dataType:'json',
            //contentType:'application/json',
            success:function(res){
                console.log(res);
                sessionStorage.setItem("sid",res);
                sessionStorage.setItem("server_url",url);
                $('input[type="button"]').val("登入成功");
                setTimeout('window.location.href = "index.html"',1000);
            },
            error:function(err){
                sessionStorage.setItem("sid","");
                console.log(err);
                confirm("登入失敗");
            }
        });
    }        
        
</script>
</html>

關於登入頁需要說一下:

當按鈕typ為submit時,在ajax的success的方法中window.location,href跳轉不起作用;

原因:因為有提交了一次表單。你的ajax是同步的,所以提交表單動作被掛起直到ajax完畢後(此時執行請求過一次伺服器),表單會提交,這樣就會執行頁面指定的action的地址,而ajax回撥successhref的連結賦值不成功

參考網路上的說明:你點選了submit,它會提交表單,但是由於你用了ajax的同步操作,submit的提交被阻塞,ajax先執行,這個時候,如果你在ajax的回撥函式(如:success)中寫了document.location.href='xxx.html',它是執行了,的確是去執行了跳轉的,於是ajax完成了,那接下來就要把剛才的submit提交的請求完成。於是呢又要從xxx.html跳回到剛才那個頁面(無論你submit有沒有提交具體的資料,總之提交了之後如果後臺沒有執行跳轉/重定向,它就要回到原來的頁面。)

即:ajax就是如你所想那樣執行了,也從A頁面跳到了B頁面,但是由於submit這種型別的特殊性,又讓B頁面跳回了A頁面,由於這個ajax執行完再執行submit請求的過程處理的很快,你會感到好像沒有效果,但是你仔細觀察,會發現這個過程頁面會重新整理的,其實就是B頁面跳回到A頁面。 server: port: 8081