在spring mvc中发布持久数据

时间:2017-05-30 16:26:11

标签: spring model-view-controller

我开始在spring mvc做一个项目,并且在从jsp到控制器获取类型时我有些疑惑。

目前我有(jsp):

<form method="POST" action="pb.html">           
<h2>Description: <textarea style="resize:none;" name="description" form="usrform" maxlength="47"></textarea><h2> 
<br>          
Number: <input type="number" min="1" value="1" name="number" />
<input type="submit" value="Create Volume" />
</form>

我的控制器:

package book;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BookController {

@Autowired
private BookDao bookDAO;

@RequestMapping(value="/book")
public ModelAndView BOOKSTORE(HttpServletRequest request) {
String description = request.getParameter("description");
String number = request.getParameter("number");

if(description != null && number != null)    
bookDAO.persist(new Book(description, Integer.parseInt(number)));

// Prepare the result view (book.jsp):
return new ModelAndView("book.jsp", "bookDao", bookDAO);
}
}

似乎我的数据没有被保留,因为控制器无法将textarea转换为字符串,并且由于某种原因它无法转换数字。

有些网站说要在jsp中使用以下内容:

<h2>Description: <input type="text" name="description"></input><h2> 
<br>          
Number: <input type="text" name="number" />

但这对我没有意义,因为我希望用户查看完整的描述(所以我需要一个文本区域),我只希望用户在数字字段上键入数字,这样就可以了更有意义的是使用tye数。

任何人都可以帮助我吗?

此致

2 个答案:

答案 0 :(得分:0)

尝试使用此代码

@RequestMapping(value="/book")
public ModelAndView BOOKSTORE(HttpServletRequest request, ModelAndView  mav) {
String description = request.getParameter("description");
String number = request.getParameter("number");

Book book=new Book();
if(description != null && number != null){
     book=new Book(description, Integer.parseInt(number));
     bookDAO.persist(book);
}

mav.setViewName("book");
mav.addObject("book", book);
return mav;
}
}

答案 1 :(得分:0)

问题解决了,

我必须将数字作为字符串传递给java类,而在java类中我做了null验证:

控制器:

@RequestMapping(value="/book")
public ModelAndView BOOKSTORE(HttpServletRequest request) {
String description = request.getParameter("description");
String number = request.getParameter("number");

if(description != null)    
bookDAO.persist(new Book(description, number));

// Prepare the result view (book.jsp):
return new ModelAndView("book.jsp", "bookDao", bookDAO);
}

爪哇:

/**
 *
 * @param description
 * @param number
 */
public Book(String description, String number){
    this.pbi_description = description;

    if(number!= null)
        this.number=  Integer.parseInt(number);  
}

但是,应该可以在控制器中进行此验证。