Spring MVC and Maven – first project: Hello world! Basic template

最近换了新环境,要在ubuntu notebook做开发,很多东东要重新配置,配置的东东比较繁琐,所以写这稿记之,一作为自己的工作笔记,二也可以帮助别人。


下面是英文资料,一个较完整的maven helloword,这个例子是假定各位的eclipse,maven,tomcat都已经安装配置好,我的环境是eclipse 4.5.2  jdk8.0.22 tomcat 8 或7


Spring is one of the most popular and used java frameworks. In this post we show how to create first project in Spring MVC + Maven and how to run it using IntelliJ IDEA and Tomcat!

To create our first project in Spring MVC we need:

  • JDK 7
  • Maven
  • Spring MVC 4.0
  • Tomcat
  • IntelliJ IDEA

And of course some basic knowledge about Java and Spring framework.

Firstly I would like to introduce you Spring MVC documentation – I think it’s must-read for all new developers in Spring MVC.

Project structure
After that, we can create maven web applicatoin. We can do it in IDEA (File->New Project->Maven module->maven-archetype-webapp) or using Maven:

?
1
mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

As as result, we should get following project structure:

?
1
2
3
4
5
6
7
8
|src
|--main
|----resources
|----webapp
|------index.jsp
|------WEB-INF
|--------web.xml
|pom.xml

I also create java directory inside main and I keep there all my java classes. In the default, all .jsp views are directly inside webapp but I keep my views in WEB-INF/views directory – I think it’s more elegant.

Now we can required dependencies to pom.xml file:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
     org.springframework
     spring-core
     4.0.0.RELEASE
     org.springframework
     spring-beans
     4.0.0.RELEASE
     org.springframework
     spring-context
     4.0.0.RELEASE
     org.springframework
     spring-web
     4.0.0.RELEASE
     org.springframework
     spring-webmvc
     4.0.0.RELEASE

Spring configuraition
Ok, now we need to configure our application to use Spring MVC. To do this we need to edit our web.xml file and add following:

?
1
2
3
4
5
6
7
8
9
10
< servlet >
     < servlet-name >mvc-dispatcher servlet-name >
     < servlet-class >org.springframework.web.servlet.DispatcherServlet servlet-class >
     < load-on-startup >1 load-on-startup >
servlet >
 
< servlet-mapping >
     < servlet-name >mvc-dispatcher servlet-name >
     < url-pattern >/ url-pattern >
servlet-mapping >

Above code defines main servlet and this servlet will be used to handle all request for / url pattern.

?
1
2
3
4
< context-param >
     < param-name >contextConfigLocation param-name >
     < param-value >/WEB-INF/mvc-dispatcher-servlet.xml param-value >
context-param >

In above code we point our spring context file where we can define all our beans etc. And finally we add following code:

?
1
2
3
4
5
6
     < listener >
         < listener-class >
             org.springframework.web.context.ContextLoaderListener
         listener-class >
     listener >
web-app >

(web.xml file is available on github, link on the end of this post).

OK, we have web.xml file so we need to create mvc-dispatcher-servlet.xml file inside WEB-INF directory. In this file we can configure our servlet and define spring beans. Our sample file looks like:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< 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"
        xmlns:mvc = "http://www.springframework.org/schema/mvc"
        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
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
     < context:component-scan base-package = "com.about.java.*" />
 
     < mvc:annotation-driven />
 
     < bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
         < property name = "prefix" >
             < value >/WEB-INF/views/ value >
         property >
         < property name = "suffix" >
             < value >.jsp value >
         property >
     bean >
beans >

In this file we configure base-package which is scan to use annotations. You can change it for your package.
Inside this file we can also configure view resolver – I use InternalResourceViewResolver which use .jsp files which are placed in WEB-INF/views/ directory (you can change it as well).

Controller and view
OK, we have configured project so now we can create controller which will handle main request. So we createIndexController:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.about.java.controllers;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class IndexController {
     @RequestMapping (value = "/" )
     public ModelAndView index() {
         ModelAndView mav = new ModelAndView( "index/index" );
 
         String msg = "Running IndexController.index() method" ;
 
         mav.addObject( "msg" , msg);
         return mav;
     }
}

Regarding above code: @Controller annotation makes this class a controller which can handle HTTP requests. Inside this class we created index() method to handle “/” url path (using @RequestMapping annotation). As you can see, this method returns ModelAndView object which is combination of objects-map and view name. As a argument it takes view name (so for us it’s index/index and it points to WEB-INF/views/index/index.jsp because we configured .jsp suffix and WEB-INF/views/ prefix). We’ve added msg object to objects-map and then we can use it in our view.

In /WEB-INF/views/index/ we create index.jsp view file:

?
1
2
3
4
5
6
7

Hello World!

 

${msg}

And as you can see we used ${msg} variable, which is set in Controller, to print text.

Overall
Our project structure now looks like:

This project is available on our GitHub: Spring MVC and Maven basic template

Running project in IntelliJ IDEA 12
OK now we need to configure our Tomcat in IDEA. To do this we need go to Run/Debug Configuration. Then we need to add new configuration and select Tomcat -> Local. As startup page we can set: http://localhost:8080/hello/. Then we have to go to Deployment tab and add artifact: war exploded and application context for this artefact set to the same path as in startup page, so: /hello.
Now only save this configuration and you can run project. As a result you should be able to openhttp://localhost:8080/hello/ and see your first Spring MVC webpage:


然后在eclipse里导入maven项目就可以运行了;但是细心的同学会发现,这个工程的propertis中的dynamic web module的version是2.3,java的版本也是1.3,这开玩笑吗?

不是,是真的这样!

那我们如何把它改成3.1,把java 1.3改成1.8;

java的版本修改,直接改就可以了;

但改dynamic web module的版本,要费点功夫:

下面给出的方案,是我读了两个外国人的解决方案后得出的最佳方案:

Open web.xml from project structure http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> Servlet 3.0 Web Application

and update web.xml file for example change version = "2.5"

Also change the org.eclipse.wst.common.project.facet.core.xml file from your project .settings file Follow the steps 1. Window > Show View > Other > General > Navigator

There is a .settings folder under your project directory

Change the dynamic web module version in this line to 2.5 4.Change the Java version in this line to 1.5 or higher

Now refresh your project and get set to run on your server.

Do follow the blog for the solution http://scrapillars.blogspot.in/2014/02/how-to-change-project-facet-in-eclipse.html

The solution is produced with image illustrations

如果出现下面错误:
org.eclipse.core.runtime.CoreException: One or more constraints have not been satisfied

可以在web.xml里配置plugin:

  
    simpv-mvctest
    
    
    org.apache.maven.plugins
    maven-compiler-plugin
    3.3
    
        1.7
        1.7
    


  


下面附上我的web.xml配置




  
	
        
            org.springframework.web.context.ContextLoaderListener
        
    
  
	    contextConfigLocation
	    classpath*:mvc-dispatcher-servlet.xml
	
	
	Archetype Created Web Application
	
	    mvc-dispatcher
	    org.springframework.web.servlet.DispatcherServlet
	    1
	
	
	
	    mvc-dispatcher
	    /
	

我的mvc-dispatcher-servlet.xml配置:


    
    

    
        
            /WEB-INF/views/
        
        
            .jsp
        
    



你可能感兴趣的:(helloword)