Spring MVC Beginner

Source: Internet
Author: User
Tags tomcat server

Transferred from: http://www.cnblogs.com/bigdataZJ/p/springmvc1.html

From today onwards, prepare to take a good look at spring MVC.

Although the first program to learn Java from--helloworld to date, has been several years. At that time, I looked for information, watching video, learning Java input and output stream, multi-threading, network programming, and so on, and three framework (Struts, Hibernate, Spring) basically just opened the head out of the internship, especially for Spring is not a systematic study, Although in the internship at the time by looking at the project, basically understand the Spring MVC programming framework is going to meet the requirements of how to write code, where to write code, but still lack a system of understanding. It's a bit cramped for problems involving some spring file configurations or how they work. So, recently, you're ready to learn Spring MVC, which is a big step in enterprise development today.

What is Spring MVC

Spring MVC is a follow-on product of springframework and has been integrated into spring Web flow. The Spring framework provides a full-featured MVC module for building WEB applications. Using spring's pluggable MVC architecture, you can choose to use Spring's SPRINGMVC framework or integrate with other MVC development frameworks, such as STRUTS1,STRUTS2, when using spring for web development.

Start by writing a spring MVC HelloWorld today, and let's see how to build 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:

Importing JAR Packages

Our development based on the Spring MVC Framework requires a dependent 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 (used to print log)

Create a new Lib folder under the Web-inf directory and put the jar package above.

The jar package can be downloaded here.

Configuration files and writing code

Web. XML (Web-inf)

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 3 Xmlns= "Http://java.sun.com/xml/ns/javaee" 4 xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_2_5.xsd "5 id=" webapp_id "version=" 2.5 "> 6 7 <!--configuration DISPATCHCERSERVL ET--8 <servlet> 9 <servlet-name>springdispatcherservlet</servlet-name>10 <s Ervlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>11 <!--configuration with spring MVC             Location and name of the file-->12 <init-param>13 <param-name>contextconfiglocation</param-name>14 <param-value>classpath:springmvc.xml</param-value>15 </init-param>16 <load -on-startup>1</load-on-startup>17 </servlet>18 <servlet-mapping>20 <servlet -name>springdispatcherservlet</servlet-name>21 <url-pattern>/</url-pattern>22 </servlet-mapping>23 </web-app&gt ;

Note: 1. Line12-15 the location and name of the configuration file used to configure Spring MVC, where a new springmvc.xml configuration file is created

2. We can also not create a new springmvc.xml, but with the default, the default configuration file format is/web-inf/[servlet-name]- Servlet.xml, that corresponds to springdispatcherservlet-servlet.xml here.

3. Here the servlet-mapping represents the interception mode, here is the "/", indicating the interception of all requests, including static resources such as HTML, JS, JPG and so on. At this time, the access to the static resources will be reported 404 error. about how to fix the following will be introduced

Springmvc.xml (SCR)

Create a new springmvc.xml under the SRC directory

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3 xmln S:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context= "Http://www.springframework.org/schema/context "5 xmlns:mvc=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC "6 xsi:schemalocation=" Http://www.springframework.org/sch Ema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 Http://www.springframework.org/schema/co ntext Http://www.springframework.org/schema/context/spring-context-4.0.xsd 8 Http://www.springframework.org/schem A/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> 9 <!--configure automatically scanned packages-         ->12 <context:component-scan base-package= "Com.jackie.springmvc" ></context:component-scan>13 <!--Configure the view resolver to resolve the handler method return value to the actual physical view-->15 <bean class= "ORG.SPRINGFRAMEWORK.WEB.SERVLET.V Iew. Internalresourceviewresolver">16 <property name =" prefix "value="/web-inf/views/"></property>17 <property N ame = "suffix" value = ". jsp" ></property>18 </bean>19 </beans>

Note: 1. Line12 represents the range of spring listening, which is under COM.JACKIE.SPRINGMVC

2. Line15-18, is to add a view parser, used in the controller handler structure to the actual physical view, this should be combined with the Controller class to parse, see below.

Helloworld.java (Com.jackie.springmvc.handlers)

1 package com.jackie.springmvc.handlers; 2  3 import org.springframework.stereotype.Controller; 4 Import org.springframework.web.bind.annotation.RequestMapping; 5  6 @Controller 7 public class HelloWorld {8  9     /**10      * 1. Use the requestmapping annotation to map the URL11 of the request      * 2. The return value is The diagram parser resolves to the actual physical view, and for the Internalresourceviewresolver view parser, it parses the      actual physical view through Prefix+returnval+suffix. Then the action is forwarded.      * "/web-inf/views/success.jsp"      * @return15      */16     @RequestMapping ("/helloworld") 17 Public     String Hello () {         System.out.println ("Hello World"); "         success";     }21}

