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,编写完毕,我们重启下服务器然后测试:
结果会插入一条数据
springmvc框架(Spring SpringMVC, Hibernate整合)的更多相关文章
- springMVC,spring和Hibernate整合(重要)
springMVC,spring和Hibernate整合 https://my.oschina.net/hugohxb/blog/184715 第一步:搭建一个springmvc工程,需要的jar有: ...
- SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分
SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分 辞职待业青年就是有很多时间来写博客,以前在传统行业技术强度相对不大,不处理大数据,也不弄高并发 ...
- Maven+SSM框架(Spring+SpringMVC+MyBatis) - Hello World(转发)
[JSP]Maven+SSM框架(Spring+SpringMVC+MyBatis) - Hello World 来源:http://blog.csdn.net/zhshulin/article/de ...
- 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)
轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...
- Spring与Hibernate整合,实现Hibernate事务管理
1.所需的jar包 连接池/数据库驱动包 Hibernate相关jar Spring 核心包(5个) Spring aop 包(4个) spring-orm-3.2.5.RELEASE.jar ...
- Spring与Hibernate整合中,使用OpenSessionInViewFilter后出现sessionFactory未注入问题
近期在知乎看到一句话,保持学习的有一种是你看到了很多其它的牛人,不甘心,真的不甘心. Spring和hibernate整合的时候,jsp页面做展现,发现展现属性出现: org.apache.jaspe ...
- Spring第九篇【Spring与Hibernate整合】
前言 前面已经学习了如何使用Spring与Struts2进行整合,本博文主要讲解如何使用Spring对Hibernate进行整合 Spring和Hibernate整合的关键点: SessionFact ...
- spring和hibernate整合,事务管理
一.spring和hibernate整合开发步骤 1 引入jar文件,用户libarary列表如下 //spring_core spring3..9core\commons-logging-1.2.j ...
- spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory
Hibernate 3.6以上版本在用junit测试时会提示错误: Unable to get the default Bean Validation factory spring和hibernate ...
随机推荐
- ZooKeeper 分布式锁 Curator 源码 02:可重入锁重复加锁和锁释放
ZooKeeper 分布式锁 Curator 源码 02:可重入锁重复加锁和锁释放 前言 加锁逻辑已经介绍完毕,那当一个线程重复加锁是如何处理的呢? 锁重入 在上一小节中,可以看到加锁的过程,再回头看 ...
- 13、java——常用类
枚举类型 描述一种事物的所有情况|所有可能|所有实例 (1)通过enum关键字定义枚举类型 (2)枚举的成员,字段都作为当前枚举类型的实例存在,默认被public static final修 ...
- 【LeetCode】283.移动零
283.移动零 知识点:数组:双指针: 题目描述 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例 输入: [0,1,0,3,12] 输出: [1, ...
- pip install 默认安装路径修改
一.使用命令查看pip默认安装目录 python -m site 这里的USER_BASE和USER_SITE其实就是默认的启用Python通过pip自动下载的脚本和依赖安装包的基础路径. 接着使用命 ...
- Java 比较两个Word文档差异
本文介绍使用Spire.Doc for Java的比较功能来比较两个相似Word文档的差异.需要使用的版本为3.8.8或者后续发布的新版本.可下载jar包,解压将lib文件夹下的Spire.doc.j ...
- node fs-extra文件操作模块的使用(支持同步、异步)
用法参见:fs-extra
- [考试总结]noip模拟19
连挂3场 \(\color{green}{\huge{\text{菜}}}\) 真 . 挂分王 ... 没什么好说的了,菜就是了. \(T1\) 一波手推想到了性质 \(1\),然后因为数组原因挂成比 ...
- Python实用案例,Python脚本,Python实现帮你选择双色球号码
往期回顾 Python实现自动监测Github项目并打开网页 Python实现文件自动归类 前言: 今天我们就利用python脚本实现帮你选择双色球号码.直接开整~ 开发工具: python版本: 3 ...
- 大数据学习(12)—— Hive Server2服务
什么是Hive Server2 上一篇我们启动了hive --service metastore服务,可以通过命令行来访问hive服务,但是它不支持多客户端同时访问,参见官网说明:HiveServer ...
- AlarmManager定时提醒的那些坑
https://blog.csdn.net/zackratos/article/details/53243595 https://blog.csdn.net/bingshushu/article/de ...