Java獲取POST數據
一般在開發的時候,我們需要獲取表單中提交的數據,那麼我們必須先創建一個say.jsp,這個jsp的內容是一個非常簡單的表單,POST方式提交,提交到/hello/show/路徑上。
- <form action='/hello/show/' method="post">
- <input name="username" type="text" />
- <input name="password" type="text" />
- <input name="" type="submit" />
- </form>
然後我們需要一個控制器文件,兩個Action,一個是現實say.jsp靜態頁面,一個是接收處理POST提交過來的數據。
其中sya()方法顯示靜態頁面;show()方法處理POST數據。
show方法兩個參數,User user這個對象 Spring會自動將POST數據填充到User這個類上面去,Modelmodel主要用來實現Controller和模板之間數據傳遞。
- package com.mvc.rest;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- //@Controller 是一個標識這個是控制器類的注解標簽,如果是控制器類 都需要有這個注解。
- @Controller
- //@RequestMapping(value="/hello") 會映射到url /hello/則訪問HelloController中的Action
- @RequestMapping(value="/hello")
- public class HelloController {
-
- //@RequestMapping(value="/say") 會映射到url /hello/say則訪問HelloController中的Action
- @RequestMapping(value="/say")
- public void say() {
- System.out.print("this is HelloController And say Action \r\n");
- }
-
- @RequestMapping("/show")
- public String show(User user,Model model) {
- System.out.print(user.getUsername());
- System.out.print(user.getPassword());
- model.addAttribute("user", user);
- return "hello/show";
- }
- }
User類:
- package com.mvc.rest;
-
- public class User {
- private String username;
-
- private String password;
-
- 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;
- }
-
-
- }
show.jsp模板類,輸出接收到的POST數據:
- user:${user.username}
- password:${user.password}
bean.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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- ">
- <context:annotation-config/>
- <aop:aspectj-autoproxy/>
- <bean id="User" class="com.mvc.rest.User" ></bean>
- </beans>