当前位置: 移动技术网 > IT编程>开发语言>Java > SpringMVC处理Form表单实例

SpringMVC处理Form表单实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring mvc 表单处理例子下面的例子说明了如何编写一个简单的基于 web 的应用程序,它利用了使用 spring 的 web mvc 框架的 html 表单。

一 测试项目搭建

(1)新建java web项目,并引入几个springmvc项目所需要的jar包,项目结构和所需要的jar包如下:

①web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
     xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee
   http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
   
  <filter>
    <filter-name>characterencodingfilter</filter-name>
    <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterencodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

这里定义了springmvc拦截以.html结尾的url后缀并进行处理

②springmvc-servlet.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:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemalocation="http://www.springframework.org/schema/beans 
              http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-4.0.xsd
              http://www.springframework.org/schema/mvc 
              http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
  <context:component-scan base-package="cn.zifangsky.* *.controller" />
 
  <context:annotation-config /> <!-- 激活bean中定义的注解 -->
  <mvc:annotation-driven /> 
 
  <bean
    class="org.springframework.web.servlet.view.internalresourceviewresolver">
    <property name="prefix" value="/web-inf/pages/" />
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

在上面的配置文件中,<context:annotation-config />激活了bean中定义的一些注解,而<mvc:annotation-driven />则启动了springmvc的一些默认配置。在配置文件的最后则定义了逻辑视图到实际视图之间的对应关系,一句话解释就是:给返回的逻辑视图加上上面定义的路径前缀和后缀就是实际视图的真正路径了。

二 使用springmvc处理form表单

(1)在正式开始之前,先建立一个model和枚举类:

①实体类user:

package cn.zifangsky.model;
import java.time.localdate;
import org.springframework.format.annotation.datetimeformat;
public class user {
  private string name;
  private string password;
  private string job;
  @datetimeformat(pattern="yyyy-mm-dd")
  private localdate birthdate;
  private gender gender;
  private string country;
  private boolean smoking;
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
  public string getjob() {
    return job;
  }
  public void setjob(string job) {
    this.job = job;
  }
  public localdate getbirthdate() {
    return birthdate;
  }
  public void setbirthdate(localdate birthdate) {
    this.birthdate = birthdate;
  }
  public gender getgender() {
    return gender;
  }
  public void setgender(gender gender) {
    this.gender = gender;
  }
  public string getcountry() {
    return country;
  }
  public void setcountry(string country) {
    this.country = country;
  }
  public boolean issmoking() {
    return smoking;
  }
  public void setsmoking(boolean smoking) {
    this.smoking = smoking;
  } 
}

②表示“性别”的枚举类gender:

package cn.zifangsky.model; 
public enum gender {
  male,
  female;
}

下面将依照程序的执行流程来简单说明springmvc的form表单处理,分别是前台的form表单填写 –>controller处理 –>处理结果视图页面

(2)测试项目的首页与form表单页面:

①首页index.jsp:

<% response.sendredirect("form.html"); %>

可以看出,在这里我们的首页很简单,就是重定向到“form.html”,但是通过我们前面在web.xml中的配置,springmvc将会对这个请求转到一个具体的controller中进行处理,当然这里就是直接转到form表单页面。具体的controller里的处理逻辑下面再说

②form表单页面userform.jsp:

<%@ page language="java" contenttype="text/html; charset=utf-8"
  pageencoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>spring mvc form handling</title>
</head>
<body>
  <h2>用户注册</h2>
  <mvc:form modelattribute="user" action="result.html">
    <table>
      <tr>
        <td><mvc:label path="name">姓名:</mvc:label></td>
        <td><mvc:input path="name" /></td>
      </tr>
      <tr>
        <td><mvc:label path="password">密码:</mvc:label></td>
        <td><mvc:password path="password" /></td>
      </tr>
      <tr>
        <td><mvc:label path="job">工作:</mvc:label></td>
        <td><mvc:textarea path="job" /></td>
      </tr>
      <tr>
        <td><mvc:label path="birthdate">生日:</mvc:label></td>
        <td><mvc:input path="birthdate" /></td>
      </tr>
      <tr>
        <td><mvc:label path="gender">性别:</mvc:label></td>
        <td><mvc:radiobuttons path="gender" items="${genders}" /></td>
      </tr>
      <tr>
        <td><mvc:label path="country">居住地:</mvc:label></td>
        <td><mvc:select path="country" items="${countries}" /></td>
      </tr>
      <tr>
        <td><mvc:label path="smoking">吸烟吗:</mvc:label></td>
        <td><mvc:checkbox path="smoking" /></td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="submit" /></td>
      </tr>
    </table>
  </mvc:form>
</body>
</html>

由于我们把这个页面放在了web-inf目录下,因此是不能直接通过url对这个文件进行访问的,必须前面定义的“form.html”转到controller处理后显示这个视图页面,这样做的目的是防止一些私密的页面在未授权的情况下被其他人随意访问。在上面的文件中,需要注意的是:

  1. 为了简化form表单的写法,因此引入了springmvc的表单标签库,也就是文件顶部的:< uri=”http://www.springframework.org/tags/form” prefix=”mvc”%>
  2. modelattribute表示手动绑定了一个名为“user”的实体类,该值与controller中处理转到这个form表单时设置的那个model值相对应
  3. 表单中的path特性则是实现了对model的绑定,如:<mvc:input path=”name” />将该输入值设置成model类中的“name”属性。如果没有显式指定id和name属性,那么在页面中呈现的html input标签就会使用path特性来设置它的id和name属性

(3)业务逻辑处理的controller类usercontroller.java:

package cn.zifangsky.controller; 
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.servlet.modelandview;
import cn.zifangsky.model.gender;
import cn.zifangsky.model.user;
@controller
public class usercontroller {
  private static final string[] countries = {"china","japan","north korea","united states"};  
  @requestmapping(value="/form.html")
  public modelandview user(){
    modelandview modelandview = new modelandview("userform");
    modelandview.addobject("user", new user());
    modelandview.addobject("genders",gender.values());
    modelandview.addobject("countries", countries);    
    return modelandview;
  }
  @requestmapping(value="/result.html")
  public modelandview processuser(@modelattribute(value="user") user u){
    modelandview modelandview = new modelandview("userresult");
    modelandview.addobject("u",u);
     
    return modelandview;
  }  
}

可以看出,在上面定义了两个方法,它们的作用分别是针对“form.html”请求转到真实的form表单以及对form表单的处理。在对表单处理时通过@modelattribute注解接收了一个user类型的“u”,也就是前面填写的form表单,后面就是表单的显示因此不多说

(4)测试:
①表单填写:

②结果显示:

userresult.jsp页面:

<%@ page language="java" contenttype="text/html; charset=utf-8"
  pageencoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc"%>
<!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>spring mvc form handling</title>
</head>
<body>
  <h2>注册结果</h2>
  <table>
    <tr>
      <td>姓名:</td>
      <td>${u.name}</td>
    </tr>
    <tr>
      <td>密码:</td>
      <td>${u.password}</td>
    </tr>
    <tr>
      <td>工作:</td>
      <td>${u.job}</td>
    </tr>
    <tr>
      <td>生日:</td>
      <td>${u.birthdate}</td>
    </tr>
    <tr>
      <td>性别:</td>
      <td>${u.gender}</td>
    </tr>
    <tr>
      <td>居住地:</td>
      <td>${u.country}</td>
    </tr>
    <tr>
      <td>吸烟吗:</td>
      <td>${u.smoking}</td>
    </tr>
  </table>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网