怎么用Spring MVC创建Web应用

技术怎么用Spring MVC创建Web应用这篇文章给大家分享的是有关怎么用Spring MVC创建Web应用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。为了把Spring MVC运用到We

本文是关于如何用Spring MVC创建Web应用程序。我觉得边肖很实用,就和大家分享一下作为参考。让我们跟着边肖看一看。

为了将Spring MVC应用于Web应用,我们首先需要在以下地址下载与操作系统对应的Spring软件包

https://repo . spring . io/libs-release-local/org/spring framework/spring/

以下网站还提供了Spring软件包的下载:

www.javathinker.net/javaweb.jsp

1.1 建立Spring MVC的环境

将Spring软件包Spring-framework-x . release-dist . zip解压到本地,将libs目录下的JAR文件复制到WEB应用的WEB-INF/lib目录下。图1-1展示了基于Sping MVC的helloapp应用程序的目录结构。

怎么用Spring  MVC创建Web应用

图1-1 hello app应用程序的目录结构

1.2 创建视图

Spring MVC的视图是一组包含Spring标签的JSP文件。在本例中,视图图层包括两个文件:student.jsp和result.jsp。Student.jsp负责为客户生成一个HTML表单来输入学生信息。student.jsp的HTML表单由网址为“/helloapp/addStudent”的网络组件处理:

form : form method=' POST ' action='/hello app/addStudent '

/form:formstudent.jsp使用Spring标签库中的标签。以下程序1-1是student.jsp的代码。

1-1常规student.jsp

% @ PageContentType=' text/html;charset=UTF-8 '语言='java'%

% @ tagliburi=' http://www . spring framework . org/tags/form '

前缀='form'%

超文本标记语言

title springmvcssample/title

/head

身体

h3StudentInformation/h3

form : form method=' POST ' action='/hello app/addStudent '

桌子

tr

TD form : label path=' name ' name/form : label/TD

n

bsp;<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>

以上student.jsp代码中的<form:form>、<form:label>和<form:input>标签来自于Spring标签库,用来生成HTML表单。
result.jsp负责显示客户端输入的学生信息,例程1-2是它的源代码。
例程1-2  result.jsp

<%@page contentType = "text/html;charset = UTF-8" language = "java" %>
<%@page isELIgnored = "false" %>
<%@taglib uri = "http://www.springframework.org/tags/form" 
                                                  prefix = "form"%>
<html>
  <head>
   <title>Spring MVC Sample</title>
  </head>
  <body>
    <h3>Submitted Student Information</h3>
    <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>

1.3  创建模型
在Spring MVC的模型层,可以创建表示业务数据或实现业务逻辑的JavaBean组件。以下例程1-3的Student类是一个JavaBean,它表示本范例应用的业务数据。
例程1-3  Student.java

package mypack;
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;
  }
}

对于非常简单的JavaWeb应用,业务逻辑也可以直接由控制器层的Controller来完成。在本例中,业务逻辑将直接由StudentController来完成。

1.4  创建Controller组件
下面创建一个类名叫StudentController的Controller组件,参见例程1-4。StudentController类有两个方法:
   student()方法:对应的URL为“/student”,请求方式为HTTP GET方式。
   addStudent()方法:对应的URL为“/addStudent”,请求方式为HTTP POST方式。
例程1-4  StudentController.java

package mypack;
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";
  }
}

当客户端以HTTP GET方式请求访问http://localhost:8080/helloapp/student,Spring MVC的DispatcherServlet就会把请求转发給StudentController的student()方法,这个方法返回一个ModelAndView对象,它表示把模型数据和视图绑定在一起的对象。在本例中,“new ModelAndView("student", "command", new Student())”中的三个参数的含义如下:
   第一个参数“student”表示视图组件的逻辑名字为“student”,实际上对应WEB-INF/jsp/student.jsp文件。本章1.5节会介绍如何在Spring MVC配置文件中配置这种对应关系。
   第二个参数“command”表明逻辑名为“student”的视图组件中的HTML表单需要与第三个参数指定的Student对象绑定。
   第三个参数“new Student()”提供了一个新建的Student对象。Spring MVC框架会负责把客户端在HTML表单中输入的数据填充到这个Student对象中。

DispatcherServlet接收到StudentController的student()方法返回的ModelAndView对象后,会把请求再转发給逻辑名字为“student”的视图组件,即WEB-INF/jsp/student.jsp文件。
以下图1-2显示了Spring MVC框架响应“/student”URL的流程。
怎么用Spring MVC创建Web应用

图1-2  Spring MVC框架响应“/student”URL的流程

student.jsp生成的网页如图1-3所示。
怎么用Spring MVC创建Web应用
图1-3  student.jsp生成的网页

客户在图1-3所示的HTML表单中输入学生的相关信息,然后提交表单,这时浏览器会以POST方式请求访问“/helloapp/addStudent”URL。
Spring MVC框架的DispatcherServlet接受到客户端的请求后,先把包含学生信息的HTML表单数据填充到表示模型数据的Student对象中,接下来DispatcherServlet就把请求转发給StudentController的addStudent()方法。
StudentController的addStudent()方法读取Student对象的各个属性,再把它存放到一个ModelMap对象中:

