Spring MVC系列:(9)接收瀏覽器傳來的參數


一、使用傳統HttpServletRequest、HttpServletResponse對象html


能夠在業務控制方法中書寫傳統web參數,這種方式並不提倡,由於耦合了Servlet的API。SpringMVC與Struts2同樣,也儘可能與Servlet API解耦。java

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @RequestMapping(value="/add")
    public String add(HttpServletRequest request, HttpServletResponse response) throws Exception{
        
        Integer id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        Double sal = Double.parseDouble(request.getParameter("sal"));
        
        System.out.println(id + " - " + name + " - " + sal);
        return "/success.jsp";
    }
    
}


在瀏覽器地址欄輸入:web

http://127.0.0.1:8080/springmvc02/user/add.action?id=1&name=Tomcat&sal=123.45

控制檯輸出:spring

1 - Tomcat - 123.45


二、在方法中添加多個參數接收各個表單數據數組

在業務控制方法中寫入模型變量收集參數,且使用@InitBind來解決字符串轉日期類型瀏覽器


準備JSP頁面服務器

index.jspmvc

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta name="content-type" content="text/html; charset=UTF-8">
        <title>Index Page</title>
    </head>
  
    <body>
        <form action="${pageContext.request.contextPath}/user/add.action" method="post">
            <table>
                <tr>
                    <td>ID:</td>
                    <td><input type="text" name="id"/></td>
                </tr>
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="name"/></td>
                </tr>
                <tr>
                    <td>薪水:</td>
                    <td><input type="text" name="sal"/></td>
                </tr>
                <tr>
                    <td>入職時間:</td>
                    <td><input type="text" name="hiredate"/></td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="提交"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>


UserAction.javaapp

@Controller
@RequestMapping(value="/user")
public class UserAction {
    
    @RequestMapping(value="/add")
    public String add(Model model, int id/*數值·整型*/,String name/*字符串*/,double sal/*數值·雙精度*/,Date hiredate) throws Exception{
        
        System.out.println(id + " - " + name + " - " + sal + " - " + hiredate);
        model.addAttribute("message", "添加成功!");
        return "/success.jsp";
    }
 
}

此時提交數據,會出現錯誤jsp

wKiom1fgmHKz-DoZAAGZufmooRg142.gif

仔細看一下錯誤:沒法將java.lang.String轉換成java.util.Date

wKioL1fgmNTQZVmYAAFuQt57osM076.png

使用@InitBind來解決字符串轉日期類型,添加以下方法(方法名能夠任意):

    @InitBinder
    private void xxxx(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }


完整的UserAction.java

package com.rk.action;

import java.text.SimpleDateFormat;
import java.util.Date;

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;

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @InitBinder
    private void xxxx(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="/add")
    public String add(Model model, int id/*數值·整型*/,String name/*字符串*/,double sal/*數值·雙精度*/,Date hiredate) throws Exception{
        
        System.out.println(id + " - " + name + " - " + sal + " - " + hiredate);
        model.addAttribute("message", "添加成功!");
        return "/success.jsp";
    }
 
}


wKiom1fgmcjT3MWKAADl_8Sq_pI447.gif


控制檯輸出:

1 - 小明 - 123.45 - Sun Oct 10 00:00:00 CST 2010


三、在方法中添加一個JavaBean參數接收各個表單數據


UserAction.java

package com.rk.action;

import java.text.SimpleDateFormat;
import java.util.Date;

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 com.rk.entity.User;

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @InitBinder
    private void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="/add")
    public String add(Model model, User user) throws Exception{
        model.addAttribute("message", "添加成功!");
        model.addAttribute("user", user);
        return "/success.jsp";
    }
 
}


User.java

package com.rk.entity;

import java.util.Date;

public class User {
    private Integer id;
    private String name;
    private Double sal;
    private Date hiredate;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
    public Date getHiredate() {
        return hiredate;
    }
    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", sal=" + sal
                + ", hiredate=" + hiredate + "]";
    }
    
}


success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta name="content-type" content="text/html; charset=UTF-8">
        <title>Success Page</title>
    </head>
  
    <body>
         ${message }<br>
        <table border="1" style="border-collapse: collapse;text-align: center;">
            <tr>
                <th width="200">屬性</th>
                <th width="300">值</th>
            </tr>
            <tr>
                <td>ID</td>
                <td>${user.id }</td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td>${user.name }</td>
            </tr>
            <tr>
                <td>薪水</td>
                <td>${user.sal }</td>
            </tr>
            <tr>
                <td>入職時間</td>
                <td>${user.hiredate}</td>
            </tr>
        </table>
    </body>
</html>


演示效果

wKiom1fgndrQhc5HAADxA362vYY472.gif


四、對User和Admin再進行一次封裝


假若有兩個JavaBean:User.java和Admin.java,它們擁有相同的屬性:id/name/sal/hiredate。

若是在UserAction.java的add方法中以下:

public String add(User user,Admin admin);

那麼,當瀏覽器表單提交數據時,會填充哪些一個JavaBean對象呢?

通過測試,發現user和admin對象都會被填充上。

