Springmvc 简明教程
Spring - MVC Framework Overview
Spring Web MVC框架提供了一个模型-视图-控制器架构和可以用来开发灵活且松散耦合的web应用程序的准备组件。MVC模式导致应用程序的不同方面(输入逻辑、业务逻辑和界面逻辑)分离,同时在这些元素之间提供松散耦合。
The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
-
The Model encapsulates the application data and in general, they will consist of POJO.
-
The View is responsible for rendering the model data and in general, it generates HTML output that the client’s browser can interpret.
-
The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering.
The DispatcherServlet
Spring Web模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet设计的,它处理所有的HTTP请求和响应。Spring Web MVC DispatcherServlet的请求处理工作流显示在下图中。
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration.
以下为响应发送到 DispatcherServlet 的入站 HTTP 请求的事件序列 -
Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −
-
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
-
The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
-
The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.
-
Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers.
所有以上提到的组件,比如HandlerMapping、Controller和ViewResolver都是 WebApplicationContext 的一部分,它扩展了平实的 ApplicationContext ,其中有一些web应用程序所必需的额外功能。
All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications.
Required Configuration
我们需要映射DispatcherServlet需要处理的请求,通过在 web.xml 文件中使用URL映射来实现。以下示例显示了 HelloWeb DispatcherServlet的声明和映射——
We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet −
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
web.xml 文件将被保留在你的web应用程序的 WebContent/WEB-INF 目录中。初始化DispatcherServlet时,框架将尝试从一个名为 [servlet-name]-servlet.xml 的文件中加载应用程序上下文,该文件位于应用程序的WebContent/WEB-INF目录中。在本例中,我们的文件将是 HelloWeb-servlet.xml 。
The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application’s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml.
接下来, <servlet-mapping> 标签指出了哪些URL将由哪个DispatcherServlet处理。在这里,所有以.jsp结尾的HTTP请求都将由 HelloWeb DispatcherServlet处理。
Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.
如果你不想使用默认的文件名 [servlet-name]-servlet.xml 和默认位置WebContent/WEB-INF,你可以通过在你的web.xml文件中添加 ContextLoaderListener servlet监听器,来自定义这个文件名和位置,如下所示——
If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows −
<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
现在,让我们查看放置在你的web应用程序的WebContent/WEB-INF目录中的 HelloWeb-servlet.xml 文件的所需配置。
Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application’s WebContent/WEB-INF directory.
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
以下是有关 HelloWeb-servlet.xml 文件的部分重点:
Following are some important points about HelloWeb-servlet.xml file −
-
The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
-
The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc.
-
The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp.
现在让我们了解如何创建实际组件,即控制器、模型和视图。
Let us now understand how to create the actual components i.e., Controller, Model and View.
Defining a Controller
DispatcherServlet 将请求委托给 controller 以执行特定于该请求的功能。 @Controller 注解表明特定的类扮演 controller 的角色。 @RequestMapping 注解用于将 URL 映射到整个类或特定的处理方法。
The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
@Controller 注解将类定义为 Spring MVC 控制器。在此,第一个 @RequestMapping 用法表示该控制器上的所有处理方法都与 /hello 路径相关。
The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path.
下一个注解 @RequestMapping (method = RequestMethod.GET) 用于将 printHello() 方法声明为控制器的默认服务方法来处理 HTTP GET 请求。我们可以在同一 URL 上定义另一个方法来处理任何 POST 请求。
The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller’s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL.
我们还可以用另一种形式编写上述控制器,其中我们可以按照如下方式在 @RequestMapping 中添加其他属性:
We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows −
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
value 属性指示处理程序方法映射到的 URL, method 属性定义了处理 HTTP GET 请求的服务方法。
The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request.
以下是有关上述控制器定义的部分重点:
Following are some important points to be noted regarding the controller defined above −
-
You will define the required business logic inside a service method. You can call another method inside this method as per the requirement.
-
Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute "message".
-
A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as the logical view name.
Creating JSP Views
Spring MVC 支持许多不同展现技术的视图类型。这些包括 JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom 和 RSS 数据源、 JasperReports 等等。然而,最常见的是使用 JSTL 编写的 JSP 模板。所以,让我们在 /WEB-INF/hello/hello.jsp 中编写一个简单的问候视图:
Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. However, the most common ones are the JSP templates written with JSTL. So, let us write a simple hello view in /WEB-INF/hello/hello.jsp −
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
此处, ${message} 是我们在控制器中设置的属性。您可以在视图中显示多个属性。
Here ${message} Here is the attribute, which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view.
Spring MVC - Environment Setup
本章将在您开始使用 Spring 框架时,指导您如何准备开发环境。它还将教您在设置 Spring 框架之前如何在您的机器上设置 JDK、Maven 和 Eclipse −
This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework −
Setup Java Development Kit (JDK)
你可以从 Oracle 的 Java 站点下载 SDK 的最新版本 − Java SE Downloads. 你在下载文件中可以找到安装 JDK 的说明,按照给定的说明进行安装和配置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。
You can download the latest version of SDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
如果您运行的是 Windows 且在 C:\jdk-11.0.11 中安装了 JDK,那么您将不得不把以下代码行放入您的 C:\autoexec.bat 文件中。
If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk-11.0.11;%PATH%
set JAVA_HOME=C:\jdk-11.0.11
或者,在 Windows NT/2000/XP 中,你必须右键单击我的电脑,选择属性 → 高级 → 环境变量。然后,你将不得不更新 PATH 值并单击确定按钮。
Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.
在 Unix(Solaris、Linux 等)中,如果 SDK 安装在 /usr/local/jdk-11.0.11 且您使用 C shell,那么您将不得不把以下代码行放入您的 .cshrc 文件中。
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.
setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11
或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.
Setup Eclipse IDE
本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。
All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.
要安装 Eclipse IDE,请从 www.eclipse.org/downloads 下载最新的 Eclipse 二进制文件。下载安装文件后,将二进制分发包解压到方便的位置。例如,在 Windows 上的 C:\eclipse 中,或 Linux/Unix 上的 /usr/local/eclipse 中,最后相应地设置 PATH 变量。
To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe
Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
成功启动后,如果一切正常,它应该显示以下结果 −
After a successful startup, if everything is fine then it should display the following result −
Install Apache Common Logging API
你可以从 https://commons.apache.org/logging/ 下载最新版的 Apache Commons Logging API。下载安装程序后,将二进制发行版解压缩到一个方便的位置。
You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you have downloaded the installation, unpack the binary distribution into a convenient location.
例如 - Windows 上的 C:\commons-logging-1.1.1,或 Linux/Unix 上的 /usr/local/commons-logging1.1.1。此目录将包含以下 jar 文件和其他支持文档等。
For example – C:\commons-logging-1.1.1 on windows, or /usr/local/commons-logging1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc.
确保在此目录上正确设置你的 CLASSPATH 变量,否则在运行你的应用程序时你会遇到问题。
Make sure you set your CLASSPATH variable on this directory properly, otherwise you will face problem while running your application.
Setup Spring Framework Libraries
现在,如果一切正常,那么我们可以继续设置 Spring Framework。以下是在机器上下载和安装框架的步骤。
Now if everything is fine, then we can proceed to setup the Spring Framework. Following are the steps to download and install the framework on the machine.
-
Make a choice whether you want to install Spring on Windows or UNIX and then proceed to the next step to download .zip file for windows and .tz file for Unix.
-
Download the latest version of Spring framework binaries from link: https://repo.spring.io/release/org/springframework/spring.
-
We have downloaded the spring-5.3.14-dist.zip on the Windows Machine and when we unzip the downloaded file, it will give out the directory structure inside – E:\spring as follows.
你将在此目录中找到所有 Spring 库 E:\spring\libs 。确保在此目录上正确设置你的 CLASSPATH 变量;否则,我们在运行应用程序时会遇到问题。如果我们使用 Eclipse,则不需要设置 CLASSPATH,因为所有设置都将通过 Eclipse 完成。
You will find all the Spring libraries in the directory E:\spring\libs. Make sure you set your CLASSPATH variable on this directory properly; otherwise, we will face a problem while running the application. If we use Eclipse, then it is not required to set the CLASSPATH because all the setting will be done through Eclipse.
完成最后一步后,您可以准备进行第一个 Spring 示例了,您将在下一章中看到。
Once you are done with this last step, you are ready to proceed for your first Spring Example, which you will see in the next chapter.
Spring MVC - Hello World Example
以下示例展示了如何使用 Spring MVC 框架编写简单基于 web 的 Hello World 应用程序。首先,我们准备一个可用的 Eclipse IDE,然后遵循以下步骤使用 Spring Web 框架开发一个动态 Web 应用程序。
The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. |
2 |
Drag and drop the following Spring and other libraries into the folder WebContent/WEB-INF/lib.. |
3 |
Create a Java class HelloController under the com.tutorialspoint package. |
4 |
Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. |
5 |
Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder. |
6 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
web.xml
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
以下是包含在 Web 应用程序中的 Spring 及其他库的列表。我们可以直接将这些文件拖放到 WebContent/WEB-INF/lib 文件夹中。
Following is the list of Spring and other libraries to be included in the web application. We can just drag these files and drop them in – WebContent/WEB-INF/lib folder.
-
servlet-api-x.y.z.jar
-
commons-logging-x.y.z.jar
-
spring-aop-x.y.z.jar
-
spring-beans-x.y.z.jar
-
spring-context-x.y.z.jar
-
spring-core-x.y.z.jar
-
spring-expression-x.y.z.jar
-
spring-webmvc-x.y.z.jar
-
spring-web-x.y.z.jar
完成后创建源代码和配置文件,导出你的应用程序。右键单击你的应用程序,使用 Export → WAR File 选项并保存 HelloWeb.war 文件到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。然后,尝试访问 URL − http://localhost:8080/HelloWeb/hello 。如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try to access the URL − http://localhost:8080/HelloWeb/hello. If everything is fine with the Spring Web Application, we will see the following screen.
你应该注意,在给定的 URL 中, HelloWeb 是应用程序名称,hello 是虚拟子文件夹,我们使用 @RequestMapping("/hello") 在控制器中已经提到了该文件夹。你可以使用 @RequestMapping("/") 将你的 URL 直接映射到根目录,在这种情况下,你可以使用缩写 URL http://localhost:8080/HelloWeb/ 访问同一个页面,但建议在不同的文件夹下有不同的功能。
You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping("/hello"). You can use direct root while mapping your URL using @RequestMapping("/"), in this case you can access the same page using short URL http://localhost:8080/HelloWeb/, but it is advised to have different functionalities under different folders.
Spring MVC - Form Handling Example
以下示例展示了如何使用 Spring MVC 框架编写简单基于 web 的 Hello World 应用程序。首先,我们准备一个可用的 Eclipse IDE,然后遵循以下步骤使用 Spring Web 框架开发一个动态 Web 应用程序。
The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes Student, StudentController under the com.tutorialspoint package. |
3 |
Create view files student.jsp, result.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
这里,在第一个 service 方法 student() 中,我们已经在具有名称“command”的 ModelAndView 对象中传递了一个空白的 Student 对象。我们之所以这么做,是因为如果我们在 JSP 文件中使用 <form:form> 标记,Spring 框架便希望有一个名为 “command” 的对象。因此,在调用 student() 方法时,它将返回 student.jsp 视图。
Here, the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name "command". This is done because the spring framework expects an object with name "command", if we use <form:form> tags in the JSP file. So, when the student() method is called, it returns student.jsp view.
第二个 service 方法 addStudent() 将针对 HelloWeb/addStudent 网址上的 POST 方法进行调用。您将基于已提交信息准备您的模型对象。最后,将从 service 方法返回一个 “result” 视图,这将导致呈现 result.jsp。
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering result.jsp.
student.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
在完成源文件和配置文件的创建后,导出您的应用程序。右键单击您的应用程序,使用导出 → WAR 文件选项,然后将 SpringWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once we are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the SpringWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保可以使用标准浏览器访问 webapps 文件夹中的其他网页。现在,尝试一个网址 – [role="bare"] [role="bare"]http://localhost:8080/SpringWeb/student ,如果 Spring Web 应用程序一切正常,您应该会看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Now, try a URL– [role="bare"]http://localhost:8080/SpringWeb/student and you should see the following screen if everything is fine with the Spring Web Application.
在提交所需的信息后,单击提交按钮以提交表单。如果 Spring Web 应用程序一切正常,你应该会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - Page Redirection Example
以下示例演示了如何编写一个简单的基于 web 的应用程序,该应用程序使用重定向将一个 http 请求传输到另一个页面。首先,让我们准备一个可用的 Eclipse IDE,并考虑按照以下步骤使用 Spring Web Framework 开发一个基于动态表单的 Web 应用程序 −
The following example shows how to write a simple web based application, which makes use of redirect to transfer an http request to another page. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework −
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class WebController under the com.tutorialspoint package. |
3 |
Create view files index.jsp, final.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
WebController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
@RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
return "final";
}
}
以下是 Spring 视图文件中的内容 index.jsp 。这将是一个着陆页,此页面将向 access-redirect 服务方法发送一个请求,该方法将此请求重定向到另一个服务方法,最后将显示一个 final.jsp 页面。
Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to the access-redirect service method, which will redirect this request to another service method and finally a *final.jsp*page will be displayed.
index.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<form:form method = "GET" action = "/HelloWeb/redirect">
<table>
<tr>
<td>
<input type = "submit" value = "Redirect Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
final.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>
一旦你完成了创建源文件和配置文件,导出你的应用程序。右键单击你的应用程序,使用“导出 → WAR 文件”选项并将你的 HelloWeb.war 文件保存到 Tomcat 的 Webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动你的 Tomcat 服务器并确保你能够使用标准浏览器访问 Webapps 文件夹中的其他网页。尝试一个 URL -http://localhost:8080/HelloWeb/index,如果 Spring Web 应用程序一切正常,你应该会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/index and you should see the following screen if everything is fine with the Spring Web Application.
现在单击“重定向页面”按钮以提交表单并转到最终重定向页面。如果我们的 Spring Web 应用程序一切正常,我们应该会看到以下屏幕 −
Now click on the "Redirect Page" button to submit the form and to get to the final redirected page. We should see the following screen, if everything is fine with our Spring Web Application −
Spring MVC - Static Pages Example
以下示例展示了如何使用 Spring MVC 框架编写一个简单的基于 Web 的应用程序,它可以通过 <mvc:resources> 标记访问静态页面和动态页面。
The following example shows how to write a simple web based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of a <mvc:resources> tag.
首先,让我们有一个正在工作的 Eclipse IDE,并遵循以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class WebController under the com.tutorialspoint package. |
3 |
Create a static file final.htm under jsp sub-folder. |
4 |
Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. |
5 |
The final step is to create the content of the source and configuration files and export the application, which is explained below. |
WebController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String redirect() {
return "redirect:/pages/final.htm";
}
}
HelloWeb-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-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<mvc:resources mapping = "/pages/**" location = "/WEB-INF/pages/" />
<mvc:annotation-driven/>
</beans>
此处, <mvc:resources…./> 标记用于映射静态页面。mapping 属性必须是一个 Ant pattern ,它指定 http 请求的 URL 模式。location 属性必须指定一个或多个有效的资源目录位置,其中包含静态页面,包括图像、样式表、JavaScript 和其他静态内容。可以使用逗号分隔的值列表指定多个资源位置。
Here, the <mvc:resources…./> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-separated list of values.
以下是 Spring 视图文件 WEB-INF/jsp/index.jsp 的内容。这将是一个登陆页面;此页面将发送一个请求来访问 staticPage service method ,该请求将重定向到 WEB-INF/pages 文件夹中可用的静态页面。
Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access the staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder.
index.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Landing Page</title>
</head>
<body>
<h2>Spring Landing Pag</h2>
<p>Click below button to get a simple HTML page</p>
<form:form method = "GET" action = "/HelloWeb/staticPage">
<table>
<tr>
<td>
<input type = "submit" value = "Get HTML Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
final.htm
<html>
<head>
<title>Spring Static Page</title>
</head>
<body>
<h2>A simple HTML page</h2>
</body>
</html>
一旦你完成了创建源文件和配置文件,导出你的应用程序。右键单击你的应用程序,使用“导出 → WAR 文件”选项并将你的 HelloWeb.war 文件保存到 Tomcat 的 Webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。然后尝试访问该 URL – [role="bare"] [role="bare"]http://localhost:8080/HelloWeb/index 。如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now try to access the URL – [role="bare"]http://localhost:8080/HelloWeb/index. If everything is fine with the Spring Web Application, we will see the following screen.
单击“获取 HTML 页面”按钮以访问 staticPage 服务方法中提到的静态页面。如果你的 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Click on "Get HTML Page" button to access a static page mentioned in the staticPage service method. If everything is fine with your Spring Web Application, we will see the following screen.
Spring MVC - Text Box Example
以下示例演示了如何在表单中使用文本框,使用 Spring Web MVC 框架。首先,让我们准备一个能正常工作的 Eclipse IDE,然后按照以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序−
The following example shows how to use Text boxes in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework −
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World Example chapter. |
2 |
Create a Java classes Student, StudentController under the com.tutorialspoint package. |
3 |
Create a view files student.jsp, result.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
这里第一个服务方法 student() ,我们在 ModelAndView 对象中传递了一个空白 Student 对象,名称为“command”,因为如果您在 JSP 文件中使用 <form:form> 标记,Spring 框架需要名称为“command”的对象。所以当调用 student() 方法时,它会返回 student.jsp view 。
Here, the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the student() method is called it returns student.jsp view.
第二个服务方法 addStudent() 将针对 HelloWeb/addStudent URL 中的 POST 方法调用。您将根据已提交的信息准备模型对象。最后,将从服务方法返回一个“result”视图,此视图将导致呈现 result.jsp。
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering result.jsp
student.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
这里我们使用 <form:input /> 标记来呈现 HTML 文本框。例如 −
Here, we are using <form:input /> tag to render an HTML text box. For example −
<form:input path = "name" />
它会呈现以下 HTML 内容。
It will render following HTML content.
<input id = "name" name = "name" type = "text" value = ""/>
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
一旦创建完源文件和配置文件,导出您的应用程序。右键单击应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once we are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保您能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试一个 URL – http://localhost:8080/HelloWeb/student ,如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/student and we will see the following screen if everything is fine with the Spring Web Application.
在提交所需信息后,单击“submit”按钮提交表单。如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We should see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Password Example
以下示例介绍了如何在表单中使用密码以及 Spring Web MVC 框架。首先,让我们有一个正在工作的 Eclipse IDE,并遵循以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example describes how to use Password in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
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;
}
}
UserController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
return "users";
}
}
这里,第一个服务方法 user() ,我们在 ModelAndView 对象中传递了一个空用户对象,名称为“command”,因为 Spring 框架期望一个名为“command”的对象,如果你在 JSP 文件中使用 <form:form> 标记。因此,当调用 user() 方法时,它返回 user.jsp 视图。
Here, the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called it returns user.jsp view.
第二个服务方法 addUser() 将针对 HelloWeb/addUser URL 上的 POST 方法进行调用。你将根据提交的信息准备模型对象。最后,从服务方法返回“users”视图,这将导致呈现 users.jsp。
The Second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在此处,我们使用 <form:password /> 标记来呈现一个 HTML 密码框。例如 −
Here, we are using the <form:password /> tag to render an HTML password box. For example −
<form:password path = "password" />
它将呈现以下 HTML 内容。
It will render the following HTML content.
<input id = "password" name = "password" type = "password" value = ""/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
</table>
</body>
</html>
完成源代码和配置文件的创建后,导出应用程序。右键单击应用程序,使用“导出 → WAR 文件”选项,并将 HelloWeb.war 文件保存在 Tomcat 的 webapps 文件夹中。
Once we are done with creating source and configuration files, export the application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试一个 URL –http://localhost:8080/HelloWeb/user,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application.
在提交所需信息后,单击“submit”按钮提交表单。如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - TextArea Example
以下示例介绍了如何在表单中使用 TextArea,方法是使用 Spring Web MVC 框架。首先,让我们提供一个可用的 Eclipse IDE,并按照后续步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序。
The following example explains how to use TextArea in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC − Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String 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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
UserController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
return "users";
}
}
在这里,对于第一个服务方法 user(),我们在 ModelAndView 对象中传递了一个空白 User 对象,名称为“command”,这是因为如果你在 JSP 文件中使用 <form:form> 标记,则 Spring 框架需要一个名为“command”的对象。因此,当调用 user() 方法时,它将返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将相对于 HelloWeb/addUser URL 上的 POST 方法调用。你将根据提交的信息准备模型对象。最后,“users”视图将从服务方法返回,这将导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:textarea /> 标记来呈现 HTML textarea 框。例如:
Here, we are using <form:textarea /> tag to render a HTML textarea box. For example −
<form:textarea path = "address" rows = "5" cols = "30" />
它将呈现以下 HTML 内容。
It will render the following HTML content.
<textarea id = "address" name = "address" rows = "5" cols = "30"></textarea>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
</table>
</body>
</html>
一旦你完成了创建源文件和配置文件,导出你的应用程序。右键单击你的应用程序,使用“导出 → WAR 文件”选项并将你的 HelloWeb.war 文件保存到 Tomcat 的 Webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试一个 URL –http://localhost:8080/HelloWeb/user,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application.
在提交所需信息后,单击“submit”按钮提交表单。如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Checkbox Example
以下示例介绍了如何在表单中使用单个复选框,方法是使用 Spring Web MVC 框架。首先,让我们提供一个可用的 Eclipse IDE,并考虑以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序。
The following example describes how to use a Single Checkbox in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspointas explained in the Spring MVC - Hello World Example chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create a view files user.jsp, users.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
}
UserController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
return "users";
}
}
在这里,对于第一个服务方法 user(),我们在 ModelAndView 对象中传递了一个空白 User 对象,名称为“command”,这是因为如果你在 JSP 文件中使用 <form:form> 标记,则 Spring 框架需要一个名为“command”的对象。因此,当调用 user() 方法时,它将返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called it returns the user.jsp view.
第二个服务方法 addUser() 将相对于 HelloWeb/addUser URL 上的 POST 方法调用。你将根据提交的信息准备模型对象。最后,“users”视图将从服务方法返回,这将导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:checkboxes /> 标记来呈现 HTML 复选框。
Here, we are using <form:checkboxes /> tag to render an HTML checkbox box.
例如 -
For example −
<form:checkbox path="receivePaper" />
它会呈现以下 HTML 内容。
It will render following HTML content.
<input id="receivePaper1" name = "receivePaper" type = "checkbox" value = "true"/>
<input type = "hidden" name = "_receivePaper" value = "on"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
</table>
</body>
</html>
一旦你完成了创建源文件和配置文件,导出你的应用程序。右键单击你的应用程序,使用“导出 → WAR 文件”选项并将你的 HelloWeb.war 文件保存到 Tomcat 的 Webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试一个 URL – [role="bare"] [role="bare"]http://localhost:8080/HelloWeb/user ,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – [role="bare"]http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application.
提交所需信息后,单击“提交”按钮以提交表单。如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen if everything is fine with the Spring Web Application.
Spring MVC - Checkboxes Example
以下示例介绍了如何在表单中使用多个复选框,方法是使用 Spring Web MVC 框架。首先,让我们提供一个可用的 Eclipse IDE,并严格按照以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序。
The following example explains how to use Multiple Checkboxes in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
}
UserController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
}
在这里,对于第一个服务方法 user() ,我们在 ModelAndView 对象中传递了一个空白 User 对象,名称为“command”,这是因为如果你在 JSP 文件中使用 <form:form> 标记,则 Spring 框架需要一个名为“command”的对象。因此,当调用 user() 方法时,它将返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将相对于 HelloWeb/addUser URL 上的 POST 方法调用。你将根据提交的信息准备模型对象。最后,“users”视图将从服务方法返回,这将导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:checkboxes /> 标记呈现 HTML 复选框。
Here, we are using <form:checkboxes /> tag to render HTML checkboxes.
<form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" />
它会呈现以下 HTML 内容。
It will render following HTML content.
<span>
<input id = "favoriteFrameworks1" name = "favoriteFrameworks" type = "checkbox" value = "Spring MVC" checked = "checked"/>
<label for = "favoriteFrameworks1">Spring MVC</label>
</span>
<span>
<input id = "favoriteFrameworks2" name = "favoriteFrameworks" type = "checkbox" value = "Struts 1"/>
<label for = "favoriteFrameworks2">Struts 1</label>
</span>
<span>
<input id = "favoriteFrameworks3" name = "favoriteFrameworks" type = "checkbox" value = "Struts 2" checked = "checked"/>
<label for = "favoriteFrameworks3">Struts 2</label>
</span>
<span>
<input id = "favoriteFrameworks4" name = "favoriteFrameworks" type = "checkbox" value = "Apache Wicket"/>
<label for = "favoriteFrameworks4">Apache Wicket</label>
</span>
<input type = "hidden" name = "_favoriteFrameworks" value = "on"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
</table>
</body>
</html>
在您创建了源文件和配置文件以后,导出您的应用程序。右键单击您的应用程序,使用 Export → WAR File 选项,并保存在Tomcat的webapps文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动Tomcat服务器,并确保您能通过标准浏览器访问webapps文件夹中的其它网页。尝试一个URL http://localhost:8080/HelloWeb/user ,如果Spring Web应用程序正常,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application.
提交所需信息后,单击提交按钮来提交表单。如果你的 Spring Web 应用程序一切正常,我们将看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - RadioButton Example
以下示例演示了如何在使用 Spring Web MVC 框架的表单中使用单选按钮。首先,我们提供一个正在运行的 Eclipse IDE,并按照以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序 −
The following example show how to use RadioButton in forms using the Spring Web MVC framework. To start with it, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using Spring Web Framework −
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
UserController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
}
这里第一个服务方法 user() ,我们在 ModelAndView 对象中传递了一个空白 User 对象,名称为“command”,因为如果您在 JSP 文件中使用 <form:form> 标记,Spring 框架需要名称为“command”的对象。所以当调用 user() 方法时,它会返回 user.jsp 视图。
Here, the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将针对 HelloWeb/addUser URL 上的 POST 方法进行调用。你将根据提交的信息准备你的模型对象。最后,将在服务方法中返回“users”视图,这会导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
这里我们使用 <form:radiobutton /> 标记来呈现 HTML 单选按钮。
Here, we are using <form:radiobutton /> tag to render HTML radiobutton.
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
它会呈现以下 HTML 内容。
It will render following HTML content.
<input id = "gender1" name = "gender" type = "radio" value = "M" checked = "checked"/><label for = "gender1">Male</label>
<input id = "gender2" name = "gender" type = "radio" value = "F"/><label for = "gender2">Female</label>
users.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
</table>
</body>
</html>
一旦创建完源文件和配置文件,导出您的应用程序。右键单击应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保您能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试一个 URL – http://localhost:8080/HelloWeb/user ,如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with your Spring Web Application.
在提交所需信息后,单击“submit”按钮提交表单。如果 Spring Web 应用程序一切正常,我们将会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - RadioButtons Example
以下示例解释了如何在表单中使用 Spring Web MVC 框架中的单选按钮。首先,让我们准备一个能正常工作的 Eclipse IDE,然后按照以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example explains how to use RadioButtons in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
}
UserController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
}
在这里,对于第一个服务方法 user(),我们在 ModelAndView 对象中传递了一个名称为“command”的空白 User 对象,因为如果你在 JSP 文件中使用 <form:form> 标记,Spring 框架会期望一个名称为“command”的对象。因此,当调用 user() 方法时,它会返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将针对 HelloWeb/addUser URL 上的 POST 方法进行调用。你将根据提交的信息准备你的模型对象。最后,将在服务方法中返回“users”视图,这会导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:radiobuttons /> 标记来呈现 HTML 单选按钮。例如 −
Here, we are using *<form:radiobuttons />*tag to render the HTML radiobuttons. For example −
<form:radiobuttons path = "favoriteNumber" items="${numbersList}" />
它将呈现以下 HTML 内容。
It will render the following HTML content.
<span>
<input id = "favoriteNumber1" name = "favoriteNumber" type = "radio" value = "1"/>
<label for = "favoriteNumber1">1</label>
</span>
<span>
<input id = "favoriteNumber2" name = "favoriteNumber" type = "radio" value = "2"/>
<label for = "favoriteNumber2">2</label>
</span>
<span>
<input id = "favoriteNumber3" name = "favoriteNumber" type = "radio" value = "3"/>
<label for = "favoriteNumber3">3</label>
</span>
<span>
<input id = "favoriteNumber4" name = "favoriteNumber" type = "radio" value = "4"/>
<label for = "favoriteNumber4">4</label>
</span>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
</table>
</body>
</html>
创建源文件和配置文件后,导出应用程序。右键单击应用程序,然后单击 Export → WAR File 选项,并通过 Tomcat 的 webapps 文件夹保存 HelloWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保你可以使用标准浏览器从 webapps 文件夹访问其他网页。尝试以下 URL – http://localhost:8080/HelloWeb/user ,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try the following URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application.
提交所需信息后,单击提交按钮来提交表单。如果你的 Spring Web 应用程序一切正常,我们将看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - Dropdown Example
以下示例描述了如何使用Spring Web MVC框架在表单中使用下拉菜单。首先,我们得准备一个Eclipse IDE并按照以下步骤,使用Spring Web框架开发一个基于动态表单的Web应用程序。
The following example describes how to use Dropdown in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
private String country;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
model.addAttribute("country", user.getCountry());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
@ModelAttribute("countryList")
public Map<String, String> getCountryList() {
Map<String, String> countryList = new HashMap<String, String>();
countryList.put("US", "United States");
countryList.put("CH", "China");
countryList.put("SG", "Singapore");
countryList.put("MY", "Malaysia");
return countryList;
}
}
这里,对于第一个服务方法 user() 来说,我们在“command”名称的ModelAndView对象中传递了一个空 User 对象,因为如果你的JSP文件里使用<form:form>标签的话,Spring框架期望一个名称为“command”的对象。因此当 user() 被调用时,它返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So when the user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将针对 HelloWeb/addUser URL 上的 POST 方法进行调用。你将根据提交的信息准备你的模型对象。最后,将在服务方法中返回“users”视图,这会导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}" />
</td>
</tr>
<tr>
<td><form:label path = "country">Country</form:label></td>
<td>
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}" />
</form:select>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
这里,我们使用 <form:select /> , <form:option /> 和 <form:options /> 标签来呈现 HTML 选择。例如 −
Here, we are using <form:select /> , <form:option /> and <form:options /> tags to render HTML select. For example −
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}" />
</form:select>
它会呈现以下 HTML 内容。
It will render following HTML content.
<select id = "country" name = "country">
<option value = "NONE">Select</option>
<option value = "US">United States</option>
<option value = "CH">China</option>
<option value = "MY">Malaysia</option>
<option value = "SG">Singapore</option>
</select>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
<tr>
<td>Country</td>
<td>${country}</td>
</tr>
</table>
</body>
</html>
一旦你完成了创建源文件和配置文件,导出你的应用程序。右键单击你的应用程序,使用 Export → WAR File 选项并将你的 HelloWeb.war 文件保存到 Tomcat 的 Webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你能够使用标准浏览器访问 Webapps 文件夹中的其他网页。尝试一个 URL - http://localhost:8080/HelloWeb/user ,如果 Spring Web 应用程序一切正常,我们将看到下面的屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application.
在提交所需的信息后,单击提交按钮以提交表单。如果 Spring Web 应用程序一切正常,你应该会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - Listbox Example
以下示例展示了如何在表单中使用Spring Web MVC框架中的列表框。首先,让我们使用Eclipse IDE并按照后续步骤使用Spring Web框架开发一个基于动态表单的Web应用程序。
The following example shows how to use Listbox in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User, UserController under the com.tutorialspointpackage. |
3 |
Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
private String country;
private String [] skills;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
}
UserController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
model.addAttribute("country", user.getCountry());
model.addAttribute("skills", user.getSkills());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
@ModelAttribute("countryList")
public Map<String, String> getCountryList() {
Map<String, String> countryList = new HashMap<String, String>();
countryList.put("US", "United States");
countryList.put("CH", "China");
countryList.put("SG", "Singapore");
countryList.put("MY", "Malaysia");
return countryList;
}
@ModelAttribute("skillsList")
public Map<String, String> getSkillsList() {
Map<String, String> skillList = new HashMap<String, String>();
skillList.put("Hibernate", "Hibernate");
skillList.put("Spring", "Spring");
skillList.put("Apache Wicket", "Apache Wicket");
skillList.put("Struts", "Struts");
return skillList;
}
}
在这里,对于第一个服务方法 user() ,我们在 ModelAndView 对象中传递了一个空白 User 对象,名称为“command”,这是因为如果你在 JSP 文件中使用 <form:form> 标记,则 Spring 框架需要一个名为“command”的对象。因此,当调用 user() 方法时,它将返回 user.jsp 视图。
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view.
第二个服务方法 addUser() 将针对 HelloWeb/addUser URL 上的 POST 方法进行调用。你将根据提交的信息准备你的模型对象。最后,将在服务方法中返回“users”视图,这会导致呈现 users.jsp。
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper" /></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male" />
<form:radiobutton path = "gender" value = "F" label = "Female" />
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}" />
</td>
</tr>
<tr>
<td><form:label path = "country">Country</form:label></td>
<td>
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}" />
</form:select>
</td>
</tr>
<tr>
<td><form:label path = "skills">Skills</form:label></td>
<td>
<form:select path = "skills" items = "${skillsList}"
multiple = "true" />
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:select /> 标记,其中具有属性 multiple=true 来绘制一个HTML列表框。例如 −
Here, we are using a <form:select /> tag , with the attribute multiple=true to render an HTML listbox. For example −
<form:select path = "skills" items = "${skillsList}" multiple = "true" />
它会呈现以下 HTML 内容。
It will render following HTML content.
<select id = "skills" name = "skills" multiple = "multiple">
<option value = "Struts">Struts</option>
<option value = "Hibernate">Hibernate</option>
<option value = "Apache Wicket">Apache Wicket</option>
<option value = "Spring">Spring</option>
</select>
<input type = "hidden" name = "_skills" value = "1"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
<tr>
<td>Country</td>
<td>${country}</td>
</tr>
<tr>
<td>Skills</td>
<td> <% String[] skills = (String[])request.getAttribute("skills");
for(String skill: skills) {
out.println(skill);
}
%></td>
</tr>
</table>
</body>
</html>
创建源文件和配置文件后,导出应用程序。右键单击应用程序,然后单击 Export → WAR File 选项,并通过 Tomcat 的 webapps 文件夹保存 HelloWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动Tomcat服务器,并确保您能通过标准浏览器访问webapps文件夹中的其它网页。尝试一个URL − http://localhost:8080/HelloWeb/user ,如果Spring Web应用程序正常,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application.
在提交所需的信息后,单击提交按钮以提交表单。如果 Spring Web 应用程序一切正常,你应该会看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - Hidden Field Example
以下示例描述了如何在表单中使用Spring Web MVC框架中的隐藏字段。首先,让我们使用Eclipse IDE并按照以下步骤使用Spring Web框架开发一个基于动态表单的Web应用程序。
The following example describes how to use a Hidden Field in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes Student, StudentController under the com.tutorialspoint package. |
3 |
Create view files student.jsp, result.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
在这里,对于第一个服务方法 student() ,我们在ModelAndView对象中传递了一个空白 Studentobject ,名称为“command”,因为如果您在JSP文件中使用<form:form>标记,Spring框架将期待一个名为“command”的对象。因此,当调用 student() 方法时,它将返回 student.jsp 视图。
Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with the name "command", because the spring framework expects an object with the name "command", if you are using <form:form> tags in your JSP file. So, when the student() method is called, it returns the student.jsp view.
第二个服务方法 addStudent() 将针对 HelloWeb/addStudent URL 中的 POST 方法调用。您将根据已提交的信息准备模型对象。最后,将从服务方法返回一个“result”视图,此视图将导致呈现 result.jsp。
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering result.jsp
student.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td>< </td>
<td><form:hidden path = "id" value = "1" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:hidden /> 标记来绘制一个HTML隐藏字段。
Here, we are using the <form:hidden /> tag to render a HTML hidden field.
例如 -
For example −
<form:hidden path = "id" value = "1"/>
它会呈现以下 HTML 内容。
It will render following HTML content.
<input id = "id" name = "id" type = "hidden" value = "1"/>
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
在您创建了源文件和配置文件以后,导出您的应用程序。右键单击您的应用程序并使用 Export → WAR File 选项,并保存在Tomcat的webapps文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application and use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动Tomcat服务器,并确保您能通过标准浏览器访问webapps文件夹中的其它网页。尝试一个URL – http://localhost:8080/HelloWeb/student ,如果Spring Web应用程序正常,我们将看到以下屏幕。
Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/student and we will see the following screen, if everything is fine with the Spring Web Application.
提交所需信息后,单击提交按钮来提交表单。如果你的 Spring Web 应用程序一切正常,我们将看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application.
Spring MVC - Error Handling Example
以下示例展示了如何在表单中使用Spring Web MVC框架中的错误处理和验证器。首先,让我们使用Eclipse IDE并按照以下步骤使用Spring Web框架开发一个基于动态表单的Web应用程序。
The following example shows how to use Error Handling and Validators in forms using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes Student, StudentController and StudentValidator under the com.tutorialspoint package. |
3 |
Create view files addStudent.jsp, result.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentValidator.java
package com.tutorialspoint;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StudentValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Student.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"name", "required.name","Field name is required.");
}
}
StudentController.java
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@Autowired
@Qualifier("studentValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("addStudent", "command", new Student());
}
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "addStudent";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id = "studentValidator" class = "com.tutorialspoint.StudentValidator" />
</beans>
在这里,对于第一个服务方法 student() ,我们在ModelAndView对象中传递了一个空白Studentobject,名称为“command”,因为如果您在JSP文件中使用<form:form>标记,Spring框架将期待一个名为“command”的对象。因此,当调用student()方法时,它将返回 addStudent.jsp 视图。
Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when student() method is called, it returns addStudent.jsp view.
第二个服务方法 addStudent() 将在 HelloWeb/addStudent URL上的POST方法中被调用。您将根据提交的信息准备您的模型对象。最后,将从服务方法中返回“result”视图,这将导致渲染result.jsp。如果使用验证器生成了错误,那么将返回相同的“addStudent”视图,Spring将自动在视图中从 BindingResult 注入错误消息。
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering the result.jsp. In case there are errors generated using validator then same view "addStudent" is returned, Spring automatically injects error messages from BindingResult in view.
addStudent.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent" commandName = "student">
<form:errors path = "*" cssClass = "errorblock" element = "div" />
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
<td><form:errors path = "name" cssClass = "error" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用 <form:errors /> 标签和path="*"来呈现错误消息。例如
Here we are using <form:errors /> tag with path="*" to render error messages. For example
<form:errors path = "*" cssClass = "errorblock" element = "div" />
它将呈现所有输入验证的错误消息。
It will render the error messages for all input validations.
我们使用 <form:errors /> 标签和path="name"来呈现name字段的错误消息。例如
We are using <form:errors /> tag with path="name" to render error message for name field. For example
<form:errors path = "name" cssClass = "error" />
它将呈现name字段验证的错误消息。
It will render error messages for the name field validations.
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
一旦创建完源文件和配置文件,导出您的应用程序。右键单击应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保能够使用标准浏览器访问 webapps 文件夹中的其他网页。尝试以下 URL - http://localhost:8080/HelloWeb/addStudent 如果 Spring Web 应用程序一切正常,我们会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL − http://localhost:8080/HelloWeb/addStudent and we will see the following screen, if everything is fine with the Spring Web Application.
提交所需信息后,单击提交按钮提交表单。如果 Spring Web 应用程序一切正常,您应该看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - File Upload Example
以下示例展示了如何在表单中使用文件上传控件及使用 Spring Web MVC 框架。首先准备一个可用的 Eclipse IDE,并遵循以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example shows how to use File Upload Control in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes FileModel, FileUploadController under the com.tutorialspoint package. |
3 |
Create view files fileUpload.jsp, success.jsp under the jsp sub-folder. |
4 |
Create a folder temp under the WebContent sub-folder. |
5 |
Download Apache Commons FileUpload library commons-fileupload.jar and Apache Commons IO library commons-io.jar. Put them in your CLASSPATH. |
6 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
FileModel.java
package com.tutorialspoint;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
FileUploadController.java
package com.tutorialspoint;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController {
@Autowired
ServletContext context;
@RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
@RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
//Now do something with file...
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
String fileName = multipartFile.getOriginalFilename();
model.addAttribute("fileName", fileName);
return "success";
}
}
}
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id = "multipartResolver"
class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
这里,对于第一个服务方法 fileUploadPage() ,我们在 ModelAndView 对象中传递了一个空白 FileModel 对象,名称为 command,因为如果您在您的 JSP 文件中使用了 <form:form> 标签,Spring 框架会期盼一个名称为 command 的对象。因此,当调用 fileUploadPage() 方法时,它会返回 fileUpload.jsp 视图。
Here, for the first service method fileUploadPage(), we have passed a blank FileModel object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when fileUploadPage() method is called, it returns fileUpload.jsp view.
第二个服务方法 fileUpload() 将被用于对比 HelloWeb/fileUploadPage URL 的 POST 方法。您将根据提交的信息准备要上传的文件。最后,服务方法会返回 success 视图,这将导致呈现 success.jsp。
The second service method fileUpload() will be called against a POST method on the HelloWeb/fileUploadPage URL. You will prepare the file to be uploaded based on the submitted information. Finally, a "success" view will be returned from the service method, which will result in rendering success.jsp.
fileUpload.jsp
<%@ page contentType="text/html; charset = UTF-8" %>
<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<form:form method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file" />
<input type = "submit" value = "upload" />
</form:form>
</body>
</html>
这里,我们使用 modelAttribute 属性以及值为 fileUpload 来映射文件上传控件和服务器模型。
Here, we are using modelAttribute attribute with value="fileUpload" to map the file Upload control with the server model.
success.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
FileName :
lt;b> ${fileName} </b> - Uploaded Successfully.
</body>
</html>
在创建原代码和配置文件后,导出您的应用程序。右键单击您的应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in the Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保能够使用标准浏览器访问 webapps 文件夹中的其他网页。尝试以下 URL - http://localhost:8080/HelloWeb/fileUploadPage 如果 Spring Web 应用程序一切正常,我们会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL– http://localhost:8080/HelloWeb/fileUploadPage and we will see the following screen, if everything is fine with the Spring Web Application.
提交所需信息后,单击提交按钮提交表单。如果 Spring Web 应用程序一切正常,您应该看到以下屏幕。
After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Bean Name Url Handler Mapping Example
以下示例展示了如何使用Spring Web MVC框架使用Bean名称URL处理程序映射。 BeanNameUrlHandlerMapping 类是默认的处理程序映射类,该类将URL请求映射到配置中所述bean的名称。
The following example shows how to use Bean Name URL Handler Mapping using the Spring Web MVC Framework. The BeanNameUrlHandlerMapping class is the default handler mapping class, which maps the URL request(s) to the name of the beans mentioned in the configuration.
<beans>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/helloWorld.htm"
class = "com.tutorialspoint.HelloController" />
<bean name = "/hello*"
class = "com.tutorialspoint.HelloController" />
<bean name = "/welcome.htm"
class = "com.tutorialspoint.WelcomeController"/>
</beans>
例如,使用以上配置,如果 URI
For example, using the above configuration, if URI
-
/helloWorld.htm or /hello{any letter}.htm is requested, DispatcherServlet will forward the request to the HelloController.
-
/welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController.
-
/welcome1.htm is requested, DispatcherServlet will not find any controller and server will throw 404 status error.
首先,让我们准备好一个运行的 Eclipse IDE,然后考虑以下步骤使用 Spring Web Framework 开发一个基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes HelloController, WelcomeController under the com.tutorialspoint package. |
3 |
Create view files hello.jsp, welcome.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of all source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/helloWorld.htm"
class = "com.tutorialspoint.HelloController" />
<bean name = "/hello*"
class = "com.tutorialspoint.HelloController" />
<bean name = "/welcome.htm"
class = "com.tutorialspoint.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in the Tomcat’s webapps folder.
现在,启动你的 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。如果 Spring Web 应用程序一切正常,尝试一下 URL − http://localhost:8080/TestWeb/helloWorld.htm ,我们将看到以下界面。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试一个网址 http://localhost:8080/TestWeb/hello.htm ,如果Spring Web应用程序一切正常,我们将会看到以下屏幕。
Try a URL − http://localhost:8080/TestWeb/hello.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试一个网址 http://localhost:8080/TestWeb/welcome.htm ,如果Spring Web应用程序一切正常,我们将会看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试一个网址 http://localhost:8080/TestWeb/welcome1.htm ,如果Spring Web应用程序一切正常,我们将会看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/welcome1.htm and we will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Controller Class Name Handler Mapping Example
以下示例展示了如何使用控制器类名处理映射及使用 Spring Web MVC 框架。 ControllerClassNameHandlerMapping 类是基于约定的处理程序映射类,它将 URL 请求映射到配置中提到的控制器的名称。该类获取控制器名称并将它们转换成小写,并在其前面添加 /。
The following example shows how to use the Controller Class Name Handler Mapping using the Spring Web MVC framework. The ControllerClassNameHandlerMapping class is the convention-based handler mapping class, which maps the URL request(s) to the name of the controllers mentioned in the configuration. This class takes the Controller names and converts them to lower case with a leading "/".
例如 - HelloController 映射到 /hello* URL。
For example − HelloController maps to "/hello*" URL.
<beans>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.tutorialspoint.HelloController" />
<bean class = "com.tutorialspoint.WelcomeController"/>
</beans>
例如,使用以上配置,如果请求 URI
For example, using above configuration, if URI
-
/helloWorld.htm or /hello{any letter}.htm is requested, DispatcherServlet will forward the request to the HelloController.
-
/welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController.
-
/Welcome.htm is requested where W is capital cased, DispatcherServlet will not find any controller and the server will throw 404 status error.
首先准备一个可用的 Eclipse IDE,并遵循后续步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
To start with it, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes HelloController and WelcomeController under the com.tutorialspoint package. |
3 |
Create view files hello.jsp, welcome.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.tutorialspoint.HelloController" />
<bean class = "com.tutorialspoint.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType="text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset=UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
在创建原代码和配置文件后,导出您的应用程序。右键单击该应用程序,使用 Export → WAR File 选项,并将 TestWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on the application, use the Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保能够使用标准浏览器访问 webapps 文件夹中的其他网页。尝试以下 URL - http://localhost:8080/TestWeb/helloWorld.htm 如果 Spring Web 应用程序一切正常,我们会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试以下 URL - http://localhost:8080/TestWeb/hello.htm 如果 Spring Web 应用程序一切正常,我们会看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/hello.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试一个网址 http://localhost:8080/TestWeb/welcome.htm ,如果Spring Web应用程序一切正常,我们将会看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试URL http://localhost:8080/TestWeb/Welcome.htm ,如果Spring Web应用程序一切正常,我们将看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/Welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Simple Url Handler Mapping Example
以下示例展示如何使用 Spring Web MVC 框架使用 Simple URL Handler Mapping。SimpleUrlHandlerMapping 类有助于将 URL 显式映射到其各自的控制器。
The following example shows how to use Simple URL Handler Mapping using the Spring Web MVC framework. The SimpleUrlHandlerMapping class helps to explicitly-map URLs with their controllers respectively.
<beans>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<props>
<prop key = "/welcome.htm">welcomeController</prop>
<prop key = "/helloWorld.htm">helloController</prop>
</props>
</property>
</bean>
<bean id = "helloController" class = "com.tutorialspoint.HelloController" />
<bean id = "welcomeController" class = "com.tutorialspoint.WelcomeController"/>
</beans>
例如,使用以上配置,如果请求 URI
For example, using above configuration, if URI
-
/helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController.
-
/welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController.
首先,让我们准备好一个运行的 Eclipse IDE,然后考虑以下步骤使用 Spring Web Framework 开发一个基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes HelloController and WelcomeController under the com.tutorialspoint package. |
3 |
Create view files hello.jsp and welcome.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<props>
<prop key = "/welcome.htm">welcomeController</prop>
<prop key = "/helloWorld.htm">helloController</prop>
</props>
</property>
</bean>
<bean id = "helloController" class = "com.tutorialspoint.HelloController" />
<bean id = "welcomeController" class = "com.tutorialspoint.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦创建好源代码和配置文件,就导出你的应用程序。右键单击你的应用程序,使用 Export → WAR File 选项,并将你的 TestWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your TestWeb.war file in Tomcat’s webapps folder.
现在,启动你的 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。如果 Spring Web 应用程序一切正常,尝试一下 URL − http://localhost:8080/TestWeb/helloWorld.htm ,我们将看到以下界面。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试一下 URL http://localhost:8080/TestWeb/welcome.htm ,如果你的 Spring Web 应用程序一切正常,你应该会看到以下结果。
Try a URL http://localhost:8080/TestWeb/welcome.htm and you should see the following result if everything is fine with your Spring Web Application.
Spring MVC - Multi Action Controller Example
以下示例展示了如何使用Spring Web MVC框架使用Multi Action Controller。 MultiActionController 类帮助分别将多个URL与其方法映射到单个控制器。
The following example shows how to use the Multi Action Controller using the Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively.
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("home");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/home.htm" class = "com.tutorialspoint.UserController" />
<bean name = "/user/*.htm" class = "com.tutorialspoint.UserController" />
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/home.htm is requested, DispatcherServlet will forward the request to the UserController home() method.
-
user/add.htm is requested, DispatcherServlet will forward the request to the UserController add() method.
-
user/remove.htm is requested, DispatcherServlet will forward the request to the UserController remove() method.
首先,让我们准备一个可用的Eclipse IDE,并坚持以下步骤,使用Spring Web框架开发基于动态表单的Web应用程序。
To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class UserController under the com.tutorialspoint package. |
3 |
Create view files home.jsp and user.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("home");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/home.htm"
class = "com.tutorialspoint.UserController" />
<bean name = "/user/*.htm"
class = "com.tutorialspoint.UserController" />
</beans>
home.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<title>Home</title>
</head>
<body>
<a href = "user/add.htm" >Add</a> <br>
<a href = "user/remove.htm" >Remove</a>
</body>
</html>
user.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动您的Tomcat服务器,并确保您可以使用标准浏览器从webapps文件夹访问其他网页。现在,尝试URL − http://localhost:8080/TestWeb/home.htm ,如果Spring Web应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try a URL − http://localhost:8080/TestWeb/home.htm and we will see the following screen, if everything is fine with the Spring Web Application.
尝试URL http://localhost:8080/TestWeb/user/add.htm ,如果Spring Web应用程序一切正常,我们将看到以下屏幕。
Try a URL http://localhost:8080/TestWeb/user/add.htm and we will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Properties Method Name Resolver Example
以下示例展示了如何使用Spring Web MVC框架的Multi Action Controller的方法名解析器方法。 MultiActionController 类帮助分别将多个URL与其方法映射到单个控制器。
The following example shows how to use the Properties Method Name Resolver method of a Multi Action Controller using Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively.
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "com.tutorialspoint.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name = "mappings">
<props>
<prop key = "/user/home.htm">home</prop>
<prop key = "/user/add.htm">add</prop>
<prop key = "/user/remove.htm">update</prop>
</props>
</property>
</bean>
</property>
</bean>
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/user/home.htm is requested, DispatcherServlet will forward the request to the UserController home() method.
-
/user/add.htm is requested, DispatcherServlet will forward the request to the UserController add() method.
-
/user/remove.htm is requested, DispatcherServlet will forward the request to the UserController remove() method.
首先,让我们准备一个可用的Eclipse IDE,并考虑以下步骤,使用Spring Web框架开发基于动态表单的Web应用程序。
To start with it, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java class UserController under the com.tutorialspoint package. |
3 |
Create a view file user.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name = "caseSensitive" value = "true" />
</bean>
<bean class = "com.tutorialspoint.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name = "mappings">
<props>
<prop key = "/user/home.htm">home</prop>
<prop key = "/user/add.htm">add</prop>
<prop key = "/user/remove.htm">update</prop>
</props>
</property>
</bean>
</property>
</bean>
</beans>
user.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动您的Tomcat服务器,并确保您可以使用标准浏览器从webapps文件夹访问其他网页。现在,尝试URL − http://localhost:8080/TestWeb/user/add.htm ,如果Spring Web应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Now, try a URL − http://localhost:8080/TestWeb/user/add.htm and we will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Parameter Method Name Resolver Example
以下示例展示了如何使用 Spring Web MVC 框架的 Parameter Method Name Resolver 使用多动作控制器。 MultiActionController 类有助于为单个控制器分别映射多个网址及其方法。
The following example shows how to use the Parameter Method Name Resolver of a Multi Action Controller using the Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively.
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "com.tutorialspoint.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name = "paramName" value = "action"/>
</bean>
</property>
</bean>
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/user/.htm?action=home is requested, DispatcherServlet will forward the request to the UserController *home() method.
-
/user/.htm?action=add is requested, DispatcherServlet will forward the request to the UserController *add() method.
-
/user/.htm?action=remove is requested, DispatcherServlet will forward the request to the UserController *remove() method.
首先,我们准备一个可用的 Eclipse IDE,然后遵循以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class UserController under the com.tutorialspoint package. |
3 |
Create a view file user.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name = "caseSensitive" value = "true" />
</bean>
<bean class = "com.tutorialspoint.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name = "paramName" value = "action"/>
</bean>
</property>
</bean>
</beans>
user.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保可以使用标准浏览器访问 webapps 文件夹中的其他网页。现在尝试一个网址 http://localhost:8080/TestWeb/user/test.htm?action=home ,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Now, try a URL − http://localhost:8080/TestWeb/user/test.htm?action=home and we will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Parameterizable View Controller Example
以下示例展示了如何使用Spring Web MVC框架的Multi Action Controller的参数化视图控制器方法。参数化视图允许使用请求映射网页。
The following example shows how to use the Parameterizable View Controller method of a Multi Action Controller using the Spring Web MVC framework. The Parameterizable View allows mapping a webpage with a request.
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
}
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
index.htm=userController
</value>
</property>
</bean>
<bean id="userController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="user"/>
</bean>
例如,使用以上配置,如果URI。
For example, using the above configuration, if URI.
-
/index.htm is requested, DispatcherServlet will forward the request to the UserController controller with viewName set as user.jsp.
首先,让我们建立一个可用的 Eclipse IDE,并遵循以下步骤,使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
To start with it, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class UserController under the com.tutorialspoint package. |
3 |
Create a view file user.jsp under the jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.tutorialspoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<value>
index.htm = userController
</value>
</property>
</bean>
<bean id = "userController" class = "org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name = "viewName" value="user"/>
</bean>
</beans>
user.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Hello World</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动您的 Tomcat 服务器,并确保您可以使用标准浏览器从 Webapps 文件夹中访问其他网页。现在,尝试一个 URL – http://localhost:8080/TestWeb/index.htm ,如果 Spring Web 应用程序一切正常,您将看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try a URL – http://localhost:8080/TestWeb/index.htm and you will see the following screen, if everything is fine with the Spring Web Application.
Spring MVC - Internal Resource View Resolver Example
InternalResourceViewResolver 用于将提供的 URI 解析到实际 URI。以下示例展示如何使用 Spring Web MVC Framework 使用 InternalResourceViewResolver。InternalResourceViewResolver 允许将网页与请求进行映射。
The InternalResourceViewResolver is used to resolve the provided URI to actual URI. The following example shows how to use the InternalResourceViewResolver using the Spring Web MVC Framework. The InternalResourceViewResolver allows mapping webpages with requests.
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
例如,使用以上配置,如果 URI
For example, using the above configuration, if URI
-
/hello is requested, DispatcherServlet will forward the request to the prefix + viewname + suffix = /WEB-INF/jsp/hello.jsp.
首先,我们得准备一个Eclipse IDE并按照以下步骤,使用Spring Web框架开发一个基于动态表单的Web应用程序。
To start with, let us have a working Eclipse IDE in place and then consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspointas explained in the Spring MVC - Hello World Example chapter. |
2 |
Create a Java classes HelloController under the com.tutorialspointpackage. |
3 |
Create a view file hello.jsp under jsp sub-folder. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动你的Tomcat服务器,并保证你可以使用标准浏览器从webapps文件夹访问其他网页。尝试访问网址: http://localhost:8080/TestWeb/hello ,如果Spring Web应用程序一切正常,我们将会看到以下屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL – http://localhost:8080/TestWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen.
Spring MVC - Xml View Resolver Example
XmlViewResolver 用于使用在 xml 文件中定义的视图 bean 解析视图名称。以下示例演示了如何使用 Spring Web MVC 框架使用 XmlViewResolver。
The XmlViewResolver is used to resolve the view names using view beans defined in xml file. The following example shows how to use the XmlViewResolver using Spring Web MVC framework.
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
views.xml
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp" />
</bean>
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml.
首先,让我们准备好一个运行的 Eclipse IDE,然后按以下步骤使用 Spring Web Framework 开发一个基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class HelloController under the com.tutorialspointpackage. |
3 |
Create a view file hello.jsp under the jsp sub-folder. |
4 |
Download JSTL library jstl.jar. Put it in your CLASSPATH. |
5 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp" />
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
一旦创建完源文件和配置文件,导出您的应用程序。右键单击应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试访问 URL − http://localhost:8080/HelloWeb/hello ,如果 Spring Web 应用程序一切正常,我们将看到以下界面。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen.
Spring MVC - Resource Bundle View Resolver Example
ResourceBundleViewResolver 用于使用属性文件中定义的视图 bean 来解析视图名称。以下示例显示了如何使用 Spring Web MVC 框架的 ResourceBundleViewResolver。
The ResourceBundleViewResolver is used to resolve the view names using view beans defined in the properties file. The following example shows how to use the ResourceBundleViewResolver using the Spring Web MVC Framework.
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views" />
</bean>
这里, basename 指的是资源包的名称,它携带视图。资源包的默认名称是 views.properties ,可以使用 basename 属性覆盖它。
Here, the basename refers to name of the resource bundle, which carries the views. The default name of the resource bundle is views.properties, which can be overridden using the basename property.
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url = /WEB-INF/jsp/hello.jsp
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties.
-
Here, "hello" is the view name to be matched. Whereas, class refers to the view type and URL is the view’s location.
首先,让我们建立一个可用的 Eclipse IDE,并考虑以下步骤,使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class HelloController under the com.tutorialspointpackage. |
3 |
Create a view file hello.jsp under the jsp sub-folder. |
4 |
Create a properties file views.properties under the src folder. |
5 |
Download JSTL library jstl.jar. Put it in your CLASSPATH. |
6 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views" />
</bean>
</beans>
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url = /WEB-INF/jsp/hello.jsp
hello.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
创建源文件和配置文件后,导出您的应用程序。右键单击您的应用程序,使用 Export → WAR File 选项并保存 HelloWeb.war 文件到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试访问 URL − http://localhost:8080/HelloWeb/hello ,如果 Spring Web 应用程序一切正常,我们将看到以下界面。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen.
Spring MVC - Multiple Resolver Mapping Example
如果您想在 Spring MVC 应用程序中使用多个视图解析器,那么可以使用 order 属性设置优先级顺序。以下示例显示了如何在 Spring Web MVC 框架中使用 ResourceBundleViewResolver 和 InternalResourceViewResolver 。
In case you want to use a Multiple View Resolver in a Spring MVC application then priority order can be set using the order property. The following example shows how to use the ResourceBundleViewResolver and the InternalResourceViewResolver in the Spring Web MVC Framework.
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views" />
<property name = "order" value = "0" />
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
<property name = "order" value = "1" />
</bean>
这里,order 属性定义了视图解析器的排名。在此,0 是第一个解析器,1 是下一个解析器,依此类推。
Here, the order property defines the ranking of a view resolver. In this, 0 is the first resolver and 1 is the next resolver and so on.
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url = /WEB-INF/jsp/hello.jsp
例如,使用以上配置,如果请求 URI −
For example, using the above configuration, if URI −
-
/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in views.properties.
首先,让我们准备好一个运行的 Eclipse IDE,然后考虑以下步骤使用 Spring Web Framework 开发一个基于动态表单的 Web 应用程序。
To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class HelloController under the com.tutorialspointpackage. |
3 |
Create a view file hello.jsp under the jsp sub-folder. |
4 |
Create a properties file views.properties under the SRC folder. |
5 |
Download the JSTL library jstl.jar. Put it in your CLASSPATH. |
6 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views" />
<property name = "order" value = "0" />
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
<property name = "order" value = "1" />
</bean>
</beans>
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url = /WEB-INF/jsp/hello.jsp
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
在您创建了源文件和配置文件以后,导出您的应用程序。右键单击您的应用程序,使用 Export → WAR File 选项,并保存在Tomcat的webapps文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,并确保您可以使用标准浏览器从 Webapps 文件夹访问其他网页。尝试访问 URL - http://localhost:8080/HelloWeb/hello ,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello, if everything is fine with the Spring Web Application, we will see the following screen.
Spring MVC - Hibernate Validator Example
以下示例演示了如何在表单中使用 Spring Web MVC 框架进行错误处理和验证。首先,让我们建立一个可用的 Eclipse IDE,并遵循以下步骤,使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example shows how to use Error Handling and Validators in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes Student, StudentController and StudentValidator under the com.tutorialspoint package. |
3 |
Create view files addStudent.jsp and result.jsp under the jsp sub-folder. |
4 |
Download Hibernate Validator library Hibernate Validator. Extract hibernate-validator-5.3.4.Final.jar and required dependencies present under the required folder of the downloaded zip file. Put them in your CLASSPATH. |
5 |
Create a properties file messages.properties under the SRC folder. |
6 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.tutorialspoint;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
public class Student {
@Range(min = 1, max = 150)
private Integer age;
@NotEmpty
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("addStudent", "command", new Student());
}
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "addStudent";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
messages.properties
NotEmpty.student.name = Name is required!
Range.student.age = Age value must be between 1 and 150!
在这里,密钥是 <Annotation>.<object-name>.<attribute>。值要显示的消息。
Here, the key is <Annotation>.<object-name>.<attribute>. Value is the message to be displayed.
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<mvc:annotation-driven />
<bean class = "org.springframework.context.support.ResourceBundleMessageSource"
id = "messageSource">
<property name = "basename" value = "messages" />
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
在这里,对于第一个服务方法 student() ,我们在 ModelAndView 对象中传递了一个空的 Studentobject> ,并命名为“command”,因为 spring 框架期望在 JSP 文件中使用 <form:form> 标记时,有一个名为“command”的对象。所以,当调用 student() 方法时,它返回 addStudent.jsp 视图。
Here, for the first service method student(), we have passed a blank Studentobject> in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the student() method is called, it returns addStudent.jsp view.
第二个服务方法 addStudent() 将在 HelloWeb/addStudent URL上的POST方法中被调用。您将根据提交的信息准备您的模型对象。最后,将从服务方法中返回“result”视图,这将导致渲染result.jsp。如果使用验证器生成了错误,那么将返回相同的“addStudent”视图,Spring将自动在视图中从 BindingResult 注入错误消息。
The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering the result.jsp. In case there are errors generated using validator then same view "addStudent" is returned, Spring automatically injects error messages from BindingResult in view.
addStudent.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/TestWeb/addStudent" commandName = "student">
<form:errors path = "*" cssClass = "errorblock" element = "div" />
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name" /></td>
<td><form:errors path = "name" cssClass = "error" /></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age" /></td>
<td><form:errors path = "age" cssClass = "error" /></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在这里,我们使用了 path="*" 的 <form:errors /> 标记来呈现错误消息。例如 -
Here, we are using the <form:errors /> tag with path="*" to render error messages. For example −
<form:errors path = "*" cssClass = "errorblock" element = "div" />
它将针对所有输入验证呈现错误消息。我们使用了 path = “name” 的 <form:errors /> 标记来呈现 name 字段的错误消息。
It will render error messages for all input validations. We are using <form:errors /> tag with path = "name" to render error message for the name field.
例如 -
For example −
<form:errors path = "name" cssClass = "error" />
<form:errors path = "age" cssClass = "error" />
它将针对 name 和 age 字段验证呈现错误消息。
It will render error messages for name and age field validations.
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
一旦创建完源文件和配置文件,导出您的应用程序。右键单击应用程序,使用 Export → WAR File 选项,并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试一个 URL - http://localhost:8080/TestWeb/addStudent ,如果你输入无效值,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/addStudent and we will see the following screen, if you have entered invalid values.
Spring MVC - Generate RSS Feed Example
以下示例展示了如何使用 Spring Web MVC 框架生成 RSS 订阅源。首先,我们准备一个可用的 Eclipse IDE,然后考虑以下步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example shows how to generate RSS Feed using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and then consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes RSSMessage, RSSFeedViewer and RSSController under the com.tutorialspoint package. |
3 |
Download the Rome library Rome and its dependencies rome-utils, jdom and slf4j from the same maven repository page. Put them in your CLASSPATH. |
4 |
Create a properties file messages.properties under the SRC folder. |
5 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
RSSMessage.java
package com.tutorialspoint;
import java.util.Date;
public class RSSMessage {
String title;
String url;
String summary;
Date createdDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
RSSFeedViewer.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;
public class RSSFeedViewer extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed,
HttpServletRequest request) {
feed.setTitle("TutorialsPoint Dot Com");
feed.setDescription("Java Tutorials and Examples");
feed.setLink("http://www.tutorialspoint.com");
super.buildFeedMetadata(model, feed, request);
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<RSSMessage> listContent = (List<RSSMessage>) model.get("feedContent");
List<Item> items = new ArrayList<Item>(listContent.size());
for(RSSMessage tempContent : listContent ){
Item item = new Item();
Content content = new Content();
content.setValue(tempContent.getSummary());
item.setContent(content);
item.setTitle(tempContent.getTitle());
item.setLink(tempContent.getUrl());
item.setPubDate(tempContent.getCreatedDate());
items.add(item);
}
return items;
}
}
RSSController.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class RSSController {
@RequestMapping(value="/rssfeed", method = RequestMethod.GET)
public ModelAndView getFeedInRss() {
List<RSSMessage> items = new ArrayList<RSSMessage>();
RSSMessage content = new RSSMessage();
content.setTitle("Spring Tutorial");
content.setUrl("http://www.tutorialspoint/spring");
content.setSummary("Spring tutorial summary...");
content.setCreatedDate(new Date());
items.add(content);
RSSMessage content2 = new RSSMessage();
content2.setTitle("Spring MVC");
content2.setUrl("http://www.tutorialspoint/springmvc");
content2.setSummary("Spring MVC tutorial summary...");
content2.setCreatedDate(new Date());
items.add(content2);
ModelAndView mav = new ModelAndView();
mav.setViewName("rssViewer");
mav.addObject("feedContent", items);
return mav;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id = "rssViewer" class = "com.tutorialspoint.RSSFeedViewer" />
</beans>
在这里,我们已经创建了一个RSS提要POJO RSSMessage和一个RSS消息查看器,它扩展了 AbstractRssFeedView 并重写了它的方法。在RSSController中,我们生成了一个RSS提要样本。
Here, we have created a RSS feed POJO RSSMessage and a RSS Message Viewer, which extends the AbstractRssFeedView and overrides its method. In RSSController, we have generated a sample RSS Feed.
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动你的Tomcat服务器并确认你能使用一个标准浏览器从webapps文件夹访问其他网页。试试网址− http://localhost:8080/TestWeb/rssfeed 我们会看到以下这个屏幕。
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/rssfeed and we will see the following screen.
Spring MVC - Generate XML Example
以下示例展示如何使用 Spring Web MVC 框架生成 XML。首先,让我们有一个正在运行的 Eclipse IDE,并坚持以下步骤以使用 Spring Web 框架开发一个可动态创建表单的 Web 应用程序。
The following example shows how to generate XML using the Spring Web MVC Framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes User and UserController under the com.tutorialspointpackage. |
3 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User {
private String name;
private int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
}
UserController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<mvc:annotation-driven />
</beans>
在这里,我们创建了一个 XML 映射的 POJO User,并在 UserController 中,我们返回了 User。Spring 会根据 RequestMapping 自动处理 XML 转换。
Here, we have created an XML Mapped POJO User and in the UserController, we have returned the User. Spring automatically handles the XML conversion based on RequestMapping.
创建源文件和配置文件后,导出应用程序。右键单击应用程序,使用 Export → WAR File 选项,将你的 TestWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试一个 URL - http://localhost:8080/TestWeb/mahesh ,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen.
Spring MVC - Generate JSON Example
以下示例展示如何使用 Spring Web MVC 框架生成 JSON。首先,让我们有一个正在运行的 Eclipse IDE,并考虑以下步骤以使用 Spring Web 框架开发一个可动态创建表单的 Web 应用程序 -
The following example shows how to generate JSON using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework −
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java classes User, UserController under the com.tutorialspoint package. |
3 |
Download Jackson libraries Jackson Core, Jackson Databind and Jackson Annotations from maven repository page. Put them in your CLASSPATH. |
4 |
The final step is to create the content of all the source and configuration files and export the application as explained below. |
User.java
package com.tutorialspoint;
public class User {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
UserController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
TestWeb-servlet.xml
<beans xmlns = http://www.springframework.org/schema/beans"
xmlns:context = http://www.springframework.org/schema/context"
xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = http://www.springframework.org/schema/mvc"
xsi:schemaLocation =
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = com.tutorialspoint" />
<mvc:annotation-driven />
</beans>
在这里,我们创建了一个简单的 POJO User,并且在 UserController 中,我们返回了 User。Spring 会根据 RequestMapping 和类路径中存在的 Jackson jar 自动处理 JSON 转换。
Here, we have created a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath.
创建源文件和配置文件后,导出应用程序。右键单击应用程序,使用 Export → WAR File 选项,将你的 TestWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器,确保可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试一个 URL - http://localhost:8080/TestWeb/mahesh ,我们将看到以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen.
Spring MVC - Generate Excel Example
以下示例展示如何使用 Spring Web MVC 框架生成 Excel。首先,让我们有一个正在运行的 Eclipse IDE,并坚持以下步骤以使用 Spring Web 框架开发一个可动态创建表单的 Web 应用程序。
The following example shows how to generate Excel using the Spring Web MVC Framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes UserExcelView and ExcelController under the com.tutorialspoint package. |
3 |
Download the Apache POI library Apache POI from the maven repository page. Put it in your CLASSPATH. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
ExcelController.java
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class ExcelController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map<String,String> userData = new HashMap<String,String>();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
UserExcelView.java
package com.tutorialspoint;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
public class UserExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> userData = (Map<String,String>) model.get("userData");
//create a wordsheet
HSSFSheet sheet = workbook.createSheet("User Report");
HSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("Roll No");
header.createCell(1).setCellValue("Name");
int rowNum = 1;
for (Map.Entry<String, String> entry : userData.entrySet()) {
//create the row data
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(entry.getKey());
row.createCell(1).setCellValue(entry.getValue());
}
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class = "com.tutorialspoint.ExcelController" />
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "UserSummary" class = "com.tutorialspoint.UserExcelView"></bean>
</beans>
我们在此处创建了一个 ExcelController 和一个 ExcelView。Apache POI 库用于处理 Microsoft Office 文件格式,它会将数据转换为一个 excel 文档。
Here, we have created an ExcelController and an ExcelView. Apache POI library deals with Microsoft Office file formats and will convert the data to an excel document.
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试 http://localhost:8080/TestWeb/excel URL,我们将看到下面的屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/excel and we will see the following screen.
Spring MVC - Generate PDF Example
下面示例展示了如何使用 Spring Web MVC 框架生成一个 PDF。我们首先要在适当的位置获取一个 Eclipse IDE,然后按照下面的步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example shows how to generate a PDF using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create Java classes UserPDFView and PDFController under the com.tutorialspoint package. |
3 |
Download the iText library − iText from the maven repository page. Put it in your CLASSPATH. |
4 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
PDFController.java
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class PDFController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map<String,String> userData = new HashMap<String,String>();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
UserExcelView.java
package com.tutorialspoint;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
public class UserPDFView extends AbstractPdfView {
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> userData = (Map<String,String>) model.get("userData");
Table table = new Table(2);
table.addCell("Roll No");
table.addCell("Name");
for (Map.Entry<String, String> entry : userData.entrySet()) {
table.addCell(entry.getKey());
table.addCell(entry.getValue());
}
document.add(table);
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class = "com.tutorialspoint.PDFController" />
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "UserSummary" class = "com.tutorialspoint.UserPDFView"></bean>
</beans>
我们在此处创建了一个 PDFController 和 UserPDFView。iText 库用于处理 PDF 文件格式,它会将数据转换为一个 PDF 文档。
Here, we have created a PDFController and UserPDFView. iText library deals with the PDF file formats and will convert the data to a PDF document.
一旦你创建完资源文件和配置文件,导出你的应用程序。右键点击你的应用程序,使用 Export → WAR File 选项并在Tomcat的webapps文件夹中保存 TestWeb.war 文件。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你能够使用标准浏览器从 webapps 文件夹访问其他网页。我们还可以尝试 http://localhost:8080/TestWeb/pdf URL,如果一切顺利,我们将看到下面的屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. We can also try the following URL − http://localhost:8080/TestWeb/pdf and if all goes as planned, we will see the following screen.
Spring MVC - Integrate LOG4J Example
下面示例展示了如何使用 Spring Web MVC 框架集成 LOG4J。我们首先要在适当的位置获取一个 Eclipse IDE,然后按照下面的步骤使用 Spring Web 框架开发一个基于动态表单的 Web 应用程序。
The following example shows how to integrate LOG4J using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
Step |
Description |
1 |
Create a project with the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC - Hello World chapter. |
2 |
Create a Java class HelloController under the com.tutorialspointpackage. |
3 |
Download the log4j library LOG4J from the maven repository page. Put it in your CLASSPATH. |
4 |
Create a log4j.properties under the SRC folder. |
5 |
The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.tutorialspoint;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
private static final Logger LOGGER = Logger.getLogger(HelloController.class);
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
LOGGER.info("printHello started.");
//logs debug message
if(LOGGER.isDebugEnabled()){
LOGGER.debug("Inside: printHello");
}
//logs exception
LOGGER.error("Logging a sample exception", new Exception("Testing"));
model.addAttribute("message", "Hello Spring MVC Framework!");
LOGGER.info("printHello ended.");
return "hello";
}
}
log4j.properties
# Root logger option
log4j.rootLogger = DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file
log4j.appender.file = org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File = ${catalina.home}/logs/myapp.log
log4j.appender.file.MaxFileSize = 5MB
log4j.appender.file.MaxBackupIndex = 10
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
我们在此处将 LOG4J 配置为在 Tomcat 控制台和 &t; tomcat 主页 → 日志中 myapp.log 文件中记录详细信息。
Here, we have configured the LOG4J to log details on the Tomcat console and in the file present in &t; tomcat home → logs as myapp.log.
创建源文件和配置文件后,导出应用程序。右键单击应用程序,使用 Export → WAR File 选项,将你的 TestWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat’s webapps folder.
现在,启动 Tomcat 服务器并确保你能够使用标准浏览器从 webapps 文件夹访问其他网页。尝试 http://localhost:8080/TestWeb/hello URL,我们将看到 Tomcat 日志上的以下屏幕。
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL −http://localhost:8080/TestWeb/hello and we will see the following screen on Tomcat’s log.