//model变量为ModelMap类型
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());

StudentController的addStudent()方法接下来返回一个字符串“result”,它是一个Web组件的逻辑名字,实际上对应WEB-INF/jsp/result.jsp文件。DispatcherServlet再把请求转发給result.jsp文件。result.jsp文件中的${name}、${age}和${id}标记会显示由StudentController存放在ModelMap对象中的name、age和id属性的值。由此可见,控制层可以借助ModelMap对象向视图层传递数据。
以下图1-4是result.jsp返回的包含学生信息的网页。
怎么用Spring MVC创建Web应用
图1-4  result.jsp返回的包含学生信息的网页

以下图1-5显示了Spring MVC框架响应“/helloapp/addStudent”URL的流程。
怎么用Spring MVC创建Web应用

图1-5  Spring MVC框架响应“/helloapp/addStudent”URL的流程

1.5  创建web.xml文件和Spring MVC 配置文件
在web.xml文件中,应该对Spring MVC框架的中央控制枢纽DispatcherServlet进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0" >
  <display-name>Spring MVC Sample</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>

以上代码为DispatcherServlet映射的URL为“/”,这意味着所有访问helloapp应用的客户请求都会先由DispatcherServlet来预处理,然后再由DispatcherServlet转发给后续组件。
以上代码为DispatcherServlet设置的Servlet名字为“HelloWeb”,与此对应,必须为Spring MVC框架提供一个名为HelloWeb-servlet.xml配置文件,它也存放在WEB-INF目录下。例程1-5是HelloWeb-servlet.xml文件的代码。
例程1-5  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 = "mypack" />
  <bean class =  "org.springframework.web.servlet.view
                        .InternalResourceViewResolver">
    <property name = "prefix" value = "/WEB-INF/jsp/" />
    <property name = "suffix" value = ".jsp" />
  </bean>
</beans>

以上代码指定负责解析视图组件的逻辑名字的类为“InternalResourceViewResolver”。它的prefix和suffix属性分别设定了视图文件的前缀与后缀。
例如,对于StudentController的addStudent()方法返回的逻辑名字“result”,将被解析为“/WEB-INF/jsp/result.jsp”文件。
再例如,StudentController的student()方法返回一个ModelAndView对象,它包含的视图组件的逻辑名字为“student”,“student”将被解析为“/WEB-INF/jsp/student.jsp”文件。

1.6  运行helloapp应用
按以上步骤创建好helloapp应用后,就可以启动Tomcat服务器,运行helloapp应用。在源代码包的sourcecode/helloapp目录下,提供了这个应用的所有源文件,可以直接将整个helloapp目录拷贝到<CATALINA_HOME>/webapps目录下,就会发布这个应用。
通过浏览器访问:
http://localhost:8080/helloapp/student
就可以访问helloapp应用了。

感谢各位的阅读!关于“怎么用Spring MVC创建Web应用”这篇文章就分享到这里了,希望

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/112714.html

(0)

相关推荐

  • 轻量云服务器有什么优势

    技术轻量云服务器有什么优势随着现在对于云服务器的使用门槛不断降低,不少机房服务商都推出了自己的轻量云服务器,而相比云服务器,轻量云服务器的优势主要是入门简单,使用便捷,单击鼠标即可快速搭建云端环境或构建应用,开箱即用,那

    礼包 2021年12月10日
  • 加拿大动物,加拿大的代表动物是什么

    技术加拿大动物,加拿大的代表动物是什么加拿大的国兽,海狸(英语叫BEAVER),也叫河狸,它是一种躯体肥胖的啮齿类动物,外型酷似大老鼠。海狸身上有两宝,一种是用于制作香水的原料,属于海狸性腺分泌的液体;另一种是海狸油光水

    生活 2021年10月27日
  • 如何解析Java 数据结构中时间复杂度与空间复杂度

    技术如何解析Java 数据结构中时间复杂度与空间复杂度这篇文章给大家介绍如何解析Java 数据结构中时间复杂度与空间复杂度,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。算法效率在使用当中,算法效率分

    攻略 2021年11月5日
  • 如何在Azure上创建Web App部署Asp.NET Core应用

    技术如何在Azure上创建Web App部署Asp.NET Core应用本篇文章为大家展示了如何在Azure上创建Web App部署Asp.NET Core应用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章

    攻略 2021年11月19日
  • 如何使用Spring Session 与 Spring security 完成网站登录改造

    技术如何使用Spring Session 与 Spring security 完成网站登录改造如何使用Spring Session 与 Spring security 完成网站登录改造,相信很多没有经验的人对此束手无策,

    攻略 2021年11月9日
  • Mybatis有什么用

    技术Mybatis有什么用这篇文章将为大家详细讲解有关Mybatis有什么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。简介MyBatis的前身叫iBatis,本是apache的一个

    攻略 2021年11月25日