Springmvc controller和jsp頁面傳值對象類型問題和普通問題

一:JSP-->controllerjavascript

1.當jsp頁面傳遞的值是對象類型時候好比User.name User.age的user對象傳遞,須要如下操做html

jsp頁面提供對應標籤的value必須存在且合法,name屬性只能是對象的具體屬性名,不須要寫成對象.屬性名的形式,例如:java

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<script type="text/javascript"
    src="<%=request.getContextPath()%>/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#prev").click(
                function() {
                    $("#form0").attr("action",
                            "${pageContext.request.contextPath}/user/prev.do");
                    var currentPage = $("#currentPage").val() - 1;
                    $("#currentPage").val(currentPage);
                    alert($("#currentPage").val());
                    $("#form0").submit();
                })

        $("#next").click(
                function() {
                    $("#form0").attr("action",
                            "${pageContext.request.contextPath}/user/next.do");
                    $("#form0").submit();
                })
    })
</script>
</head>
<body>
    <form id="form0" method="POST">
        <table border="1">
            <thead>
                <tr>
                    <td width="60px">id</td>
                    <td width="120px">name</td>
                    <td width="60px">age</td>
                </tr>
            </thead>
            <tbody>
                <c:forEach var="user" items="${userList}" varStatus="status">
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.userName}</td>
                        <td>${user.age}</td>
                    </tr>
                </c:forEach>
                <tr>
                    <td><c:if test="${pageTableForm.currentPage > 1}">
                            <input id="prev" type="button" value="上一頁">
                        </c:if></td>
                    <td>當前<label>${pageTableForm.currentPage}</label>頁/共<label>${pageTableForm.pageCount}</label></td>
                    <td><c:if test="${pageTableForm.currentPage < pageTableForm.pageCount}">
                            <input id="next" type="button" value="下一頁">
                        </c:if></td>
                </tr>
                
            </tbody>
        </table>
        <input id="currentPage" type="text" name="currentPage" value="${pageTableForm.currentPage}">
    </form>
</body>
</html>

這裏的jquery

<input id="currentPage" type="text" name="currentPage" value="${pageTableForm.currentPage}"> 

我本身定義的一個封裝屬性的javabean對象PageTableForm,用來存放表單內容,我的習慣別較真兒web

package com.mi.form;

public class PageTableForm {

    private int currentPage;// 當前頁
    private int pageSize = 3;// 每頁記錄數
    private int beginIndex;// 開始位置
    private int endIndex;// 結束位置
    private int pageCount;// 共多少頁
    private int userCount;// 共多少條記錄
    ...
省略get set
}

此時的value="${pageTableForm.currentPage}"的值爲一個int類型且存在的數字,提交表單後到對應的requestmapping的方法中,代碼以下spring

package com.mi.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mi.entity.User;
import com.mi.form.PageTableForm;
import com.mi.service.impl.UserInfoServiceImpl;

@Controller
@RequestMapping("/user")
public class UserInfoCotroller {

    @Autowired
    private UserInfoServiceImpl userInfoServiceImpl;

    private PageTableForm pageTableForm;

    @RequestMapping("/init")
    public String init(){
        pageTableForm = new PageTableForm();
        return "redirect:/user/query.do";
    }
    
    @RequestMapping("/query")
    public String queryUserInfo(Model model,HttpServletRequest request) {
        pageTableForm = getOperation();
        List<User> userList = userInfoServiceImpl.queryUserInfo(pageTableForm.getBeginIndex(), pageTableForm.getEndIndex());
        model.addAttribute("userList", userList);
        model.addAttribute("pageTableForm", pageTableForm);
        return "userInfo";
    }

    public PageTableForm getOperation() {
        if (pageTableForm.getCurrentPage() == 0)
            pageTableForm.setCurrentPage(1);

        pageTableForm.setUserCount(getCount());
        if (pageTableForm.getUserCount() % 3 == 0) {
            pageTableForm.setPageCount(pageTableForm.getUserCount() / pageTableForm.getPageSize());
        } else {
            pageTableForm.setPageCount(pageTableForm.getUserCount() / pageTableForm.getPageSize() + 1);
        }
        
        pageTableForm.setBeginIndex(pageTableForm.getCurrentPage() * 3 - 3);
        pageTableForm.setEndIndex(pageTableForm.getCurrentPage() * 3);

        return pageTableForm;
    }

    @RequestMapping("/prev")
    public String pagePrev(Model model,HttpServletRequest request,PageTableForm pageTableForm) {
        System.out.println(request.getParameter("currentPage"));
        System.out.println(pageTableForm.getCurrentPage());
        int currentPage = pageTableForm.getCurrentPage()-1;
        pageTableForm.setCurrentPage(currentPage);
        return "redirect:/user/query.do"; }
    
