欢迎使用Spring Mvc示例。什么时候回来SpringMVC教程,我解释了如何使用Spring工具套件创建Spring Mvc应用程序。但是今天,我将使用maven和Eclipse创建一个基本的helloworldSpring Mvc应用程序。
目录
Spring MVC示例
Spring Mvc基于模型-视图-控制器体系结构。下图显示了SpringMVC架构在一个高层次上。
DispatcherServlet
is the front controller class to take all requests and start processing them. We have to configure it in web.xml file. It’s job is to pass request to appropriate controller class and send the response back when view pages have rendered the response page.
HomeController.java
will be the single controller class in our spring mvc example application.
home.jsp
, user.jsp
are the view pages in our spring mvc hello world example application.
User.java
will be the only model class we will have in our spring mvc example web application.
SpringMVC示例Hello World Eclipse项目
下图显示了Eclipse中的SpringMVC示例项目。
让我们开始,从头开始创建我们的项目。
Spring Mvc示例Eclipse项目设置
由于它是一个web应用程序,我们希望使用maven进行依赖关系管理,因此首先我们必须创建一个动态web应用程序,然后将其转换为maven项目。下面的图片展示了如何做到这一点,并准备好我们的项目框架结构。
右键单击project explorer窗口并单击“;新建->动态Web项目”;,如下图所示。
在下一个弹出页面中提供名称为“;Spring Mvc example”;在下一个弹出页面中,不需要更改其余内容。
在下一页中,将源文件夹提供为&&8220;src/main/java&8221;。在添加此文件夹之前,您可能需要从列表中删除“;src”;文件夹。
接下来是web模块页面,提供应用程序的上下文根作为“;spring mvc example”;,并确保选中“;Generateweb.xml文件部署描述符和选项。
单击Finish,您将在eclipseprojectexplorer中有一个新的动态Web项目。
将动态Web项目转换为Maven项目
我们希望使用maven轻松地管理Spring Mvc依赖关系。因此,让我们将web项目转换为maven。
右键单击该项目,然后选择&&8220;配置->;转换为Maven项目&8221;。
下一步提供pom.xml文件配置如下所示。
我们的maven web应用程序项目框架代码已经准备好了。现在我们可以开始对它进行更改,并创建我们的Spring Mvchelloworld示例应用程序。
Spring MVC依赖关系到pom.xml文件
我们需要在pom.xml文件,还添加了servlet api、jspapi和jstl依赖项。我们的决赛pom.xml文件文件如下所示。
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.spring.mvc</groupId>
<artifactId>spring-mvc-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring MVC Example</name>
<description>Spring MVC Hello World Example</description>
<!-- Add Spring Web and MVC dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName> <!-- added to remove Version from WAR file -->
</build>
</project>
注意finalName
configuration in build, so that our WAR file name doesn’t have version details.
当项目由Eclipse构建时,您将注意到maven依赖项部分中显示的所有jar。
Spring MVC DispatcherServlet作为前控制器
我们必须将Spring Mvc框架添加到我们的web应用程序中,为此我们需要配置DispatcherServlet
in web.xml as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>spring-mvc-example</display-name>
<!-- Add Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
contextConfigLocation
init-param is used to provide the location of spring bean configuration file.
Spring Mvc示例Bean配置文件
下一步是创建Spring Bean配置文件spring-servlet.xml
as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet"s request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<context:component-scan base-package="com.journaldev.spring" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
>
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
有三种重要的配置。
annotation-driven
tells DispatcherServlet to look for Controller classes using@Controller
注解.context:component-scan
tells DispatcherServlet where to look for controller classes.InternalResourceViewResolver
bean configuration to specify location of view pages and suffix used. Controller class methods return name of the view page and then suffix is added to figure out the view page to use for rendering the response.
Spring MVC控制器类
我们有一个控制器类来响应两个uri–;“;/”;用于主页和“;/user”;,用于用户页。
package com.journaldev.spring.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.model.User;
@Controller
public class HomeController {
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
System.out.println("Home Page Requested, locale = " + locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model) {
System.out.println("User Page Requested");
model.addAttribute("userName", user.getUserName());
return "user";
}
}
注意,为了简单起见,我没有使用任何日志框架,比如日志4J.
Spring MVC模型类
我们有一个带有单个变量的简单模型类及其getter setter方法。它是一个简单的POJO类。
package com.journaldev.spring.model;
public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Spring Mvc视图页面
我们有两个查看页面定义如下。
home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello world!</h1>
<P>The time on the server is ${serverTime}.</p>
<form action="user" method="post">
<input type="text" name="userName"><br> <input
type="submit" value="Login">
</form>
</body>
</html>
user.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Home Page</title>
</head>
<body>
<h3>Hi ${userName}</h3>
</body>
</html>
注意,Spring Mvc负责将表单变量映射到模型类变量,这就是为什么我们在这两个地方都有相同的变量名。
就这样,我们的Spring Mvc示例项目已经准备好部署和测试了。
Spring Mvc Eclipse项目部署
我们可以使用Eclipse export as WAR file选项将其直接部署到任何正在运行的tomcat服务器webapps目录中。但是,您也可以使用命令行来构建项目,然后将其复制到您喜欢的servlet容器部署目录中。
参考文献:官方网页