Note: 1. The first step is to add a "controller" annotation to the front of the class, indicating that it is a spring control, where a method hello () is written.

2. There is a @requestmapping above the Hello method, which is the path used to match the request, for example, where the matching request path is "Http://localhost:8080/springTest/springmvc/helloworld", That is, when the Tomcat service starts, when the browser enters the URL, if this method breaks the point, it will jump into the method.

3. The result of this return is not to be written in a random The returned string is in conjunction with the line15-18 in the above springmvc.xml, Springmvc.xml declares prefix and suffix, and the folder between the two is the string returned here, so after executing this method, we can get such a request resource path "/web-inf/views/success.jsp", this success.jsp is for us to create a new

Index.jsp (webcontent)

Before we create a new success.jsp, we need to have a portal, the index.jsp here.

1 <%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2     pageencoding=" UTF-8 "%> 3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 4 

When you visit index.jsp, a hyperlink is displayed on the page, and when you click the hyperlink, the address in the URL jumps to the "http://localhost:8080/springTest/index.jsp" to "http// Localhost:8080/springtest/helloworld ", and this URL request enters the Hello method in HelloWorld because it matches the"/helloworld "on the method.

Success.jsp (Web-inf/views)

This page is the corresponding page after the request is successful

success.jsp

At this point, we have completed the development of the HelloWorld program based on the spring MVC framework, including the jar package to be relied on, the configuration file, the writing of the Controller code and the writing of the presentation page.

In addition, we introduce some of the minor problems encountered during the entire configuration process:

1. Adding a Tomcat server

As can be seen from the previous introduction, our program is to request through the browser to obtain the desired page, then there is inevitably a Web server, this is tomcat.

First you need to download a tomcat and then bind the Tomcat server in Eclipse->windows->preference->servers;

Next you need to add Tomcat support to your new spring MVC project, or you will be prompted with an error in the new JSP file "The superclass Javax.servlet.http.HttpServlet is not found on The Java Build Path "

Right-click Project->build path->configure build Path->add library->server Runtime, choose your Tomcat

With the Tomcat server, you can right-click on the server on the index.jsp and select your Tomcat server, so you can start the Tomcat service and help you complete the request and response of the Web page.

2. How spring MVC accesses static resources

About using spring MVC to handle static resources, such as HTML (Springmvc.xml in the previous <property name = "suffix" value = ". JSP" ></property> The end of the JSP is defined as a successful jump, but if you change to HTML and create a new HTML file under Web-inf, and change the ". jsp" suffix here to ". html", you cannot jump to the desired HTML page and give a 404 error, At the same time, the console gives the error message: No mapping found for HTTP request with URI [/springtest/web-inf/views/result.html] in Dispatcherserv)

Finally, it is necessary to let spring explicitly deal with static resources, the original web. XML only

1 <servlet-mapping>2     <servlet-name>springdispatcherservlet</servlet-name>3     < Url-pattern>/</url-pattern>4 </servlet-mapping>

It matches the request for an annotation configuration like @requestmapping ("/springmvc/helloworld") in the controller, and access to resources like Html/css/jpg will not be available, Therefore, the following types of support need to be added to Web. xml

1 <servlet-mapping> 2      <servlet-name>default</servlet-name> 3      <url-pattern>*.css </url-pattern> 4 </servlet-mapping> 5  6 <servlet-mapping> 7       <servlet-name>default </servlet-name> 8       <url-pattern>*.gif</url-pattern> 9 </servlet-mapping>10 < servlet-mapping>12     <servlet-name>default</servlet-name>13      <url-pattern>*.jpg</ url-pattern>14 </servlet-mapping>15 <servlet-mapping>17      <servlet-name>default</ servlet-name>18      <url-pattern>*.js</url-pattern>19 </servlet-mapping>20 < servlet-mapping>22       <servlet-name>default</servlet-name>23       <url-pattern>*.html </url-pattern>24 </servlet-mapping>

This ensures that spring can intercept and process static resources

Here, the Hello method in Helloworld.java is changed to:

@RequestMapping ("/helloworld") public    String Hello () {        System.out.println ("Hello World");        return "Jackie";}

Springmvc.xml instead:

class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >            <property name = "prefix" Value= "/web-inf/views/" ></property>            <property name = "suffix" value = ". jpg" ></property> </bean>

means we have access to JPG static picture resources.

(If you see a picture of discomfort, please use the likes to alleviate the symptoms.)

Spring MVC Beginner

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.