1. 程式人生 > 實用技巧 >ELK - Logstash連線MySQL

ELK - Logstash連線MySQL

一、從前端向後端傳送資料

常見的3種方式

1、form表單的action:此方法可以提交form表單內的輸入資料,也可同時提交某些隱藏但設定有預設值的<input>,如修改問題時,我們除了提交問題的相關資訊,還需要將使用者的編號提交給後端,此時就可以設定一個預設值為使用者編號的<input>,並將其隱藏

2、<a>標籤的href屬性:此方法一般用來提交一些較少的資料,比如物件編號

 <a href="<%=path%>/Question/DisplayQuestionInfo?question_id=${question.question_id}">${question.question_title}</a>

比如該處程式碼,顯示了問題的標題資訊,並將其作為超連結,點選該連結時進入後端Controller類的方法,並向其傳送問題編號question_id

3、ajax請求:此方法一般在不需要頁面跳轉時採用,可以區域性重新整理頁面,比如向後端提交關注某使用者的資訊,後端收到ajax的請求資料,對資料庫進行操作,並通過@Response註解返回資訊給前端,然後前端進行相關操作,可以不進行頁面跳轉

前端部分程式碼

 <script language="JavaScript">
......
function SaveUserFollowUser(){
var login_user_id = ${login_user_id} //登入者(發起者)編號
var user_id = ${user.user_id}; //接受者使用者編號 $.ajax({
url:"<%=path%>/UserRelation/SaveUserFollowUser",
type:"POST",
async: false,
contentType:"application/json;charset=UTF-8",
dataType:'json', data:JSON.stringify({"from_user_id":login_user_id,"to_user_id":user_id}), //JSON物件轉為字串
success:function(data){
/* 可在後端增加判斷髮起者和接受者使用者是否是同一使用者的判斷 */
if (data == true) {
alert("關注成功");
} else {
alert("您已經關注該使用者,不可重複關注")
}
}
});
}
</script> ......
<button class="btn btn-success" style="width: 100px" onclick="SaveUserFollowUser()">關注使用者</button>
......

後端Controller類

 /**
* 表現層 使用者關係相關 (關注使用者、被使用者關注、關注問題、贊同回答)
*/
@Controller
@RequestMapping("/UserRelation")
public class UserRelationController { ...... /**
* 新增某使用者關注某使用者
* @param map
* @return
*/
@RequestMapping(value = "/SaveUserFollowUser",method = {RequestMethod.POST})
public @ResponseBody Boolean SaveUserFollowUser(@RequestBody Map<String,String> map) { //關注發出者編號
Integer from_user_id = Integer.parseInt(map.get("from_user_id"));
//關注接受者編號
Integer to_user_id = Integer.parseInt(map.get("to_user_id"));
//是否新增成功
//該項可以增加發起者使用者和接受者使用者是否是同一使用者的判斷,即比較from_user_id與to_user_id是否相等,如果相等則關註失敗
//通過返回Integer型別而非Boolean型別的做判斷 本程式並未增加這項判斷
Boolean flag = userRelationService.saveUserFollowUser(from_user_id,to_user_id);
return flag;
} ...... }

二、從後端向前端傳送資料

1、Model

後端部分程式碼

 /**
* 表現層 使用者
*/
@Controller
@RequestMapping(value = "/User")
public class UserController { ...... /**
* 進入個人資訊頁面
* @param httpSession
* @param model
* @return
*/
@RequestMapping(value = "/DisplayMyInfo")
public String DisplayMyInfo(HttpSession httpSession, Model model) {
Integer user_id = (Integer) httpSession.getAttribute("login_user_id"); //登入者個人編號
User user = userService.findUserById(user_id); //登入者個人資訊 model.addAttribute("user",user); //將登入者個人資訊返回給前端
return "User/myInfo";
} ...... }

前端部分程式碼

 ......
<div class="col-md-6 col-md-offset-5" style="text-align: left;">
<h2>使用者名稱:${user.user_name}</h2>
<h2>使用者暱稱:${user.user_nickname}</h2>
<h2>使用者性別:${user.user_sex}</h2>
<h2>使用者郵箱:${user.user_email}</h2>
<h2>使用者密碼:${user.user_password}</h2>
</div>
......

此時可以通過${}直接取得後端傳來的資料

2、ModelAndView

該方法與Model相比,多增加了返回的檢視(View),對於返回給前端的具體資料處理類似