Best practice of Building spring4+spring MVC Web project

Source: Internet
Author: User
Tags pack


Spring is a very, very good Java framework, the main thing is to use its IOC container to help us rely on injecting and managing bean components in some programs, to achieve low coupling relationships, and ultimately to improve system scalability and maintainability, and it will be very, very enjoyable to use it to assist us in building Web projects.

Spring's spring MVC comes from behind, designed very, very elegantly, and can be used instead of struts to control the interface view (Controller).

Now let's build an example of a Web engineering best practice that combines spring and spring mvc. Take the spring Framework 4.2.0 as an example, the IDE is myeclipse.

First, a new dynamic Web Project

Add a spring-context and its dependent Jar pack

Join spring MVC related JAR pack

The complete jar package is as follows

Now you're ready to configure the IOC container for spring and spring MVC, theoretically, you can just need the IOC container for spring MVC, and all the beans are in there for the Spring MVC container to manage, but it's not elegant, we can get spring The MVC container manages only what is relevant to it, such as data sources, transaction management, and the beans that are needed in its own program, which can be managed with spring's IOC container.

Configured in Web.xml to start spring's IOC container:

<!--start Spring's IOC container-->

<context-param>

    <param-name>contextconfiglocation</ param-name>

    <param-value>/WEB-INF/beans.xml</param-value>

</context-param>

<listener>

    <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>

</listener>

This configuration means passing in a configuration message named "Contextconfiglocation" to ServletContext, and then adding a listener that spring provides for us to start the spring container. When the Web application is started, this listener will name the "contextconfiglocation" configuration information from ServletContext, the path of the spring configuration file, and if so, will start the spring container from the specified path. If you do not read from the default path, here we specify the Beans.xml file under Web-inf, here is an example of the most basic Beans.xml configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns=

"Http://www.springframework.org/schema/beans"

    xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"

    xmlns:context= "http://www.springframework.org/ Schema/context "

    xsi:schemalocation=" Http://www.springframework.org/schema/beans http:// Www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context-4.2.xsd ">

 

    <context:component-scan base-package= "COM.CPWL" >

 

</context:component-scan>

 

</beans>

The above configuration specifies the package that needs to be scanned, and Base-package represents the package that needs to be scanned, and spring scans the components in it and all of its child packages (add some annotations to the class, such as: @Component, @Controller, @Service, @ Repository, and then creates an instance of it and puts it into the IOC container.

Then we'll configure the necessary configuration to start the Spring MVC container, go back to Web.xml, and paste the following configuration in:

<!--launches the IOC container-->

<servlet> <servlet-name>springdispatcherservlet</of Spring MVC

  Servlet-name>

  <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class >

  <init-param>

    <param-name>contextConfigLocation</param-name>

    <param-value >/WEB-INF/spring-mvc.xml</param-value>

  </init-param>

  <load-on-startup>1</ load-on-startup>

</servlet>

<servlet-mapping>

  <servlet-name> springdispatcherservlet</servlet-name>

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

</ Servlet-mapping>

Because spring MVC is primarily used as a front-end controller, the bottom layer is naturally a servlet implementation, which means configuring a spring to provide us with a good servlet to start spring MVC, reading the specified path of spring MVC configuration file and specifies that it blocks all requests (Spring MVC handles the request to the controller of the specified request path). Here we specify the path for the Spring-mvc.xml file under the Web-inf directory as the configuration file for spring MVC.

Come to the Web-inf directory, create a new Spring-mvc.xml file, and the same format as Beans.xml file.

We mainly use spring MVC to write controller, each controller can map any number of paths, using annotations to annotate controller is very convenient and elegant, we need to use the @controller annotation to specify the controller object , using @requestmapping to specify a method to map a path, you only need to add the <mvc:annotation-driven></mvc:annotation-driven in the Spring-mvc.xml > can be.

But to intercept all requests, some static resources outside of the bad access, when we want to let the server's own default servlet to help us deal with static resource response, only need to Spring-mvc.xml file with a <MVC: Default-servlet-handler/> on the line, using the MVC namespace, you naturally need to import the MVC namespace.

Don't worry, you also need to specify the package for the Spring MVC Scan component To add a configuration like this in Spring-mvc.xml: <context:component-scanbase-package= "COM.CPWL" Use-default-filters= "false" ></context:component-scan>

Note that the use-default-filters is set to false.

At this point the complete spring-mvc.xml is like this:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns=

"Http://www.springframework.org/schema/beans"

    xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"

    xmlns:mvc= "http://www.springframework.org/ Schema/mvc "

    xmlns:context=" Http://www.springframework.org/schema/context "

    xsi:schemalocation=" http:// Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

        http:// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

        http:// Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd " >

 

    <mvc:default-servlet-handler/>

<mvc:annotation-driven></mvc:annotation-driven>

    <context:component-scan base-package= "Com.cpwl" use-default-filters= "false" >

</context: Component-scan>

 

</beans>

Now, we can write a controller:

Package Com.cpwl.springtest.controller;

 

Import Org.springframework.stereotype.Controller;

Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RequestMethod;

Import Org.springframework.web.servlet.ModelAndView;

 

@Controller public

class TestController {public

    

    TestController () {System.out.println ()}

        ("TestController Constructed ... ");

    

    @RequestMapping (value= "/test", method=requestmethod.get) public

    Modelandview Testmvc () {

        Modelandview Modelandview = new Modelandview ("/web-inf/views/test.jsp");

        Modelandview.addobject ("Info", "Timmy Wanli");

        Return Modelandview

    }

 

}

The controller Testmvc method maps the path of "/test", when it accesses it, it sets a message and then sends it to/web-inf/views/test.jsp to display the output page to the client.

Create a new views directory in the Web-inf directory, enter the directory and create a new test.jsp, as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!

DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


Now the project structure of Web project is as follows:

OK, now we deploy it to the server, start the server and use the browser to access the path mapped by TESTMVC ():

Oh, yes.

But. Let's look at the information that the console outputs:

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.