在以前的學習中咱們都知道,獲取view層傳遞過來的參數,咱們通常的都是key,value鍵-值對的形式,在servlet控制器中使用getParameter,來接收view層傳遞過來的參數!!!做爲表現層控制器的springMVC,給咱們提供了更加的方式去獲取view層傳遞過來的參數!!!html
參數類型分爲:前端
1. 基本數據類型和字符串類型
2. 實體類型(JavaBean)
3. 集合數據類型(List、map集合等)java
準備配置環境web
web.xml文件、springmvc文件spring
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- SpringMVC的核心控制器:前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 而後配置Servlet的初始化參數,讀取springmvc的配置文件,建立spring容器 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 首先是:servlet啓動時加載對象 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置過濾器解決中文亂碼:提供初始化參數--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!-- 啓動過濾器 --> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring建立容器時要掃描的包 --> <context:component-scan base-package="com.cc"></context:component-scan> <!-- 配置視圖解析器:返回請求成功後的頁面 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--文件所在的目錄--> <property name="prefix" value="pages/"></property> <!--文件的後綴名--> <property name="suffix" value=".jsp"></property> </bean> <!--配置日期類型轉換器--> <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <!--給工廠注入一個新的類型轉換器--> <property name="converters"> <!--把咱們本身寫的日期類型轉化器配置進去--> <bean class="com.cc.util.StringToDataCoverter"></bean> </property> </bean> <!--配置spring開啓註解mvc的支持--> <!--開啓啓動日期類型專戶器服務--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/> </beans>
實體類:Accountspring-mvc
package com.cc.entity; import java.io.Serializable; import java.util.List; import java.util.Map; /** * 用戶實體類 */ public class Account implements Serializable { private String username; private String password; private Double money; //存在引用類型的時候 private User user; //存在list和map集合的時候 List<User> list; Map<String,User> map; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } /*public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void setUser(List<User> user) { this.user = user; }*/ public Map<String, User> getMap() { return map; } public void setMap(Map<String, User> map) { this.map = map; } @Override public String toString() { return "Account{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", money=" + money + ", list=" + list + ", map=" + map + '}'; } }
實體類:Usertomcat
package com.cc.entity; import javax.xml.crypto.Data; import java.io.Serializable; public class User implements Serializable { private String uname; private String password; private Data data; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Data getData() { return data; } public void setData(Data data) { this.data = data; } @Override public String toString() { return "User{" + "uname='" + uname + '\'' + ", password='" + password + '\'' + ", data=" + data + '}'; } }
在jsp頁面,只是用鍵值對的方式session
<h1>你好tomcat</h1> <a href="/hello?username=Tom">入門程序</a>
2、在控制層代碼(控制器)mvc
要求:提交表單的name和參數的名稱是相同的app
package com.cc.controller; import com.cc.entity.Account; import com.cc.entity.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { //處理映射器,用於創建請求 URL 和處理請求方法之間的映射關係 @RequestMapping(path = "/hello") public String sayHello(String username){ System.out.println("hello springMVC"+"user:"+username); return "success"; } }
這裏還存在一個問題,就是在Account實體類中若是存在引用類型User類那怎麼辦??採用對象.屬性的表達式獲取屬性
<form action="/account" method="post"> 用戶名:<input type="text" name="name"><br> 帳戶:<input type="text" name="password"><br> 金額:<input type="text" name="money"><br> 用戶名:<input type="text" name="user.uname"><br> 密碼:<input type="text" name="user.password"><br> <input type="submit" value="提交"> </form>
list數據類型採用list[0].屬性的方式、map集合採用鍵值對的方式
實體類:Account
package com.cc.entity; import java.io.Serializable; import java.util.List; import java.util.Map; /** * 用戶實體類 */ public class Account implements Serializable { private String username; private String password; private Double money; //存在引用類型的時候 private User user; //存在list和map集合的時候 List<User> list; Map<String,User> map; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } /*public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void setUser(List<User> user) { this.user = user; }*/ public Map<String, User> getMap() { return map; } public void setMap(Map<String, User> map) { this.map = map; } @Override public String toString() { return "Account{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", money=" + money + ", list=" + list + ", map=" + map + '}'; } }
<!--綁定封裝list集合和map集合到--> <form action="/account" method="post"> 用戶名:<input type="text" name="name"><br> 帳戶:<input type="text" name="password"><br> 金額:<input type="text" name="money"><br> 用戶名:<input type="text" name="list[0].uname"><br> 密碼:<input type="text" name="list[0].password"><br> <!--帶有map數據封裝,key,value--> 用戶名:<input type="text" name="map['one'].uname"><br> 密碼:<input type="text" name="map['one'].password"><br> <input type="submit" value="提交"> </form>
在web.xml文件中配置過濾器
<!-- 配置過濾器,解決中文亂碼的問題 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter- class> <!-- 指定字符集 --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
表單提交的任何數據類型所有都是字符串類型,可是後臺定義Integer類型,數據也能夠封裝上,說明Spring框架內部會默認進行數據類型轉換。可是咱們本身想要自定義數據類型轉化怎麼辦?能夠實現Converter的接口
1、咱們能夠先建立一個數據類型轉化器,把請求過來的數據類型轉化爲咱們想要的
package com.cc.util; import org.springframework.core.convert.converter.Converter; import org.springframework.util.StringUtils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * 把字符串轉換爲日期 * StringUtils這個類須要好好研究一下 */ public class StringToDataCoverter implements Converter<String, Date> { @Override public Date convert(String source) { try { //傳進來參數爲空狀況 if (StringUtils.isEmpty(source)) { throw new RuntimeException("請輸入要轉換的日期"); } //自定義日期轉換格式 DateFormat dt = new SimpleDateFormat("yyyy-MM-dd"); return dt.parse(source); } catch (Exception e) { throw new RuntimeException(e); } } }
2、註冊自定義類型轉換器,在springmvc.xml配置文件中編寫配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring建立容器時要掃描的包 --> <context:component-scan base-package="com.cc"></context:component-scan> <!-- 配置視圖解析器:返回請求成功後的頁面 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--文件所在的目錄--> <property name="prefix" value="pages/"></property> <!--文件的後綴名--> <property name="suffix" value=".jsp"></property> </bean> <!--配置日期類型轉換器--> <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <!--給工廠注入一個新的類型轉換器--> <property name="converters"> <!--把咱們本身寫的日期類型轉化器配置進去--> <bean class="com.cc.util.StringToDataCoverter"></bean> </property> </bean> <!--配置spring開啓註解mvc的支持--> <!--開啓啓動日期類型專戶器服務--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/> </beans><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring建立容器時要掃描的包 --> <context:component-scan base-package="com.cc"></context:component-scan> <!-- 配置視圖解析器:返回請求成功後的頁面 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--文件所在的目錄--> <property name="prefix" value="pages/"></property> <!--文件的後綴名--> <property name="suffix" value=".jsp"></property> </bean> <!--配置日期類型轉換器--> <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <!--給工廠注入一個新的類型轉換器--> <property name="converters"> <!--把咱們本身寫的日期類型轉化器配置進去--> <bean class="com.cc.util.StringToDataCoverter"></bean> </property> </bean> <!--配置spring開啓註解mvc的支持--> <!--開啓啓動日期類型專戶器服務--> <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/> </beans>
在控制器中使用原生的ServletAPI對象,只須要在控制器的方法參數定義HttpServletRequest和HttpServletResponse對象
1、 使用model來保存數據到前臺
controller頁面代碼 @RequestMapping("/demo") public String Model(Model model){ UserBean bean = new UserBean(); bean.setName("admin"); bean.setPwd("admin"); model.addAttribute("admin", bean); return "Model"; }
Model.jsp頁面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> ${admin } </body> </html>
第2、使用modelView的方式
controller層代碼
@RequestMapping("/demo1") public ModelAndView ModelView(){ ModelAndView view = new ModelAndView(); UserBean bean = new UserBean(); bean.setName("孫悟空"); bean.setPwd("豬八戒"); view.addObject("admin", bean); view.setViewName("Model"); return view; }
第3、使用session來保存數據
@RequestMapping("/demo3") public String session(HttpSession session){ UserBean bean = new UserBean(); bean.setName("曹操"); bean.setPwd("周瑜"); session.setAttribute("admin", bean); return "Model"; }
第4、使用map來傳遞數據
@RequestMapping("/demo2") public String Hashmap(Map<String, Object> Map){ UserBean bean = new UserBean(); bean.setName("劉備"); bean.setPwd("張飛"); Map.put("admin", bean); return "Model"; }
//攜帶數據並實現跳轉的兩種方式 //第一種 @RequestMapping("index") public String test(Model model){ //攜帶數據 model.addAttribute("username","張三") return "index"; } //第二種 @RequestMapping("index") public ModelAndView testone(){ //攜帶數據 ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("username","張三"); modelAndView.setViewName("index"); return modelAndView; }