Spring Introduction (v) "SPRINGMVC environment building"

Source: Internet
Author: User
Tags log4j

springmvc, as a Web component of spring, is an MVC idea that reduces the difficulty of web development, and now introduces the construction of SPRINGMVC environment, the concrete principle is introduced in the Following. Friends who have used frames know that to use a framework in a Web project, you have to introduce this framework, as is the case with other frameworks, SPRINGMVC is introduced by dispatcherservlet, Then we are going to configure this servlet in Web. xml, I have already imported all the jar packages in the Lib directory, and look at the configuration of my Web. XML file,

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name>springmvc</ display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file& Gt;index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!--log4j Configuration file--<context-param> <par Am-name>log4jconfiglocation</param-name> <param-value>/web-inf/classes/log4j.properties</ param-value> </context-param> <!--spring Configuration file--<context-param> <param-nam E>contextconfiglocation</param-name> <param-value>classpath:application-context.xml</ param-value> </context-param> <!--configuration springmvc--> <servlet> <servlet-name>springmvc& Lt;/servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--springmvc profiles--<init-param> <param-name>contextconfiglocation</param-name&gt        ; <param-value>/WEB-INF/classes/springmvc.xml</param-value> </init-param> <load-on-startup >1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</ servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--configuration spring--> <liste Ner> <listener-class>Org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--log-in configuration system--<listener> <listener-class>Org.springframework.web.util.Log4jConfigListener</listener-class> </listener></web-app>

Springmvc

In the configuration file we configured the dispatherservlet, and configured its initialization parameters contextconfiglocation, specified the path of the file is:/web-inf/classes, configured the blocked url, We intercept all the URLs Here.

Spring

You might wonder why we've configured spring here, is it just springmvc? The answer is yes, we can completely put all the configuration in the SPRINGMVC configuration file, but we follow the hierarchical configuration, let Springmvc is a configuration file, spring is a configuration file, the function they want to complete separate, In fact, all configurations can be loaded entirely by dispatherservlet.

Spring load mode uses a listener here, contextloaderlistener, which reads the configuration parameters in the Context: contextconfiglocation, reads the spring configuration file, loads the spring container.

Log4j

Because the log function is used in the project, the log is configured here, and the configuration file in the context is Referenced.

Here's a look at Springmvc's 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:AOP= "http://www.springframework.org/schema/aop"Xmlns:tx= "http://www.springframework.org/schema/tx"Xmlns:context= "http://www.springframework.org/schema/context"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/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp//Www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!--configured for component scanning, you do not need to configure <context:annotation-config>, because component scans already contain, component scans, scanned annotations have @controller, @Service, @Resposity, @Component, @ Controller annotations must be scanned by dispatherdispatcherservlet, and dependency injection is implemented, support for @Autowired, @Resource-<context:component-scan base- package= "com.cn.my" > <context:include-filter type= "annotation" expression= " Org.springframework.stereotype.Controller "/> </context:component-scan> <!--turn on annotation-based drivers--&l t;context:annotation-config></context:annotation-config> <!--turn on MVC annotation driver, You can use @requestparam annotations, The request parameters can be helped to the controller parameters--<mvc:annotation-driven/> <mvc:resources location= "/resource/*" mapping= "/res ource/** "/> <beanclass= "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix" value= "/ web-inf/jsp/"></property> <property name=" suffix "value=". jsp "></property> </be An></beans>

The above is the SPRINGMVC configuration file, first configured the component scan, the role of component scanning is automatic class-level annotations (@Controller, @Component, @Service, @Resposity), This is configured to scan only classes with @controller annotations, because classes with @controller annotations can only be loaded by dispatherservlet, followed by the annotation-based driver, which can implement dependency injection, for @autowired, @ Resource Annotations work, but can not be configured, because this feature is already included in component scanning, and the mvc-based annotation driver makes it easy to set the request parameters to the Controller Parameters.
The view resolver is configured at the bottom, and the default view resolver is used Here.

Then look at the spring 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:aop= "http://www.springframework.org/schema/aop" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "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.xsdhttp://www.springframework.org/schema/tx http:/ /www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop/http Www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/context/http Www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc/http Www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "><context:component-scan base-package=" com.cn.my " ><context:excLude-filter type= "annotation" expression= "org.springframework.stereotype.Controller"/></context: Component-scan><!--configure a data source to use the data source provided by Spring--><bean id= "dataSource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource "><property name=" driverclassname "value=" Com.mysql.jdbc.Driver "></property><property name=" url "value=" jdbc:mysql://127.0.0.1:3306/test "> </property><property name= "username" value= "root" ></property><property name= "password" value= "123456" ></property></bean><bean id= "jdbctemplate" class= " Org.springframework.jdbc.core.JdbcTemplate "><property name=" dataSource "ref=" dataSource "></property ></bean></beans>

Spring's role can be the configuration of the data source, transaction or service layer dependency injection, first of all, the component scan, scanning object is in addition to @controller annotations, followed by a data source, where spring provides the data source, the other can also use the dbcp, c3p0, jndi, etc., discussed in the Rear.

A data access object, jdbctemplate, is then configured to manipulate the Database.

Now that our environment has been built, the following is the specific use,

Write the Controller class,

Since we are using component scanning, we use annotations on the class @controller

 packagecom.cn.my.controllor;Importjavax.servlet.http.HttpServletRequest;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;Importorg.springframework.web.bind.annotation.RequestParam;Importcom.cn.my.service.CourseServiceInter, @Controller @requestmapping ("/my/*") public classMycontroller {@AutowiredPrivateCourseserviceinter csi; //generic type of URL@RequestMapping ("my")     publicString method (httpservletrequest request, @RequestParam ("courseid") (String Courseid) {csi.findcourse (courseid); return"success"; }    //restful forms of URLs//http://localhost: 8080/MY/MY2/12@RequestMapping ("my2/{courseid}/{name}")     publicString Method2 (@PathVariable ("courseid") string courseid, @PathVariable ("name") (String Name) {csi.findcourse (courseid+"  "+name); return"success"; }}

In addition to using the @controller annotation on the class, the @requestmapping annotation is used, the path of the access is noted, and then the @requestmapping annotation is used on the Method. A complete URL access path consists of paths on the class and paths on the method, example:/my/my.do, This is an access path, we also use a service layer Findcourse method, The Service Layer object has framework dependency injection, in the method used the @ Requestparam annotations, This note can be in the URL of the parameter to the method parameters, where the value in @requestparam and the URL of the request parameter name consistent, followed by the corresponding method in the parameter Name. The method finally returns a string value that returns the logical view name, or the JSON string, which is described in the BACK.

After the controller has been configured, it can be accessed, so that a SPRIGMVC environment and controller writing is DONE.

There is an undesirable place to welcome the point, thank you!

Spring Introduction (v) "SPRINGMVC environment building"

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.