spingmvc的form表单标签使用实例。
一,项目结构
二,所需jar包
commons-logging.jar
spring-aop-4.1.8.RELEASE.jar
spring-beans-4.1.8.RELEASE.jar
spring-context-4.1.8.RELEASE.jar
spring-core-4.1.8.RELEASE.jar
spring-expression-4.1.8.RELEASE.jar
spring-web-4.1.8.RELEASE.jar
spring-webmvc-4.1.8.RELEASE.jar
以下两个为jstl标签库所需
standard.jar
jstl.jar
三,web.xml配置springmvc的DispatcherServlet
web.xml中主要进行DispatcherServlet配置和初始化springmvc.xml配置文件。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4"> <!-- 配置DisptatcherServlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置DispatcherServlet的初始化参数 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- web应用被加载的时候创建servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
四,springmvc.xml配置
配置扫描包文件,视图解析器等等。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.lanhuigu.springmvc"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置前缀 --> <property name="prefix" value="/WEB-INF/views/"/> <!-- 配置后缀 --> <property name="suffix" value=".jsp"/> </bean> <!-- 自定义视图解析器:BeanNameViewResolver使用视图的名字解析视图 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <!-- 设置该自定义视图解析器BeanNameViewResolver与 InternalResourceViewResolver视图解析器的优先级值, InternalResourceViewResolver的order默认值为Integer的最大值,BeanNameViewResolver以下设置 order为100,order值越小,视图解析器的优先级越高。 该配置文件中自定视图解析器BeanNameViewResolver的优先级高于InternalResourceViewResolver, 每次先使用BeanNameViewResolver解析视图,如果实现不了需求,自动调用InternalResourceViewResolver 解析视图。 --> <property name="order"> <value>100</value> </property> </bean> <!-- 配置直接转发的页面 --> <mvc:view-controller path="/success" view-name="success"/> <!-- 解决mvc:view-controller配置后RequestMapping映射地址报404的问题 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
五,实体类User和Address
User.java
package com.lanhuigu.springmvc.entities; public class User { private String username; private String password; private Integer gender; private Address address;//级联类 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } /** * 重写toString()方法 */ @Override public String toString() { return "User [username=" + username + ", password=" + password + ", gender=" + gender + ", address=" + address + "]"; } }
Address.java
package com.lanhuigu.springmvc.entities; public class Address { private Integer id; private String province; private String city; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
六,Restful风格action,文件在action包下
该控制类中有三个方法,数据均为模拟:
(1)queryList查询用户列表
(2)editInput初始添加用户的页面
(3)add添加用户的方法,这里没有连接数据库,主要目的是用于查看form表单提交的数据
package com.lanhuigu.springmvc.action; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.lanhuigu.springmvc.entities.Address; import com.lanhuigu.springmvc.entities.User; @RequestMapping("/testRestful") @Controller public class TestRestfulAction { /** * 查询列表数据 * @param map * @return */ @RequestMapping("/list") public String queryList(Map<String, Object> map) { List<User> lists = new ArrayList<User>(); User user = new User(); user.setUsername("ONE"); user.setPassword("111111"); Address address = new Address(); address.setProvince("aaaaaa"); address.setCity("bbbbbb"); user.setAddress(address); lists.add(user); map.put("users", lists); return "list"; } /** * 初始化编辑页面 * @param map * @return */ @RequestMapping(value="/input",method=RequestMethod.GET) public String editInput(Map<String, Object> map) { map.put("user", new User()); return "input"; } /** * 添加用户 * @param user * @return */ @RequestMapping(value="/addUser",method=RequestMethod.POST) public String add(User user) { System.out.println( "username:"+user.getUsername() + " " + "password:"+user.getPassword() + " " + "gender:"+user.getGender() + " " + "province:"+user.getAddress().getProvince() + " " + "city:"+user.getAddress().getCity()); return "redirect:/testRestful/list"; } }
七,list.jsp页面,该页面位于WEB-INF下的views下
该页面为列表展示页面,页面上有个add user添加用户的超链接,用于初始化用户添加页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>spring MVC实例初体验</title> </head> <body> <table border="1" cellpadding="10" cellspacing="0"> <tr> <th>username</th> <th>password</th> <th>province</th> <th>city</th> </tr> <c:forEach items="${users }" var="user"> <tr> <td>${user.username }</td> <td>${user.password }</td> <td>${user.address.province }</td> <td>${user.address.city }</td> </tr> </c:forEach> </table> <div><a href="input">ADD USER</a></div> </body> </html>
input.jsp初始化编辑页面,位于views下,位置同list.jsp,内容如下:
添加用户的页面,该页面的map代码在实际中均可通过数据库查询封装,或模型数据定义等实现,这里直接通过Java代码在jsp页面完成。
该页通过post方式提交到addUser这个action地址,modelAttribute为表单属性,它会自动的绑定来自Model中的一个属性值到当前form对应的实体对象,
默认是command属性,找不到command时会报错,我们手动封装一个空的user替代。spring表单提交方式除了get,post外还有delete,put等。
<%@page import="com.lanhuigu.springmvc.entities.Address"%> <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>spring MVC实例初体验</title> </head> <body> <!-- action属性的addUser为表单提交路径,method的post为提交方式 , modelAttribute为实体类,默认为command,如果找不到command会报错, 这里手动修改为user,表单初始化的方法中设置map.put("user", new User()); --> <form:form action="addUser" method="POST" modelAttribute="user"> <!-- path属性对应html表单标签的name属性 --> USERNAME:<form:input path="username" maxlength="20"/><br> PASSWORD:<form:password path="password"/><br> <% Map<Integer,String> genders = new HashMap<Integer,String>(); genders.put(1, "男"); genders.put(0, "女"); request.setAttribute("genders", genders); %> GENDER:<form:radiobuttons path="gender" items="${genders }"/><br> <% Map<String,String> provinces = new HashMap<String,String>(); provinces.put("1", "北京"); provinces.put("2", "天津"); request.setAttribute("provinces", provinces); %> <!-- path后面的address.province为级联属性 --> PROVINCE:<form:select path="address.province" items="${provinces }" ></form:select><br> <% Map<String,String> cities = new HashMap<String,String>(); cities.put("1", "东城"); cities.put("2", "西城"); request.setAttribute("cities", cities); %> CITY:<form:select path="address.city" items="${cities }"></form:select><br> <input type="submit" value="提交"> </form:form> </body> </html>
八,访问地址测试
测试逻辑:通过第一地址到用户列表页面,点击add user都添加用户初始化页面,完成页面填写提交表单,
控制台查看或debugger追踪查看提交效果,体验spring的form表单在springmvc中实际应用。
http://localhost:9000/SpringMVC/testRestful/list到列表展示页面:
点击ADD USER到添加用户表单页面:
提交表单,查看控制台,或在input方法下debugger看看user是否获取表单页面提交的值
九,控制台输出结果
十,总结分析
对form表单列了个图:
对于以上这标签的用法类似html中的表单使用,个别标签的属性有区别,不过都是顾名思义。