Spring MVC Framework configuration method and detailed description, springmvc

Source: Internet
Author: User
Tags sonatype

Spring MVC Framework configuration method and detailed description, springmvc

Currently, the mainstream Web MVC framework is not only the main force of Struts, but also Spring MVC. Therefore, this is also the mainstream framework that programmers need to master. There are more frameworks to choose from, when dealing with changing needs and businesses, there will naturally be more feasible solutions. However, to flexibly use Spring MVC to cope with most Web development tasks, you must master its configuration and principles.

I. Spring MVC environment setup: (Spring 2.5.6 + Hibernate 3.2.0)

1. Import the jar package

Spring 2.5.6: spring. jar, spring-webmvc.jar, commons-logging.jar, cglib-nodep-2.1_3.jar

Hibernate 3.6.8: hibernate3.jar, hibernate-jpa-2.0-api-1.0.1.Final.jar, antlr-2.7.6.jar, commons-collections-3.1, dom4j-1.6.1.jar, javassist-3.12.0.GA.jar, jta-1.1.jar, slf4j-api-1.6.1.jar, slf4j-nop-1.6.4.jar, driver jar package for the appropriate database

2. web. xml configuration (Part)

<! -- Spring MVC configuration --> <! -- =================================================== --> <Servlet-name> spring </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <! -- Servlet can be customized. the location and name of the xml configuration file, which is under the WEB-INF directory by default and named [<servlet-name>]-servlet. xml, such as spring-servlet.xml <init-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/spring-servlet.xml </param-value> default </init-param> --> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> spring </servlet-name> <url-pattern> *. do </url-pattern> </servlet-mapping> <! -- Spring configuration --> <! -- =================================================== --> <Listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener> <! -- Specifies the directory where the configuration file of Spring Bean is located. The default configuration is under the WEB-INF directory --> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: config/applicationContext. xml </param-value> </context-param>

3. spring-servlet.xml Configuration

The name of spring-servlet is based on the web. in xml, the <servlet-name> tag value is spring (<servlet-name> spring </servlet-name> ), coupled with the "-servlet" suffix and the formation of the spring-servlet.xml file name, if changed to springMVC, the corresponding file name is the springMVC-servlet.xml.

<? 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: p =" http://www.springframework.org/schema/p "Xmlns: context =" http://www.springframework.org/schema/context "Xsi: schemaLocation =" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans Spring-beans-3.0.xsd http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop Spring-aop-3.0.xsd http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx Spring-tx-3.0.xsd http://www.springframework.org/schema/context <A href =" http://www.springframework.org/schema/context /Spring-context-3.0.xsd "> http://www.springframework.org/schema/context /Spring-context-3.0.xsd </A> "> <! -- Enable spring mvc annotation --> <context: annotation-config/> <! -- Set the jar package of the class using the annotation --> <context: component-scan base-package = "controller"> </context: component-scan> <! -- Ing requests and POJO annotations --> <bean class = "org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter"/> <! -- Parse the path of the redirection page. Prefix: prefix, suffix: suffix --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "p: prefix ="/jsp/"p: suffix = ". jsp "/> </beans>

4. applicationContext. xml configuration

<? 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 "Xsi: schemaLocation =" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans Spring-beans-2.5.xsd http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop Spring-aop-2.5.xsd http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx /Spring-tx-2.5.xsd "> <! -- Hibernate is used. cfg. xml-based data source configuration --> <bean id = "sessionFactory" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean "> <property name =" configLocation "> <value> classpath: config/hibernate. cfg. xml </value> </property> </bean> <! -- Associate transactions with Hibernate --> <bean id = "transactionManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager "> <property name =" sessionFactory "> <ref local =" sessionFactory "/> </property> </bean> <! -- Transaction (annotation) --> <tx: annotation-driven transaction-manager = "transactionManager" proxy-target-class = "true"/> <! -- Test Service --> <bean id = "loginService" class = "service. LoginService"> </bean> <! -- Test Dao --> <bean id = "hibernateDao" class = "dao. hibernateDao "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> </beans>

Ii. Details

Spring MVC and Struts are similar in principle (both based on the MVC Architecture). They all have a Servlet that controls page requests and jump to the page after processing. See the following code (annotation ):

