Idea builds spring MVC Hello World detailed Getting Started tutorial

Source: Internet
Author: User

intro, actually from. NET to Java has been a few months, the project has done a lot, but many configurations are based on the company template or online tutorial than ignore the painting scoop, the simplest configuration and settings are not fully understood, is still small white users. Recently the project is not busy, re-combed the spring MVC configuration, the way to save, hoping to help other students ... Master Ignore ~ ~ ~

Catalogue
    • Create a new spring MVC project with idea
    • Set up run, debug related configurations
    • Import Spring MVC related class library
    • Add Controller
    • Modify Url-pattern (Web. xml)
    • Configuration Component-scan (Dispatcher-servlet.xml)
    • Configuration Viewresolver (Dispatcher-servlet.xml)
    • Add a view file (. jsp)
    • Pass value to View through Model

Create a new spring MVC project with idea

Create the project first, either from the cover page or from the main form.

New Project window, select the Additional class library "Spring MVC"

Select the project name and location

Finally click on the Finish button, idea will help you to download the required class library

After creation, the project has these files, mainly three XML files + one index.jsp

This JSP file must not be in the end, but do not panic before deleting

set up run, debug related configurations

After the project is built, it cannot be run directly, and the run and debug menus are gray and cannot be clicked.

Need to do a bit of running and debugging related configuration

As. NET to Java code Farm, sometimes really miss the universe first ide:visual Studio, according to the template created by the project rarely can not directly run, forget, do not say, continue to configure ...

Set the Server tab first

Click on the "Deployment" tab, continue setting,

Create artifact, and finally remember to click OK to save

Now, the menu item of Run ' Mvc-helloworld ' appears under the Run menu (shift+f10 Run, shift+f9 Debug)

The toolbar also has a run and debug button, and you can choose the way you want to run your project

Although we have not started to write code, but after all, idea helped us generate a JSP file, you can use this file to see if the site can open (index.jsp code below)

<%@ Page ContentType="Text/html;charset=utf-8"language="Java" %><HTML>  <Head>    <title>$Title $</title>  </Head>  <Body>$END $</Body></HTML>

Browser input Address http://localhost:8080/index.jsp

The project is not operational (in fact, from the run up, but also lacks a lot of configuration, continue to look back),

What's the situation? Of course to look at the log ... Click the "Tomcat Localhost Log" below to see where the problem is ...

Java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener

It means I can't find the Contextloaderlistener class.

Import Spring MVC related class library

Java, classnotfoundexception seems to be a very common exception, first check the corresponding jar package is not included in ...

Open Project Structure, with project-related configuration basically in a menu ...

After clicking on the "Artifacts" tab, there are a number of obvious hints, missing references to the spring MVC-related class library

Why do I feel like I'm not that good-looking, despite all the idea's reminders?

Fix the errors in the following ways, just pick one of them.

When the program is deployed, copy the Spring MVC related class library into the Lib folder

Rerun the project (SHIFT+F10 Run, shift+f9 Debug) ...

If you did not stop last time, this run may pop up this dialog box, select "Restart Server" and then "OK" ...

Visit http://localhost:8080/index.jsp once again

This time finally can see the point of content, at least the service started.

If you look at the log again, the original error is not

Add Controller

The site can be opened, but we're not MVC because there's no m, no V, no c.

Let's start with C (Controller) in MVC and continue to configure

Before you create a new controller, you must first build a package that SPRINGMVC cannot run under the default package, and build the package as follows.

I built the package name is:wormday.springmvc.helloworld

In fact, the package name is arbitrary, but must have ...

New Java class file under this package Hicontroller

The code is as follows

 Package Wormday.springmvc.helloworld; Import Org.springframework.stereotype.Controller; Import org.springframework.web.bind.annotation.RequestMapping, @Controller @requestmapping ("/hi")  Public class Hicontroller {    @RequestMapping ("/say")    public  String Say () {         return "/web-inf/jsp/say.jsp";    }}

If you're like me, you can't wait. To access the Controller's action address should be:

Http://localhost:8080/hi/say.form actually this time the result of the visit is 404, because there are a lot of configuration did not do ...

The annotation @requestmapping ("/hi") on the class specifies the front part of the URL path

Note @requestmapping ("/say") on the method specifies the last part of the URL path

You can also write annotations only on methods, such as @requestmapping ("/hi/say")

The end of the form is what ghost, and then look at the next section of Url-pattern ...

Modify Url-pattern (Web. xml)

Open Web\web-inf\web.xml File First

For servletmapping settings, this setting allows you to configure those types of URLs to be handled by those servlets.

    <servlet>        <servlet-name>dispatcher</servlet-name>        <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class>        <load-on-startup>1</ load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>dispatcher</ servlet-name>        <url-pattern>*.form</url-pattern>    </servlet-mapping>

Combining this XML, we can see that idea defaults to help me configure a servlet named dispatcher.

This servlet uses the Org.springframework.web.servlet.DispatcherServlet class to handle

The URL for this servlet is *.form

