歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 獲取POST數據以及簡單模板輸出

Java 獲取POST數據以及簡單模板輸出

日期:2017/3/1 10:06:25   编辑:Linux編程

Java獲取POST數據

一般在開發的時候,我們需要獲取表單中提交的數據,那麼我們必須先創建一個say.jsp,這個jsp的內容是一個非常簡單的表單,POST方式提交,提交到/hello/show/路徑上。

  • <form action='/hello/show/' method="post">
  • <input name="username" type="text" />
  • <input name="password" type="text" />

  1. <input name="" type="submit" />
  2. </form>

然後我們需要一個控制器文件,兩個Action,一個是現實say.jsp靜態頁面,一個是接收處理POST提交過來的數據。

其中sya()方法顯示靜態頁面;show()方法處理POST數據。

show方法兩個參數,User user這個對象 Spring會自動將POST數據填充到User這個類上面去,Modelmodel主要用來實現Controller和模板之間數據傳遞。

  1. package com.mvc.rest;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. //@Controller 是一個標識這個是控制器類的注解標簽,如果是控制器類 都需要有這個注解。
  6. @Controller
  7. //@RequestMapping(value="/hello") 會映射到url /hello/則訪問HelloController中的Action
  8. @RequestMapping(value="/hello")
  9. public class HelloController {
  10. //@RequestMapping(value="/say") 會映射到url /hello/say則訪問HelloController中的Action
  11. @RequestMapping(value="/say")
  12. public void say() {
  13. System.out.print("this is HelloController And say Action \r\n");
  14. }
  15. @RequestMapping("/show")
  16. public String show(User user,Model model) {
  17. System.out.print(user.getUsername());
  18. System.out.print(user.getPassword());
  19. model.addAttribute("user", user);
  20. return "hello/show";
  21. }
  22. }

User類:

  1. package com.mvc.rest;
  2. public class User {
  3. private String username;
  4. private String password;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. }

show.jsp模板類,輸出接收到的POST數據:

  1. user:${user.username}
  2. password:${user.password}

bean.xml配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-2.5.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  13. ">
  14. <context:annotation-config/>
  15. <aop:aspectj-autoproxy/>
  16. <bean id="User" class="com.mvc.rest.User" ></bean>
  17. </beans>
Copyright © Linux教程網 All Rights Reserved