Package controller; import javax. servlet. http. httpServletRequest; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestParam; import entity. user; @ Controller // Action public class TestController similar to Struts {@ RequestMapping ("test/login. do ") // request url address ing, similar to Struts's action-mapping public Stri Ng testLogin (@ RequestParam (value = "username") String username, String password, HttpServletRequest request) {// @ RequestParam refers to the parameters that must be included in the request url address ing (unless the attribute required = false) // @ RequestParam can be abbreviated as @ RequestParam ("username ") if (! "Admin". equals (username) |! "Admin ". equals (password) {return "loginError"; // redirect page path (forwarding by default ), this path does not need to contain the prefix and suffix configured in the spring-servlet configuration file} return "loginSuccess";} @ RequestMapping ("/test/login2.do") public ModelAndView testLogin2 (String username, string password, int age) {// request and response do not have to appear in the method. If not, you can remove the // parameter name that matches the name of the page control, the parameter type is automatically converted if (! "Admin". equals (username) |! "Admin ". equals (password) | age <5) {return new ModelAndView ("loginError"); // manually instantiate ModelAndView to jump to the page (forward ), the result is equivalent to the return string} return new ModelAndView (new RedirectView (".. /index. jsp "); // redirect the page. // rewrite also has a simple method // return new ModelAndView (" redirect :.. /index. jsp ") ;}@ RequestMapping ("/test/login3.do ") public ModelAndView testLogin3 (User user User) {// The same parameter supports form objects, similar to the Struts ActionForm, the User does not need any configuration. String username = user. getUsername (); String password = user. getPassword (); int age = user. getAge (); if (! "Admin". equals (username) |! "Admin ". equals (password) | age <5) {return new ModelAndView ("loginError");} return new ModelAndView ("loginSuccess");} @ Resource (name = "loginService ") // obtain applicationContext. the bean id in xml is loginService, and private LoginService loginService is injected; // It is equivalent to the traditional spring injection method for writing get and set methods. This advantage is conciseness and conciseness, save the code @ RequestMapping ("/test/login4.do") public String testLogin4 (User user User) {if (loginService. login (user) = false) {return "loginError";} return "loginSuccess ";}}

The above four method examples show that a Controller contains different request URLs. You can also use a url to access different methods by using url parameters. The Code is as follows:

Package controller; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestMethod; @ Controller @ RequestMapping ("/test2/login. do ") // specify a unique *. do requests are associated with the Controller public class TestController2 {@ RequestMapping public String testLogin (String username, String password, int age) {// if no parameter is added When the/test2/login. do request is sent, the if (! "Admin". equals (username) |! "Admin ". equals (password) | age <5) {return "loginError";} return "loginSuccess" ;}@ RequestMapping (params = "method = 1", method = RequestMethod. POST) public String testLogin2 (String username, String password) {// identify different call methods based on the value of the params parameter method. // you can specify the type of the page request method, the default value is get request if (! "Admin". equals (username) |! "Admin ". equals (password) {return "loginError";} return "loginSuccess";} @ RequestMapping (params = "method = 2") public String testLogin3 (String username, String password, int age) {if (! "Admin". equals (username) |! "Admin". equals (password) | age <5) {return "loginError";} return "loginSuccess ";}}

In fact, RequestMapping can be viewed as a parent Request url in the Class, while RequestMapping can be viewed as a sub-Request url in the method, the parent-child request url will eventually match the page request url. Therefore, the RequestMapping can also be written as follows:

Package controller; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; @ Controller @ RequestMapping ("/test3/*") // The parent request url public class TestController3 {@ RequestMapping ("login. do ") // The subrequest url, which is equivalent to/test3/login after splicing. do public String testLogin (String username, String password, int age) {if (! "Admin". equals (username) |! "Admin". equals (password) | age <5) {return "loginError";} return "loginSuccess ";}}

Iii. Conclusion

Mastering the above Spring MVC has already had a good foundation, and almost can cope with any development. After mastering these skills, you can use more in-depth and flexible technologies, such as multiple view technologies, such as Jsp, Velocity, Tiles, iText, and POI. The Spring MVC Framework does not know the view used, so it does not force you to only use JSP technology.


How does eclipse build springmvc + mybatis?

SpringMVC + MyBatis + Freemarker simple framework (1)

I. Development Environment:
For details about Eclipse, Tomcat, and SVN, see the following post.
Www.iteye.com/topic/982182

Install svn and maven plug-ins:
1. Install the gef plug-in first
Address: download.eclipse.org/tools/gef/updates/interim/
2. Install the svn plug-in
Address: subclipse.tigris.org/update_1.6.x
3. maven plug-in
M2eclipse-core Update address: m2eclipse.sonatype.org/sites/m2e
M2eclipse-extras Update City: m2eclipse.sonatype.org/sites/m2e-extras
4. Possible Installation Problems
If you directly install maven2 online, the dependency plug-in cannot be found and cannot be installed. You must install the gef plug-in before installing the m2eclipse-core plug-in. However, installing the m2eclipse-extras plug-in depends on the subclipse plug-in. Therefore, the correct installation sequence of the three plug-ins is: gef plug-ins, subclipse plug-ins, and m2eclipse plug-ins.

Ii. web. xml and applicationContext. xml configuration
1. web. xml file Configuration:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app xmlns: xsi = "www.w3.org/2001/XMLSchema-instance"
Xmlns = "... the remaining full text>

How to build a spring framework?

First of all, java Beginners should not be eager to learn spring. spring is hard to understand if they have not written jsp + servlet-only projects. In addition, the above framework will be used in the project to greatly limit people's thinking, so you should learn the mvc development mode of jsp + servlet first.
To enter spring, you must first integrate the development environment. If the development environment is difficult to build (such as Eclipse and those who advocate notepad development), you will lose interest in spring, therefore, we recommend that you use Netbeans, which comes with spring2.5 in version 6.1. You can add spring mvc support when creating a web project. All the required packages are included.
The use of spring is relatively simple, so it focuses on understanding the principle. We use spring to actually use other people's design methods. If we do not clarify it, it will become a hard work of the program. You can search for tutorials online, but not all of them. It is better to buy books at first, and you can search for documents online to expand your knowledge later. At the beginning, I read "Detailed description of Integrated ssh Application Development". This book is generally used to get started by choosing one with a certain thickness.

Related Article

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.