1. 程式人生 > >Springmvc返回值,ajax,重定向

Springmvc返回值,ajax,重定向

.

TestControler:

package com.mth.springmvc;

import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mth.springmvcmodel.Person;
import com.mth.springmvcmodel.User;

/**
 * @author 註解controler
 * 
 */
@RequestMapping("/test")
// controler名稱空間或者 唯一標識
@Controller
// 用來標註當前類是springmvc的控制層的類
public class TestControler {
	/**
	 * 方法的返回值代表ModelAndView中的ViewName
	 * 
	 * @return
	 */
	@RequestMapping("/hello.do")
	// 用來訪問控制層方法的註解
	public String hello() {
		System.out.println("mth=================");
		return "index";
	}

	/**
	 * HttpServletRequest 可以直接定義在引數列表裡面
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/toPerson.do")
	public String toPerson(HttpServletRequest req) {
		String name = req.getParameter("name");
		System.out.println(name);
		return "index";
	}

	/**
	 * http://localhost:8088/Spring_MVC_2/test/toPerson1.do?name=zs name
	 * 就是前臺傳遞的name 在引數列表上面直接定義要接受的引數名稱 只要這個引數名稱一樣 就能接收傳過來的資料
	 * 
	 * @return
	 */
	@RequestMapping("/toPerson1.do")
	public String toPerson1(String name) {
		System.out.println("toPerson1方法中的name:" + name);
		return "index";
	}

	/**
	 * http://localhost:8088/Spring_MVC_2/test/toPerson2.do?name=12
	 * 
	 * 在引數列表上面直接定義要接受的引數名稱 只要這個引數名稱一樣 就能接收傳過來的資料 此時可自動轉換成引數列表裡面的型別
	 * 注意的是值與型別之間是可以轉換的
	 * 
	 * @return
	 */
	@RequestMapping("/toPerson2.do")
	public String toPerson2(Integer name) {
		System.out.println("toPerson1方法中的name:" + name);
		return "index";
	}

	/**
	 * http://localhost:8088/Spring_MVC_2/test/toPerson3.do?name=zs&age=22&
	 * address=DL 傳遞多個引數 姓名 年齡 地址 生日
	 * 
	 * @return
	 */
	@RequestMapping("/toPerson3.do")
	public String toPerson3(String name, Integer age, String address,
			Date birthday) {
		System.out.println("toPerson1方法中的name:   " + name + "....age:  " + age
				+ "....address:  " + address + "....birthday:  " + birthday);
		return "index";
	}

	/**
	 * 註冊時間型別的屬性編輯器
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				new SimpleDateFormat("yyyy-MM-dd"), true));

	}

	/**
	 * http://localhost:8088/Spring_MVC_2/test/
	 * toPerson4.do?name=zs&age=22&address=DL&birthday=2012-12-21 SpringMVC接受物件
	 * 傳遞的引數的名字必須要與實體類裡面set方法後面的字串匹配的上才能接收到引數 首字元的大小寫不區分 (通過反射方式呼叫set方法注入)
	 * 注意:請求中傳的引數和引數列表裡面的變數名或者實體裡面的set後面的字串 匹配的上就能接收到
	 * 
	 * @param p
	 * @return
	 */
	@RequestMapping("/toPerson4.do")
	public String toPerson4(Person p, User user) {
		System.out.println(p);
		// Person [address=DL, age=22, birthday=Fri Dec 21 00:00:00 CST 2012,
		// name=zs]
		System.out.println(user);
		// User [age=22, name=zs]
		return "index";
	}

	/**
	 * http://localhost:8088/Spring_MVC_2/test/toPerson5.do?name=zs&name=ww&name
	 * =ls 比如checkbox多選的時候接受的就是陣列(愛好)
	 * 
	 * @return
	 */

	@RequestMapping("/toPerson5.do")
	public String toPerson5(String[] name) {
		for (String n : name) {
			System.out.println(n);
		}
		return "index";
	}

