1. 程式人生 > >springMVC簡單互動

springMVC簡單互動

利用springMVC框架簡單實現下前後端資料互動

test.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath}/test/bb">
		userName:<input type="text" name="name">
		<br>
		age		:<input type="text" name="age">
		<br>
		<input type="submit" value="submit">
	</form>
	<br>
		<br>
	<button onclick="get()">ajax</button>
<script>
function get(){
	$.ajax({
		type:"get",
		url:"${pageContext.request.contextPath}/test/cc",
		dateType:"text/html",
		success:function(data,textStatus,jqXHR){
			$("[name='name']").val(data[0]);
			$("[name='age']").val(data[1]);
		},
		error:function(XMLHttpRequest,textStatus,errorThrown){
			alert("error");
		}
	});
}
	</script>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page isELIgnored="false"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h2>歡迎進入本頁面</h2>
<h1>name:${name}</h1>
<h1>age:${age}</h1>
</body>
</html>

controller:

package com.qc2.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

@Controller
@RequestMapping("/test")
public class Demo {

	@RequestMapping(value="/bb")
	public ModelAndView returninfo(String name,String age) {
		System.out.println(name+":::::"+age);
		ModelAndView mv=new ModelAndView();
		mv.addObject("name",name);
		mv.addObject("age",age);
		mv.setViewName("success");
		return mv;
	}
	
	@ResponseBody
	@RequestMapping(value="/cc")
	public String[] returninfo() {
		String name="lyc";
		String age="18";
		String arr[]= {name,age};
//		Gson json=new Gson();
//		String data = json.toJson(arr);
		return arr;
	}
}

實現效果:

 

點選ajax按鈕呼叫後端的方法更改表單的值,

點選submit跳轉到另一個jsp檔案。