Spring MVC +Spring+Hibernate framework construction and detailed explanation

 

In addition to Struts, the current mainstream Web MVC framework is Spring MVC. Therefore, this is also the mainstream framework that a programmer needs to master. There are many framework choices. When dealing with changing needs and business, the feasible solution Naturally more. However, if you want to use Spring MVC flexibly to deal with most web development, you must master its configuration and principles.

  1. Spring MVC environment construction: (Spring 2.5.6 + Hibernate 3.2.0)

  1. Introduction of 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 of the corresponding database

  2. web.xml configuration (part)

<!-- Spring MVC configuration-->  
<!-- ====================================== -->  
<servlet>  
    <servlet-name>spring</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <!-- You can customize the location and name of the servlet.xml configuration file, the default is in the WEB-INF directory, the name is [<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>  默认  
    </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>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>  
    
  
<!-- Specifies the directory where the Spring Bean configuration file is located. The default configuration is in 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 spring-servlet is formed because the value of the <servlet-name> tag in the web.xml above is spring (<servlet-name>spring</servlet-name>), plus the "-servlet" suffix. -servlet.xml file name, if changed to springMVC, the corresponding file name is 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 annotations-->  
    <context:annotation-config />  
  
    <!-- Set the jar package where the class using the annotation is located -->  
    <context:component-scan base-package="controller"></context:component-scan>  
  
    <!-- Complete the mapping of requests and annotation POJOs -->  
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  
  
    <!-- Path parsing to the redirected 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">  
  
    <!-- Use hibernate.cfg.xml to configure the data source-->  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="configLocation">  
            <value>classpath:config/hibernate.cfg.xml</value>  
        </property>  
    </bean>  
      
    <!-- Associate transaction 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>  

 2. Detailed explanation

  Spring MVC and Struts are very similar in principle (both are based on MVC architecture), both have a Servlet that controls page requests, and jumps to the page after processing. Look at 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 similar to Struts   
public class TestController {  
  
    @RequestMapping("test/login.do") // Request url address mapping, similar to Struts' action-mapping   
    public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {  
        // @RequestParam refers to the parameters that must be included in the request url address mapping (unless the attribute required=false)   
        // @RequestParam can be abbreviated as: @RequestParam("username")   
  
        if (!"admin".equals(username) || !"admin".equals(password)) {  
            return "loginError"; // Jump page path (default is forwarding), 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 they are not used, they can be removed   
        // The name of the parameter matches the name of the page control, and the parameter type will be automatically converted   
          
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {  
            return new ModelAndView("loginError"); // Manually instantiate ModelAndView to complete the page jump (forwarding), the effect is equivalent to the return string of the above method   
        }  
        return new ModelAndView(new RedirectView("../index.jsp")); // Jump to the page by redirection   
        // There is also a simple way to write redirection   
        // return new ModelAndView("redirect:../index.jsp");   
    }  
  
    @RequestMapping("/test/login3.do")  
    public ModelAndView testLogin3(User user) {  
        // Also supports parameter as form object, similar to ActionForm of Struts, User does not need any configuration, just write it directly   
        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") // Get the id of the bean in applicationContext.xml as loginService and inject it   
    private LoginService loginService; //It is equivalent to writing the get and set methods in the traditional spring injection method, which has the advantage of being concise and neat, eliminating unnecessary code   
  
    @RequestMapping("/test/login4.do")  
    public String testLogin4(User user) {  
        if (loginService.login(user) == false) {  
            return "loginError";  
        }  
        return "loginSuccess";  
    }  
}  

 The above four methods are examples, a Controller contains different request urls, or a url can be used to access, through the url parameter to distinguish different access methods, 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 request associated with the Controller   
public class TestController2 {  
      
    @RequestMapping  
    public String testLogin(String username, String password, int age) {  
        // If no parameters are added, this method will be executed by default when requesting /test2/login.do   
          
        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) {  
        // Distinguish different calling methods according to the value of the parameter method of params   
        // You can specify the type of page request method, the default 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 on the Class can be regarded as the parent Request request url, and RequestMapping on the method can be regarded as the child Request request url, the parent and child request urls will eventually be spelled out to match the page request url, so RequestMapping can also be written in this way :

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

 3. Conclusion

  Mastering the above Spring MVC already has a good foundation, and can deal with almost any development. After mastering these, you can use deeper and more flexible technologies, such as a variety of view technologies, such as Jsp, Velocity, Tiles , iText and POI. The Spring MVC framework doesn't know which views to use, so it doesn't force you to use only JSP technology.

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326943265&siteId=291194637