zoukankan      html  css  js  c++  java
  • springmvc框架(Spring SpringMVC, Hibernate整合)

    直接干货

    model 考虑给用户展示什么。关注支撑业务的信息构成。构建成模型。

    control 调用业务逻辑产生合适的数据以及传递数据给视图用于呈献;

    view怎样对数据进行布局,以一种优美的方式展示给用户;

      

    MVC核心思想:业务数据抽取和业务数据呈献相分离。

     看看Spring MVC官网给的图:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html

              Spring’sweb MVC framework is, like many other web MVC frameworks, request-driven, designed around a central Servlet that dispatchesrequests to controllers and offers other functionality that facilitates thedevelopment of web applications.Spring’s DispatcherServlet however, doesmore than just that. It is completely integrated with the Spring IoC containerand as such allows you to use every other feature that Spring has.

             Therequest processing workflow of the Spring Web MVC DispatcherServlet isillustrated in the following diagram.Thepattern-savvy reader will recognize that the DispatcherServlet is an expressionof the "Front Controller" design pattern (this is a pattern thatSpring Web MVC shares with many other leading web frameworks).

     

     

    简单理解就是:client发过来的请求,首先被交给叫做DispatcherServlet的前端控制器去处理,由它决定交给哪个Control去处理。

    处理完后,还会返回结果给Front controller。然后前端控制器再去和View交互,最后response给用户。是不是非常其他MVC框架非常像呢?比方Struts 2.0

    当中大概设计到这些概念(看不懂没关系,后面文章会解释):先看个脸熟

    DispatchServlet 

    Controller

    HandlerAdapter

    HandlerInterceptor

    HandlerMapping

    HandlerExecutionChain

    ModelAndView

    ViewResolver

    View

    好了,是不是已经迫不及待了呢?以下给个高速入门的实例,非常easy,仅仅有一个java文件。两个配置文件和一个终于的jsp文件:

    简单的springmvc框架配置:

    1.spring-mvc.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"
    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">

    <!--激活@Required @Autowired,JSP250'S @PostConstruct, @PreDestroy @Resource等标注 -->
    <context:annotation-config/>

    <!--DispatcherServlet上下文,仅仅搜索@Controller标注的类。不搜索其它搜索的类 -->
    <context:component-scan base-package="com.xidian.mvcdemo.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--启用HandlerMapping标签 -->
    <mvc:annotation-driven/>
    <!--ViewResovlver启用。视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <!--存放jsp文件的目录位置 -->
    <property name="prefix" value="/WEB-INF/jsps/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    </beans>

    2.web.xml

    <?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"
    version="3.0">
    <!-- 地址为http://localhost:8080/ 显示的默认网页-->
    <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <!--加载Spring的配置文件到上下文中去-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/configs/applicationContext.xml
    </param-value>
    </context-param>

    <!-- spring MVC config start-->
    <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 此处指向的的是SpringMVC的配置文件 -->
    <param-value>/WEB-INF/configs/spring-mvc.xml</param-value>
    </init-param>
    <!--配置容器在启动的时候就加载这个servlet并实例化-->
    <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring MVC config end-->

    </web-app>

    3. MainController.java

    package com.xidian.mvcdemo.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class MainController
    {

    @RequestMapping(value = "test", method = RequestMethod.GET)
    public String test(){
    // 实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀
    return "home";
    }

    }

    4. home.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">

    <title>My JSP 'home.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    </head>

    <body>
    Hello Spring MVC <br>
    </body>
    </html>

    能够这样理解程序之间的关系:首先在web.xml中我们用servlet拦截了全部请求交给Spring MVC的Dispatcher,然后它去找对应文件夹下的mvc-dispatcher-servlet.xml文件(也能够不设置,会在默认位置载入文件,代码中有说明,这里仅仅是帮助养成良好的文件归档习惯)。我们在对应的HelloMvcConntroller.java中加上的@Controller 

    @RequestMapping("/hello")  @RequestMapping("/mvc")注解,会告诉Spring MVC这里是Controller,当前端控制器发送来的请求符合这些要求时。就交给它处理。最后会返回home.jsp,哪里的home.jsp?

    输入:http://localhost:8083/SpringTest/test

    结果是home.jsp

    二. Spring整合SpringMvc

    配置applicationContext.xml这个Spring的配置文件如下

    <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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.xidian">
    <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    </beans>

    完善web.xml配置文件如下:

    <?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"
    version="3.0">
    <!-- 地址为http://localhost:8080/ 显示的默认网页-->
    <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

    <!--加载Spring的配置文件到上下文中去-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/configs/applicationContext.xml
    </param-value>
    </context-param>

    <!-- spring MVC config start-->
    <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 此处指向的的是SpringMVC的配置文件 -->
    <param-value>/WEB-INF/configs/spring-mvc.xml</param-value>
    </init-param>
    <!--配置容器在启动的时候就加载这个servlet并实例化-->
    <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring MVC config end-->

    <!-- Spring监听器 -->
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 字符集过滤 -->
    <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    </web-app>

    web.xml配置文件中更改了三处:引入Spring配置文件 Spring的监听器  以及 字符集过滤

    OK,Spring+SpringMVC配置完成,下面我们开始测试:

    在service写一个TestServiceImpl实现TestService接口并实现其test()方法, 代码如下:

    import com.xidian.mvcdemo.service.TestService;
    @Service
    public class TestServiceImpl implements TestService{

    @Override
    public String test() {
    // TODO Auto-generated method stub
    return "home";
    }

    }

    MainController控制器更改如下:

    package com.xidian.mvcdemo.controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    import com.xidian.mvcdemo.service.TestService;

    @Controller
    public class MainController {

    @Autowired
    private TestService testService;

    @RequestMapping(value = "test", method = RequestMethod.GET)
    public String test(){
    // 实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀
    return "home";
    }

    @RequestMapping(value = "springtest", method = RequestMethod.GET)
    public String springTest(){
    return testService.test();
    }
    }

    控制器这里我们运用了Spring的依赖注入自动装配。

    在浏览器中输入地址

    http://localhost:8083/SpringTest/springtest

    结果是home.jsp

    3.Spring+SpringMVC+hibernate整合

    我们想来编写config.properties这个配置文件,里面存放的是hibernate的一些配置

    #database connection config
    jdbc.driver = com.microsoft.sqlserver.jdbc.SQLServerDriver
    jdbc.url = jdbc:sqlserver://localhost:1433;databaseName=test2
    jdbc.username = sa
    jdbc.password = sapassword

    #hibernate config
    hibernate.dialect = org.hibernate.dialect.SQLServerDialect
    hibernate.show_sql = true
    hibernate.format_sql = true
    hibernate.hbm2ddl.auto = update

    下面配置hibernate,这里我为了方便,就直接写进applicationContext.xml里面。配置后的applicationContext.xml如下:

    <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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.xidian">
    <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--扫描配置文件(这里指向的是之前配置的那个config.properties)-->
    <context:property-placeholder location="/WEB-INF/configs/config.properties" />

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动-->
    <property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址-->
    <property name="user" value="${jdbc.username}" /> <!--用户名-->
    <property name="password" value="${jdbc.password}" /> <!--密码-->
    <property name="maxPoolSize" value="40" /> <!--最大连接数-->
    <property name="minPoolSize" value="1" /> <!--最小连接数-->
    <property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接-->
    <property name="maxIdleTime" value="20" /> <!--最大空闲时间-->
    </bean>

    <!--配置session工厂-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.xidian.mvcdemo.entity" />
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
    <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言-->
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句-->
    <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)-->
    </props>
    </property>

    </bean>

    <!-- 事物管理器配置 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    </beans>

     OK,到了这里,配置结束。下面进入测试阶段

    实体类(entity):

    package com.xidian.mvcdemo.entity;

    import javax.persistence.*;

    @Entity
    @Table(name = "Person")
    public class Person {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created")
    private Long created = System.currentTimeMillis();

    @Column(name = "username")
    private String username;

    @Column(name = "address")
    private String address;

    @Column(name = "phone")
    private String phone;

    @Column(name = "remark")
    private String remark;

    public Long getId() {
    return id;
    }

    public void setId(Long id) {
    this.id = id;
    }

    public Long getCreated() {
    return created;
    }

    public void setCreated(Long created) {
    this.created = created;
    }

    public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getAddress() {
    return address;
    }

    public void setAddress(String address) {
    this.address = address;
    }

    public String getPhone() {
    return phone;
    }

    public void setPhone(String phone) {
    this.phone = phone;
    }

    public String getRemark() {
    return remark;
    }

    public void setRemark(String remark) {
    this.remark = remark;
    }

    }

    数据库访问层(repository):

    package com.xidian.mvcdemo.repository;

    import java.io.Serializable;
    import java.util.List;

    public interface DomainRepository<T,PK extends Serializable>{
    T load(PK id);

    T get(PK id);

    List<T> findAll();

    void persist(T entity);

    PK save(T entity);

    void saveOrUpdate(T entity);

    void delete(PK id);

    void flush();
    }

    public interface PersonRepository extends DomainRepository<Person,Long> 
    { }

    @Repository
    public class PersonRepositoryImpl implements PersonRepository {
    
        @Autowired
        private SessionFactory sessionFactory;
    
        private Session getCurrentSession() {
            return this.sessionFactory.openSession();
        }
    
        public Person load(Long id) {
            return (Person)getCurrentSession().load(Person.class,id);
        }
    
        public Person get(Long id) {
            return (Person)getCurrentSession().get(Person.class,id);
        }
    
        public List<Person> findAll() {
            return null;
        }
    
        public void persist(Person entity) {
            getCurrentSession().persist(entity);
        }
    
        public Long save(Person entity) {
            return (Long)getCurrentSession().save(entity);
        }
    
        public void saveOrUpdate(Person entity) {
            getCurrentSession().saveOrUpdate(entity);
        }
    
        public void delete(Long id) {
            Person person = load(id);
            getCurrentSession().delete(person);
        }
    
        public void flush() {
            getCurrentSession().flush();
        }
    }

    服务层(service):
    public interface PersonService {
        Long savePerson();
    }
    @Service
    public class PersonServiceImpl implements PersonService {
    
        @Autowired
        private PersonRepository personRepository;
    
        public Long savePerson() {
            Person person = new Person();
            person.setUsername("XRog");
            person.setPhone("18381005946");
            person.setAddress("chenDu");
            person.setRemark("this is XRog");
            return personRepository.save(person);
        }
    }

    控制层(controller):
    @Controller
    public class MainController {
    
        @Autowired
        private PersonService personService;
    
        @RequestMapping(value = "savePerson", method = RequestMethod.GET)
        @ResponseBody
        public String savePerson(){
            personService.savePerson();
            return "success!";
        }
    }
    OK,编写完毕,我们重启下服务器然后测试:
    结果会插入一条数据



  • 相关阅读:
    标准输入/输出通道
    不要在纠结负数的表示了
    Coursera公开课-Machine_learing:编程作业7
    Heap堆
    广义表的实现
    二叉树的实现
    模拟实现strstr和strrstr
    栈和队列常考面试题(二)
    栈和队列常考面试题(一)
    vector迭代器失效的几种情况
  • 原文地址:https://www.cnblogs.com/daxiong225/p/9426211.html
Copyright © 2011-2022 走看看