Home> Java> javaTutorial> body text

A brief introduction to Spring MVC

巴扎黑
Release: 2017-09-08 09:46:00
Original
2463 people have browsed it

Spring MVC is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow. Today we will start by writing a Spring MVC HelloWorld. Let us see how to set up a Spring MVC environment and run the program. Friends who are interested can learn together.

What is Spring MVC

Spring MVC is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow. The Spring framework provides full-featured MVC modules for building web applications. Using Spring's pluggable MVC architecture, when using Spring for WEB development, you can choose to use Spring's SpringMVC framework or integrate other MVC development frameworks, such as Struts1, Struts2, etc.

Today we will start by writing a Spring MVC HelloWorld. Let us see how to set up a Spring mvc environment and run the program.

Software parameters

Eclipse: Mars.1 Release (4.5.1)
Tomcat: 8.0.36
JDK: 1.8.0_60
Spring-framework: 4.0.4.RELEASE

##New project

File-New -Other, select Dynamic web project

## After the project is built, the directory structure is as follows:


Import jar packageWe develop based on the Spring mvc framework and need to rely on the following spring jar package:

spring-aop-4.0.4.RELEASE.jar spring-beans-4.0.4.RELEASE.jar spring-context-4.0.4.RELEASE.jar spring-core-4.0.4.RELEASE.jar spring-expression-4.0.4.RELEASE.jar spring-web-4.0.4.RELEASE.jar spring-webmvc-4.0.4.RELEASE.jar commons-logging-1.1.1.jar(用来打印log)
Copy after login

Create a new lib folder in the WEB-INF directory and put the above jar package into it.


Configuration files and writing code

##
web.xml(WEB-INF下)     springDispatcherServlet org.springframework.web.servlet.DispatcherServlet   contextConfigLocation classpath:springmvc.xml  1   springDispatcherServlet /  
Copy after login

Note: 1. For line12-15 For configuring the location and name of the spring mvc configuration file, here is a description of a new springmvc.xml configuration file

 2. We can also not create a new springmvc.xml, but use the default, default configuration file The format is /WEB-INF/[servlet-name]-servlet.xml, which corresponds to springDispatcherServlet-servlet.xml

 3. The servlet-mapping here represents the interception mode, here is "/", Indicates the interception of all requests, including static resources such as html, js, jpg, etc. At this time, a 404 error will be reported when accessing static resources. How to solve it will be introduced later

Springmvc.xml (under scr)

Create a new springmvc.xml in the src directory

         
Copy after login

Note: 1. line12 represents the scope of spring monitoring, which is under com.jackie.springmvc

2. Line15-18 adds a view parser to put the handler in the controller The structure is parsed into the actual physical view. This must be parsed with the controller class. See below for details.


HelloWorld.java(com.jackie.springmvc.handlers下) package com.jackie.springmvc.handlers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloWorld { /** * 1. 使用RequestMapping注解来映射请求的URL * 2. 返回值会通过视图解析器解析为实际的物理视图, 对于InternalResourceViewResolver视图解析器,会做如下解析 * 通过prefix+returnVal+suffix 这样的方式得到实际的物理视图,然后会转发操作 * "/WEB-INF/views/success.jsp" * @return */ @RequestMapping("/helloworld") public String hello(){ System.out.println("hello world"); return "result"; } }
Copy after login


Note:

1. First, add "Controller" in front of the class " annotation, indicating that it is a spring controller. Here a method hello()

will be written. 2. There is a @RequestMapping above the hello method, which is used to match the path of the request. For example, the matching request path here is " http://localhost:8080/springTest/springmvc/helloworld", that is, when the tomcat service is started and this URL is entered in the browser, if there is a break point in this method, it will jump into this method.

3. The result of this return is not random. The returned string is matched with line15-18 in springmvc.xml above. Prefix and suffix are declared in springmvc.xml, and they are sandwiched here The thing between the two is the string returned here, so after executing this method, we can get the request resource path "/WEB-INF/views/success.jsp". This success.jsp needs to be created by us

Index.jsp (under WebContent)

Before creating a new success.jsp, we need to have an entrance, which is the index.jsp here

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>     Insert title here 
hello world
Copy after login

When accessing index.jsp, a hyperlink will be displayed on the page. After clicking the hyperlink, the address in the url will jump, starting from "http://localhost:8080/springTest/index .jsp" jumps to "http://localhost:8080/springTest/helloworld", and this url request will enter the hello method in HelloWorld because it matches "/helloworld" on this method.

Success.jsp (under WEB-INF/views)

This page is the corresponding page after the request is successful

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>     Insert title here 

Success Page

Copy after login

So far, we have completed the development of the HelloWorld program based on the Spring mvc framework, including the dependent jar packages, configuration files, controller code writing and display page writing, etc.

除此以外,再介绍下整个配置过程中遇到的一些小问题:

1. tomcat服务器的添加

  从前面的介绍可以看出,我们的程序是通过浏览器发请求来获取想要的页面,那么这里就免不了要有一个web服务器,这里就是tomcat。

  首先你需要下载个tomcat,然后在eclipse->windows->preference->servers中绑定这个tomcat服务器;

  其次你需要在你新建的spring mvc项目中添加tomcat的支持,否则在新建的jsp文件中会提示报错“The superclass javax.servlet.http.HttpServlet was not found on the Java Build Path”

  右键项目->build path->configure build path->add library->server runtime, 选择你的tomcat即可

  有了tomcat服务器,你就可以在index.jsp上右键run on server,选择你的tomcat服务器,这样就可以启动tomcat服务,帮助你完成网页的请求和响应操作。

2. spring mvc如何访问静态资源

  关于使用spring mvc处理静态资源,比如html(发现之前的springmvc.xml中 定义为jsp结尾就可以成功跳转,但是如果改为html并在web-inf下面新建了html文件后,并将suffix这里的".jsp"改为".html",无法跳转到想要的html页面,并且给出404错误,同时console给出错误信息为:No mapping found for HTTP request with URI [/springTest/WEB-INF/views/result.html] in DispatcherServlet)

  最后发现是需要让spring明确要处理静态资源,原来的web.xml中只有


 springDispatcherServlet / 
Copy after login

  其匹配的都是controller中类似@RequestMapping("/springmvc/helloworld")这样的注解配置的请求,而对于类似html/css/jpg等资源的访问就会得不到,所以需要在web.xml中加入以下类型的支持


 default *.css   default *.gif   default *.jpg   default *.js   default *.html 
Copy after login

  这样就可以保证spring 能够拦截并处理静态资源

  这里将HelloWorld.java中的hello方法改为:


@RequestMapping("/helloworld") public String hello(){ System.out.println("hello world"); return "Jackie"; }
Copy after login

Springmvc.xml改为:


class="org.springframework.web.servlet.view.InternalResourceViewResolver">   
Copy after login

The above is the detailed content of A brief introduction to Spring MVC. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!