IDEA Spring MVC Hello World getting started, springmvc

Source: Internet
Author: User

IDEA Spring MVC Hello World getting started, springmvc
Introduction, in fact, from. NET to Java has been around for several months, and many projects have been done. However, many configurations are based on company templates or online tutorials, I do not fully understand the simplest configurations and settings, but I am still a white-haired user. Recently, the project was not busy. I reviewed Spring MVC configurations and saved them. I hope they can help other students ...... Master ignores ~~~

 

Directory
  • Use IDEA to create a Spring MVC Project
  • Configure running and debugging
  • Import Spring MVC-related Class Libraries
  • Add Controller
  • Modify url-pattern (web. xml)
  • Configure component-scan (dispatcher-servlet.xml)
  • Configure ViewResolver (dispatcher-servlet.xml)
  • Add view file (. jsp)
  • Pass value to View through Model

 

Use IDEA to create a Spring MVC Project

Create a project first. You can create a project from the cover or main form.

In the "New Project" window, select the additional class library "Spring MVC"

 

Select the project name and storage location

Click Finish to download the required class library.

After the project is created, these files are mainly used to add three xml files and one index. jsp file.

This jsp file is definitely not needed at last, but you should not try to delete it in a hurry.

 

 

Configure running and debugging

After the project is created, it cannot be Run directly. The Run and Debug menus are gray and cannot be clicked.

You need to configure the operation and debugging.

As. NET to Java code farmers, sometimes really miss the universe first IDE: Visual Studio, according to the template to create a project rarely can not run directly, forget it, do not mention it, continue to configure...

Set the "Server" tab first

 

Click the "Deployment" tab to continue setting,

Create Artifact and click OK to save it.

 

Now, the Run 'mvc-helloworld' menu item appears under the Run menu (Shift + F10 Run, Shift + F9 Debug)

The run and debug buttons are also available on the toolbar. You can choose your preferred method to run the project.

Although we haven't started writing code yet, after all, IDEA has helped us generate a jsp file. You can use this file to see if the site can be opened (index. jsp code is as follows)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Enter the URL http: // localhost: 8080/index. jsp in the browser.

The project is not running (in fact, there are still a lot of configuration missing from running, continue to look back ),

What is the situation? Of course, the log... Click "Tomcat Localhost Log" to view the problem...

 

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

The ContextLoaderListener class cannot be found.

Import Spring MVC-related Class Libraries

In Java, ClassNotFoundException seems to be a common exception. First, check whether the corresponding jar package is included...

Open the Project Structure, and the configuration related to the Project is basically in a menu...

 

After clicking the "Artifacts" tab, there are more obvious prompts, missing references to the class libraries related to Spring MVC.

Despite the many reminders made by IDEA, why do I still feel less eye-catching?

 

Follow these steps to fix the error:

Copy the class libraries related to Spring MVC to the lib folder during program deployment.

 

Re-run the project (Shift + F10 run, Shift + F9 Debug )......

If you did not Stop the operation last time, this dialog box may pop up. Select "Restart server" and then "OK...

Again visit http: // localhost: 8080/index. jsp

This time we can finally see some content. At least it indicates that the service has started ..

 

If you look at the log just now, the original error is no longer returned.

 

Add Controller

The site can be opened, but we are not MVC, because there is no M, No V, and no C

We will start from the C (Controller) in MVC and continue to configure

Before creating a Controller, create a package. SpringMVC cannot run under the default package. Create a package as follows,

The package name I created is wormday. springmvc. helloworld.

In fact, the package name is random, but it must be...

 

 

Create a new Java Class file HiController in this package.

 

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 want to access the Action address of the Controller just like me, it should be:

Http: // localhost: 8080/hi/say. form in fact, the access result is 404 at this time, because there are still a lot of configuration not done...

 

 

Class annotation @ RequestMapping ("/hi") specifies the part of the front of the Url path

Method annotation @ RequestMapping ("/say") specifies the last part of the Url path

You can also write the Annotation on the method, for example, @ RequestMapping ("/hi/say ")

What is the form at the end? Let's look at the url-pattern...

Modify url-pattern (web. xml)