    @RequestMapping("/next")
    public String pageNext(Model model) {
        int currentPage = pageTableForm.getCurrentPage()+1;
        pageTableForm.setCurrentPage(currentPage);
        return "redirect:/user/query.do";
    }
    
    public int getCount() {
        return userInfoServiceImpl.getCount();
    }

    public UserInfoServiceImpl getUserInfoServiceImpl() {
        return userInfoServiceImpl;
    }

    public void setUserInfoServiceImpl(UserInfoServiceImpl userInfoServiceImpl) {
        this.userInfoServiceImpl = userInfoServiceImpl;
    }

    public PageTableForm getPageTableForm() {
        return pageTableForm;
    }

    public void setPageTableForm(PageTableForm pageTableForm) {
        this.pageTableForm = pageTableForm;
    }

}

紅色部分就是提交的方法,能夠看出在方法參數中要聲明一下對象,這裏我爲了是實驗比較數據傳到後臺是否正確,因此使用了2中方法--request.getParamter()和直接使用對象.get...方法,得出結果以下所示,app

我點擊上一頁,頁面alert一個跳轉頁面的頁碼,如今是從第二頁翻到第一頁,因此是1,這樣咱們後臺2次正確的狀況應該也都是1(日語操做系統,別在乎這些,不是亂碼)jsp

多點了一次,別在乎這些,重點是後臺獲取的數據就是前臺咱們想要的post

 2.當jsp->後臺是普通數據的時候,實際項目中這種狀況很少,可是仍是總結一下ui

暫時掛起,關於這些我想等到實際用到時再列,上1中已經列了一種方法,另外就是利用註解去值

頁面以下

<form action="login2" method="post">
          用戶:<input type="text" name="name"><br><br>
          密碼:<input type="text" name="password"><br><br>
        <input type="submit" value="肯定">
</form>

普通數據(非對象)的數據有2種方法傳遞到後臺,request獲取+註解版的request

1):request獲取

/**
     * 使用HttpServletRequest獲取
     */
    @RequestMapping("/login1")
    public String login1(HttpServletRequest request,Model model){
        model.addAttribute("name", request.getParameter("name"));
        model.addAttribute("password", request.getParameter("password"));
        return "success";
    }

2):註解版的request

 /**
     * spring自動將表單參數注入到方法參數,參數值和頁面name屬性一致時能夠省去@RequestParam註解
     */
    @RequestMapping("/login2")
    public String login2(@RequestParam("name") String name, String password,Model model){
        model.addAttribute("name", name);
        model.addAttribute("password", password);
        return "success";
    }

實體類User再也不列出了

二:controller-->JSP

有2中辦法(實際更多,不過存在重複嫌疑列舉經常使用的就好),用model+用map

1):利用model對象添加數據到屬性中,頁面可使用EL表達式獲取

    @RequestMapping("/init")
    public String init(){
        pageTableForm = new PageTableForm();
        return "redirect:/user/query.do";
    }
    
    @RequestMapping("/query")
    public String queryUserInfo(Model model,HttpServletRequest request) {
        pageTableForm = getOperation();
        List<User> userList = userInfoServiceImpl.queryUserInfo(pageTableForm.getBeginIndex(), pageTableForm.getEndIndex());
        model.addAttribute("userList", userList);
        model.addAttribute("pageTableForm", pageTableForm);
        return "userInfo";
    }

JSP:

<form id="form0" method="POST">
        <table border="1">
            <thead>
                <tr>
                    <td width="60px">id</td>
                    <td width="120px">name</td>
                    <td width="60px">age</td>
                </tr>
            </thead>
            <tbody>
                <c:forEach var="user" items="${userList}" varStatus="status">
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.userName}</td>
                        <td>${user.age}</td>
                    </tr>
                </c:forEach>
                <tr>
                    <td><c:if test="${pageTableForm.currentPage > 1}">
                            <input id="prev" type="button" value="上一頁">
                        </c:if></td>
                    <td>當前<label>${pageTableForm.currentPage}</label>頁/共<label>${pageTableForm.pageCount}</label></td>
                    <td><c:if test="${pageTableForm.currentPage < pageTableForm.pageCount}">
                            <input id="next" type="button" value="下一頁">
                        </c:if></td>
                </tr>
                
            </tbody>
        </table>
        <input id="currentPage" type="text" name="currentPage" value="${pageTableForm.currentPage}">
    </form>

2):使用map方式設值,JSP同上再也不列出

@RequestMapping("/login4")
    public String login4(User user, Map<String, Object> map){
        map.put("name", user.getName());
        map.put("password", user.getPassword());
        return "success";
    }
相關文章
相關標籤/搜索