If you don't like me. Each MVC URL has a form behind it and can be changed to a slash

<url-pattern>/</url-pattern>

If you restart the program now, then continue to access Http://localhost:8080/hi/say

Found, still 404, and with each access, there is an error log in the server's Output window

Org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/hi/say] in Dispa Tcherservlet with name ' dispatcher '

The meaning is not to find the appropriate controller, not only to write the controller's code, but also to tell Spring (here is actually the dispatcher servlet) where to find these controllers ...

As a validation, you can add a breakpoint to the controller and then refresh the page, and the program is not executed in the controller.

So now it's time to modify another configuration file, Dispatcher-servlet.xml.

configuration Component-scan (dispatcher-servlet.xml)

Component-scan is telling the servlet where to find the controller.

Open Dispatcher-servlet.xml

In the already existing <beans></beans> center Plus

<context:component-scan base-package= "wormday.springmvc.helloworld"/>

BASE-PACKAGE Specifies the package that holds the controller.

After you finish this step, restart the project and visit Http://localhost:8080/hi/say again

This should still be a 404 error, but it's a big step forward than the 404 mistake just now.

After all, this controller has been executed, if the breakpoint has not been removed, you can verify to see

This time it was because the view was "/web-inf/jsp/say.jsp" (we did just tell him the location, but never created the file).

Again, Spring MVC if can not find controller or view will be reported 404 error, specifically find out who, to specific analysis, fortunately, is generally easy to distinguish out.

There's a problem with this place. In general, the return value of the controller code is in the form of a string "say", which does not require a. JSP, nor does it require a path in the front, such as

But if you write this now, you will report a strange 500 error instead of 404.

HTTP Status 500-circular view path [say]: would dispatch back to the current handler URL [/hi/say] again. Check your Viewresolver setup! (Hint:this May is the result of a unspecified view, due to default view name generation.)

The reasons are:

    1. We have not configured viewresolver,spring will default to help us generate a, automatically generated and not configured the view default prefix and suffix (for this project is "/web-inf/jsp/" and ". JSP"), So we can only write absolute paths, and we'll talk about how to configure
    2. If it is not a "/" path (that is, relative path), spring will be the current path to match up, the current controller path is "/hi/" with the View path "say", became "/hi/say", controller execution results sent to view, This view is also the controller itself, spring found that this is a dead loop, no longer execute the direct report above the error
    3. This error I again controller unit test also encountered, the principle knows how to solve the

However, the absolute path to the view must now be set because we have not configured the configuration Viewresolver, which will be specifically mentioned in the back.

Add a view file (. jsp)

This is not a good explanation, just let spring where to find this view, you create this view where

If you can't find it, he will make a rough 404 error, according to the code I wrote, the creation position should be in.

In fact, spring does not limit you have to create under Web-inf, but it is more secure, because Web-inf directory users are not directly accessible, after all, there may be some code in view

<%@ Page ContentType= "Text/html;charset=utf-8" language= "java"%>   

Visit Http://localhost:8080/hi/say again

Finally no more error, it seems the controller also found the corresponding view

configuration Viewresolver (dispatcher-servlet.xml)

Do you remember that the controller return value must be the absolute path to view this thing? Normally, we wouldn't write that.

Most of the tutorials on the web only return the name of the view, such as

The reason is that the following code is typically specified on the dispatcher-servlet.xml.

    <!--Specify the View resolver -    <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver">        <!--the path to the view -        < Propertyname= "prefix"value= "/web-inf/jsp/"/>        <!--View name suffix -        < Propertyname= "suffix"value= ". jsp"/>    </Bean>

CLASS specifies viewresolver implementation classes, which you can use without viewresolver depending on the situation, which is specified here Org.springframework.web.servlet.view.InternalResourceViewResolver

I did not specify, the default is this class

The prefix and suffix in the back are relatively simple, so let's see.

Remember to modify the return value of the controller synchronously after you change the XML. or 404 again.

Pass value to View through Model

Through the above operation, has completed the MVC (V and C), M has not seen the shadow, let us continue to modify

Open the controller that you just defined, which is the Hicontroller.java file

Modify the following (I have highlighted the change point)

 PackageWormday.springmvc.helloworld;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model; //  import a model class here Importorg.springframework.web.bind.annotation.RequestMapping, @Controller @requestmapping ("/hi") Public classHicontroller {@RequestMapping ("/say")     PublicString say (model model) { //  parameter passed in model Model.addattribute ("name", "Wormday"); //  Specify the value of the model Model.addattribute ("url", "http://www.cnblogs.com/wormday/p/8435617.html"); //  Specify the value of the model         return"Say"; }}

Then open the view, that is, the say.jsp file, modify the following

<%@ Page ContentType="Text/html;charset=utf-8"language="Java" %><HTML><Head>    <title>Title</title></Head><Body>Hello World,${name} <BR/>${url}</Body></HTML>

The relationship between the two is not explained, then rerun the project, refresh the page

One of the simplest MVC projects to complete!!!

Idea builds spring MVC Hello World detailed Getting Started tutorial

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.