User [id=3, name=小剛, sal=555.555, hiredate=Fri Dec 12 00:00:00 CST 2014]
Admin [id=3, name=小剛, sal=555.555, hiredate=Fri Dec 12 00:00:00 CST 2014]


爲了區分User和Admin的表單數據,須要在服務器和瀏覽器進行區分。


Bean.java

package com.rk.entity;

public class Bean {
    private User user;
    private Admin admin;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Admin getAdmin() {
        return admin;
    }
    public void setAdmin(Admin admin) {
        this.admin = admin;
    }
}


UserAction.java 

package com.rk.action;

import java.text.SimpleDateFormat;
import java.util.Date;

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 com.rk.entity.Admin;
import com.rk.entity.Bean;
import com.rk.entity.User;

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @InitBinder
    private void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="/add")
    public String add(Model model, Bean bean) throws Exception{
        model.addAttribute("message", "添加成功!");
        System.out.println(bean.getAdmin());
        System.out.println(bean.getUser());
        return "/success.jsp";
    }
 
}


index.jsp 頁面上進行區分

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta name="content-type" content="text/html; charset=UTF-8">
        <title>Index Page</title>
    </head>
  
    <body>
        <form action="${pageContext.request.contextPath}/user/add.action" method="post">
            <table>
                <tr>
                    <td>用戶ID:</td>
                    <td><input type="text" name="user.id"/></td>
                </tr>
                <tr>
                    <td>用戶姓名:</td>
                    <td><input type="text" name="user.name"/></td>
                </tr>
                <tr>
                    <td>用戶薪水:</td>
                    <td><input type="text" name="user.sal"/></td>
                </tr>
                <tr>
                    <td>用戶入職時間:</td>
                    <td><input type="text" name="user.hiredate"/></td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="提交"/>
                    </td>
                </tr>
            </table>
            <br/><br/>
            <table>
                <tr>
                    <td>管理員ID:</td>
                    <td><input type="text" name="admin.id"/></td>
                </tr>
                <tr>
                    <td>管理員姓名:</td>
                    <td><input type="text" name="admin.name"/></td>
                </tr>
                <tr>
                    <td>管理員薪水:</td>
                    <td><input type="text" name="admin.sal"/></td>
                </tr>
                <tr>
                    <td>管理員入職時間:</td>
                    <td><input type="text" name="admin.hiredate"/></td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="提交"/>
                    </td>
                </tr>
            </table>
              
        </form>
    </body>
</html>


五、接收數組參數

批量刪除

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta name="content-type" content="text/html; charset=UTF-8">
        <title>Index Page</title>
    </head>
  
    <body>
        <form action="${pageContext.request.contextPath}/user/add.action" method="post">
            <table>
                <tr><td> <input type="checkbox" name="ids" value="1"/>第一項 </td></tr>
                <tr><td> <input type="checkbox" name="ids" value="2"/>第二項 </td></tr>
                <tr><td> <input type="checkbox" name="ids" value="3"/>第三項 </td></tr>
                <tr><td> <input type="checkbox" name="ids" value="4"/>第四項 </td></tr>
                <tr><td> <input type="submit" value="刪除"/> </td></tr>
            </table>
        </form>
    </body>
</html>


UserAction.java

package com.rk.action;

import java.text.SimpleDateFormat;
import java.util.Date;

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;

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @InitBinder
    private void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="/add")
    public String add(Model model, int[] ids) throws Exception{
        String str = "須要批量刪除的是:";
        for(int id : ids){
            str += id+" ";
        }
        model.addAttribute("message", "批量刪除成功!" + str);
        return "/success.jsp";
    }
 
}


wKiom1fgqP6ya6rMAANy9O_sItg379.gif



六、接收List<JavaBean>參數

批量註冊用戶

UserAction.java

@Controller
@RequestMapping(value="/user")
publicclass UserAction {
    @RequestMapping(value="/addAll")
    public String addAll(Bean bean,Model model) throws Exception{
       for(User user :bean.getUserList()){
           System.out.println(user.getName()+":"+user.getGender());
       }
       model.addAttribute("message","批量增長用戶成功");
       return"/success.jsp";
    }
}

Bean.java

publicclass Bean {
    private List<User> userList = new ArrayList<User>();
    public Bean(){}
    public List<User> getUserList() {
       returnuserList;
    }
    publicvoid setUserList(List<User> userList) {
       this.userList = userList;
    }
}


index.jsp

    <form action="${pageContext.request.contextPath}/user/addAll.action"method="POST"> 
        
       姓名:<input type="text"name="userList[0].name"value="小明"/>
       性別:<input type="text"name="userList[0].gender"value="男"/>
       <hr/>
       
       姓名:<input type="text"name="userList[1].name"value="小剛"/>
       性別:<input type="text"name="userList[1].gender"value="男"/>
       <hr/>
 
       姓名:<input type="text"name="userList[2].name"value="小紅"/>
       性別:<input type="text"name="userList[2].gender"value="女"/>
       <hr/>
       
       <input type="submit" value="批量註冊"/>
       
    </form>
相關文章
相關標籤/搜索