Spring表单标签和modelAttribute
web.xml contextConfigLocation classpath*:/springMVC.xml org.springframework.web.context.ContextLoaderListener
springMVC.xml
<mvc:resources mapping="/resources/**" location="/"/> mvc:annotation-driven/ <context:component-scan base-package="com.test.controller" /> /WEB-INF/pages/ .jsp //创建一个实体Book类 public class Book { String name; String press; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPress() { return press; } public void setPress(String press) { this.press = press; }
}
@Controller
@RequestMapping("/welcome")
public class Hello {
//处理index.jsp表单提交
@RequestMapping(value="/show.do",method=RequestMethod.POST)
public String show(@ModelAttribute("book")Book book,Map<String,Object>model){
model.put("book",book);
return "hello";
}
//我们不能直接访问使用Spring表单标签的JSP页面,要先通过controller处理modelAttribute和表单标签的绑定才能访问
@RequestMapping(value="/new.do",method=RequestMethod.GET)
public String login(Map model){
Book book=new Book();
model.put("book",book);
return "index";
}
}
通过controller处理后,book里的属性自动和表单标签里的"path"绑定,简单来说,其实path就是起到了book.getXXX()的作用。
<span style="color:red">切记,path后跟着的名字要与对象的属性名字一样,否则绑定不了</span>
index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ page import="com.test.entity.*" %>
hello.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