	// =============================以下是各種頁面跳轉=====================================
	/**
	 * 反方的返回值採用的是ModelAndView new ModelAndView("person", map);
	 * 相當於把結果資料放到request裡 (此種方法不建議使用)
	 * 
	 */
	@RequestMapping("/toPerson6.do")
	public ModelAndView toPerson6() {
		Person p = new Person();
		p.setName("zs");
		p.setAge(20);
		p.setAddress("DL");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = format.parse("1986-11-12");
			p.setBirthday(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("person", p);
		return new ModelAndView("person", map);
	}

	/**
	 * 
	 * @Title: toPerson7
	 * @Description: 直接在方法的引數列表中定義一個Map,這個Map就是ModelAndView裡面的Map,
	 *               由試圖解析器統一處理,統一會走ModelAndView的介面(也不建議使用)
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/toPerson7.do")
	public String toPerson7(Map<String, Object> map) {
		Person p = new Person();
		p.setName("zs");
		p.setAge(20);
		p.setAddress("DL");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = format.parse("1986-11-12");
			p.setBirthday(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("person", p);
		return "person";
	}

	/**
	 * 
	 * @Title: toPerson8
	 * @Description: 在引數列表中直接定義Model物件 採用model.addAttribute("person", p)方法
	 *               相當於把引數值放到Request類裡面(建議使用)
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/toPerson8.do")
	public String toPerson8(Model model) {
		Person p = new Person();
		p.setName("zs");
		p.setAge(20);
		p.setAddress("DL");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = format.parse("1986-11-12");
			p.setBirthday(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addAttribute("person", p);
		return "person";
	}

	// =============================ajax=====================================
	/**
	 * @throws Exception
	 * 
	 * @Title: ajax
	 * @Description: ajax的請求返回型別值直接定義HttpServletResponse 獲得PrintWriter 把資料
	 *               寫回前臺(不建議使用)
	 * @param 設定檔案
	 * @return void 返回型別
	 * @throws
	 */
	@RequestMapping("/ajax.do")
	public void ajax(String name, HttpServletResponse response)
			throws Exception {
		String result = "hello..." + name;
		/**
		 * 直接寫回前臺
		 */
		response.getWriter().write(result);
	}

	/**
	 * 
	 * @Title: ajax
	 * @Description: 直接在引數的列表上定義PrintWriter 物件;把結果寫回介面(建議使用)
	 * @param @param name
	 * @param @param response
	 * @param @throws Exception 設定檔案
	 * @return void 返回型別
	 * @throws
	 */
	@RequestMapping("/ajax1.do")
	public void ajax1(String name, PrintWriter out) throws Exception {
		String result = "hello..." + name;
		/**
		 * 直接寫回前臺
		 */
		out.write(result);
	}

	/**
	 * 
	 * @Title: toAjax
	 * @Description: 因為頁面在WEB-INF下面,為了訪問並跳轉到Ajax.jsp介面
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/toAjax.do")
	public String toAjax() {
		return "ajax";
	}

	// =============================以下是獲取Form表單=========================================

	/**
	 * 
	 * @Title: getForm
	 * @Description: method=RequestMethod.POST 這段程式碼的意思就是規定了前臺請求的方式 必須是post方法
	 *               如果前臺form表單用get方法請求 將報錯405!為了安全性考慮!
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping(value = "/getForm.do", method = RequestMethod.POST)
	public String getForm(Person person) {
		System.out.println(person);
		return "index";
	}

	/**
	 * 
	 * @Title: toForm
	 * @Description: 訪問WEB-INF下的Form.jsp
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/toForm.do")
	public String toForm() {
		return "Form";
	}

	// =============================以下是內部重定向=========================================

	/**
	 * 
	 * @Title: redirectToForm
	 * @Description: Controler內部重定向,位址列變化 redirect:加上同一個類中要重定向到的URL, 注意:
	 *               這種寫法僅僅是在一個Controler裡面這麼寫 ,不需要指定前面的namespace
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/redirectToForm.do")
	public String redirectToForm() {
		return "redirect:toForm.do";
	}

	// =============================以下是兩個Controler內的重定向=========================================
	/**
	 * 
	 * @Title: redirectToForm
	 * @Description: redirect:/test1/toForm.do 必須加上名稱空間,還要加上/,代表從根目錄開始找。
	 *               如果不加就代表在當前Controler裡面找test1/toForm.do,因為沒有所以會報錯。
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/redirectToForm1.do")
	public String redirectToForm1() {
		return "redirect:/test1/toForm.do";
	}

}

Test1Controler:
package com.mth.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 本類只是為了測試兩個Controler之間的跳轉
 * 
 */
@RequestMapping("/test1")
// controler名稱空間或者 唯一標識
@Controller
// 用來標註當前類是springmvc的控制層的類
public class Test1Controler {

	/**
	 * 
	 * @Title: toForm
	 * @Description: 訪問WEB-INF下的Form.jsp
	 * @param @return 設定檔案
	 * @return String 返回型別
	 * @throws
	 */
	@RequestMapping("/toForm.do")
	public String toForm() {
		return "Form";
	}

}

Ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>Ajax</title>
		<script type="text/javascript" src="Jquery/jquery-1.7.1.min.js"></script>
		<script type="text/javascript" src="Jquery/jquery.js"></script>

	</head>

	<body>
		ajax獲取資料!
		<br />
		<input id="getStr" value="ajax獲取資料" type="button">
	</body>
</html>

Form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>Form.jsp</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

	</head>

	<body>
		<form action="test/getForm.do" method="post">
			name:
			<input name="name" type="text">
			<br />
			age:
			<input name="age" type="text">
			<br />
			address:
			<input name="address" type="text">
			<br />
			birthday:
			<input name="birthday" type="text">
			<br />
			<input type="submit" value="註冊">
		</form>

	</body>
</html>

person.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>Person</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

	</head>

	<body>
		跳轉成功!
		<h3>
			${person.name }
		</h3>
		<h3>
			${person.age }
		</h3>
		<h3>
			${person.address }
		</h3>
		<h3>
			<fmt:formatDate value="${person.birthday }" pattern="yyyy-MM-dd" />
		</h3>
	</body>
</html>
jquery.js
$(function() {
			$("#getStr").click(function() {
						$.ajax({
									url : "test/ajax1.do",
									type : "post",
									dataType : "text",
									data : {
										name : "zhangsan"
									},
									success : function(responseText) {
										alert(responseText);
									},
									error : function() {
										alert("System error!");
									}
								});

					})
		})