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 ...
随机推荐
- shell脚本(6)-shell数组
一.数组介绍 一个变量只能存一个值,现实中很多值需要存储,可以定义数组来存储一类的值. 二.基本数组 1.概念: 数组可以让用户一次性赋予多个值,需要读取数据时只需通过索引调用就可以方便读出. 2. ...
- MySQL中的redo log和undo log
MySQL中的redo log和undo log MySQL日志系统中最重要的日志为重做日志redo log和归档日志bin log,后者为MySQL Server层的日志,前者为InnoDB存储引擎 ...
- 第十四篇 -- QMainWindow与QAction(清空-全选-撤销-重做-关闭-语言选择)
效果图: 这次添加了关闭-撤销-重做-全选-清空等功能,并添加了字体和字体大小选择.基本方法跟前面几篇类似. ui_mainWindow.py # -*- coding: utf-8 -*- # Fo ...
- LUSE: 无监督数据预训练短文本编码模型
LUSE: 无监督数据预训练短文本编码模型 1 前言 本博文本应写之前立的Flag:基于加密技术编译一个自己的Python解释器,经过半个多月尝试已经成功,但考虑到安全性问题就不公开了,有兴趣的朋友私 ...
- vscode源代码管理(vscode报错 未找到Git,请安装Git,或在"git.path" 设置中配置)
vscode源代码管理(vscode报错 未找到Git,请安装Git,或在"git.path" 设置中配置) 直接上图,电脑上已经安装git,由于vscode没有找到git,所以v ...
- 微信小程序 -- 英语词典 (小程序插件)
英语词典小程序 基于英语词典小程序插件 - 提供开源地址 项目地址 英语词典小程序插件: 微信小程序 词典 真题基础服务插件(gitee.com) 功能特色 [x] 全面详实的经典词库,详细释义覆盖约 ...
- 移植TensorFlow到Windows平台
2015年11月,Google宣布开源旗下机器学习工具TensorFlow,引发业界热潮.TensorFlow原生支持*unix系和安卓平台,但并不提供对Windows平台的支持.如果想在Window ...
- Linux下MySQL基础及操作语法
什么是MySQL? MySQL是一种开源关系数据库管理系统(RDBMS),它使用最常用的数据库管理语言-结构化查询语言(SQL)进行数据库管理.MySQL是开源的,因此任何人都可以根据通用公共许可证下 ...
- linux命令打基础
目录 一.shell概述 二.linux命令分类 三.linux命令行 3.1 格式 3.2 编辑Linux命令行 四.Linux基础命令 4.1 pwd:查看当前的工作目录 4.2 cd:切换工作目 ...
- WPF上传图片到服务器文件夹
1.前端用ListBox加载显示多张图片 1 <ListBox Name="lbHeadImages" Grid.Row="1" ScrollViewer ...