28、(知識篇)SpringMVC05 Spring 註解@ModelAttribute

/**

* Spring 註解@ModelAttribute

* 使用@ModelAttribute會在本類的所有方法執行之前先執行一次。

* 通常使用場景是在修改一個數據記錄,然後某些字段的值需要保留

* 但是也不放在隱藏域中,這樣可以用到@ModelAttribute註解

* 當然 使用者可以加多額外的判斷,限制某寫方法執行或者不執行ModelAttribute裏面的方法

*

* 當前事例是:

* 訪問:http://127.0.0.1:8080/28SpringMVC05/testModelAttribute

* 會有 new User(1, "你的名字", 20)

* 當在index.jsp 修改 年齡爲 21時,(id沒有作爲隱藏域)提交

* http://127.0.0.1:8080/28SpringMVC05/submitUser

* 同樣會得到結果 User [id=1, userName=你的名字, age=23]

* 其中需要注意的是:

* 1、獲取ModelAttribute註解 對應put入key的值

* 可以在參數前用@ModelAttribute 修飾 設置相關value獲取

* 2、如果參數前不用@ModelAttribute 修飾

*  spring默認會使用參數的類名首字母小寫的形式來獲取

* 3、***注意額外知識: 

* 如果參數前用@ModelAttribute 修飾,但是也類也聲明瞭對應key的SessionAttribute註解

* 如果沒有找到相關類,則會拋異常

* @param map

*/


測試類:

package com.spring.test;

import java.io.UnsupportedEncodingException;
import java.util.Map;

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

import com.spring.vo.User;

@Controller
public class TestController {
	/**
	 * Spring 註解@ModelAttribute
	 * 使用@ModelAttribute會在本類的所有方法執行之前先執行一次。
	 * 通常使用場景是在修改一個數據記錄,然後某些字段的值需要保留
	 * 但是也不放在隱藏域中,這樣可以用到@ModelAttribute註解
	 * 當然 使用者可以加多額外的判斷,限制某寫方法執行或者不執行ModelAttribute裏面的方法
	 *
	 * 當前事例是:
	 * 訪問:http://127.0.0.1:8080/28SpringMVC05/testModelAttribute
	 * 會有 new User(1, "你的名字", 20)
	 * 當在index.jsp 修改 年齡爲 21時,(id沒有作爲隱藏域)提交
	 * http://127.0.0.1:8080/28SpringMVC05/submitUser
	 * 同樣會得到結果 User [id=1, userName=你的名字, age=23]
	 * 
	 * 其中需要注意的是:
	 * 1、獲取ModelAttribute註解 對應put入key的值
	 * 	可以在參數前用@ModelAttribute 修飾 設置相關value獲取
	 * 2、如果參數前不用@ModelAttribute 修飾
	 *  spring默認會使用參數的類名首字母小寫的形式來獲取
	 * 3、***注意額外知識: 
	 * 	如果參數前用@ModelAttribute 修飾,但是也類也聲明瞭對應key的SessionAttribute註解
	 * 	如果沒有找到相關類,則會拋異常
	 * 
	 * @param map
	 */
	
	
	@ModelAttribute(value="user")
	public void getUser(Map<String,Object> map){
		System.out.println("獲取user...");
		map.put("user", new User(1, "你的名字", 20));
	}
	
	
	@RequestMapping("testModelAttribute")
	public String testModelAttribute(){
		return "index";
	}
	
	@RequestMapping("submitUser")
	//public String submitUser(@ModelAttribute(value="user") User user)
	public String submitUser(User user) throws UnsupportedEncodingException{
		user.setUserName(new String(user.getUserName().getBytes("ISO-8859-1"),"UTF-8"));
		System.out.println(" user == "+user);
		return "index";
	}
	
}

user類:

package com.spring.vo;

import org.springframework.stereotype.Component;

@Component
public class User {
	public int id ;
	private String userName;
	private int age;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(int id, String userName, int age) {
		super();
		this.id = id;
		this.userName = userName;
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";
	}
	
}

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<context:component-scan base-package="com.spring"></context:component-scan>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="suffix" value=".jsp"></property>
		<property name="prefix" value="/WEB-INF/views/"></property>
	</bean>
	
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>27SpringMVC04</display-name>
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

web-inf/views/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<form action="submitUser" method="post">
		
		username:<input type="text" name="userName" value="${user.userName }">
		<br>
		age:<input type="text" name="age" value="${user.age }">
		<br>
		<input type="submit" value="提交修改">
	</form>
	
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章