Open the web \ WEB-INF \ web. xml file first

For settings on ServletMapping, you can configure the types of URLs and use those servlets for processing.

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

In combination with this xml section, we can see that IDEA configures a Servlet named dispatcher for me by default.

This Servlet uses the org. springframework. web. servlet. DispatcherServlet class for processing.

The Url of this Servlet is *. form.

If you do not like a form behind every MVC Url like me, you can change it to a slash.

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

If you restart the program now and continue accessing http: // localhost: 8080/hi/say

It is found that there is still 404 errors in the Output window of the Server with each access.

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

This means that no corresponding Controller is found. Not only do you need to write the Controller code, but you also need to tell Spring (which is actually the dispatcher servlet) where to find these controllers...

For verification, you can add a breakpoint in the Controller and refresh the page. The program is not executed in the Controller.

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

 

Configure component-scan (dispatcher-servlet.xml)

Component-scan is to tell the Servlet where to find the corresponding Controller

Open dispatcher-servlet.xml

Add

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

The base-package specifies the Controller package.

After this step, restart the project and access http: // localhost: 8080/hi/say again.

This time it should be 404 errors, but it is a big step forward than the 404 error.

After all, the Controller has been executed this time. If the breakpoint is not removed, you can verify it.

This is because the View "/WEB-INF/jsp/say. jsp" is not found (we did just tell him this location, but never created this file)

Once again, if Spring Mvc cannot find the Controller or View, it will report a 404 error. If it cannot find the specific person, it should be analyzed in detail. Fortunately, it can be easily identified.

There is a problem in this area. In general, the Controller code returns a string of "say" and does not require. jsp or the forward path. For example

However, if you write this code now, a strange 500 error will be reported, instead of 404.

HTTP Status 500-Circular view path [say]: wocould dispatch back to the current handler URL [/hi/say] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation .)

The reason is:

However, the absolute path of the View must be specified at present, because we have not configured ViewResolver. We will discuss this issue later.

 

Add view file (. jsp)

 

There is no explanation for this. Just now, where did you ask Spring to find this View? Where did you create this View?

If no error is found, the system reports a 404 error. According to the code I wrote in the front, the creation location should be entered.

In fact, Spring does not limit that you have to create in the WEB-INF, but this is more secure, because the WEB-INF directory users are not directly accessible, after all, there may be some code in the View

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Access http: // localhost: 8080/hi/say again

Finally, no error is reported. It seems that the Controller has found the corresponding view.

Configure ViewResolver (dispatcher-servlet.xml)

Do you still remember that the returned value of Controller must be the absolute path of the View? Generally, this is not the case.

Most of the online tutorials only return the View name, for example

 

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

<! -- Specify the view parser --> <bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver"> <! -- View path --> <property name = "prefix" value = "/WEB-INF/jsp/"/> <! -- View name suffix --> <property name = "suffix" value = ". jsp"/> </bean>

Class specifies the class implemented by ViewResolver. You can use ViewResolver that is not used according to different situations. Here, org. springframework. web. servlet. view. InternalResourceViewResolver is specified.

I didn't specify it just now. The default class is also

The prefix and suffix are relatively simple. You can see it.

Remember to modify the returned value of the Controller synchronously after the xml is changed .. Or 404 more

Pass value to View through Model

Through the above operations, the (V and C) in MVC has been completed, and M has not seen the shadow. Let's continue to modify it.

Open the defined Controller, which is the HiController. java file.

Modify the settings as follows (I have highlighted the changes)

Package wormday. springmvc. helloworld; import org. springframework. stereotype. controller; import org. springframework. ui. model; // a Model class import org. springframework. web. bind. annotation. requestMapping; @ Controller @ RequestMapping ("/hi") public class HiController {@ RequestMapping ("/say") public String say (Model model) {// input the Model model in the parameter. addattriday ("name", "wormday"); // specify the Model value. addAttribute ("url", "http://www.cnblogs.com/wormday/p/8435617.html"); // specify the Model value return "say ";}}

Then open the View, that is, the say. jsp file, and modify it as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

The relationship between the two is not explained, and then the project is re-run to refresh the page

A simple MVC project is complete !!!

 

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.