ssh框架(hibernate+spring+springmvc+maven)
1.环境搭建
jdk安装以及环境变量配置
mysql安装以及环境变量配置(cmd操作数据时,最好配置mysql的环境变量,便于操作)
tomcat安装以及环境变量配置
maven安装以及环境变量配置
以上的操作都可以在百度上找,具体的在此demo中不写。
2.项目结构
3.pom.xml文档配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>zy.com</groupId> <artifactId>ssh</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <springVersion>4.3.1.RELEASE</springVersion> <hibernateVersion>4.3.5.Final</hibernateVersion> <jstlVersion>1.2</jstlVersion> <taglibVersion>1.1.2</taglibVersion> <servletVersion>3.0-alpha-1</servletVersion> <jsonVersion>1.9.13</jsonVersion> <jacksonVersion>2.5.0</jacksonVersion> <mysqlVersion>5.1.38</mysqlVersion> <c3p0Version>0.9.1.2</c3p0Version> <log4jVersion>1.2.17</log4jVersion> <fileuploadVersion>1.3.1</fileuploadVersion> <lombokVersion>1.16.10</lombokVersion> </properties> <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <!-- spring web + spring MVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <!-- hibernate配置--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- hibernate 缓存, 视情况添加--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- jsp页面使用的jstl支持--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlVersion}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibVersion}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servletVersion}</version> <scope>provided</scope> </dependency> <!-- DataBase数据库连接 mysql包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <!-- 数据库连接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0Version}</version> </dependency> <!-- json数据 使springMVC可以返回json值 ,视情况添加--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jsonVersion}</version> </dependency> <!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonVersion}</version> </dependency> <!-- log4j配置, 视情况添加--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jVersion}</version> </dependency> <!--文件 上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadVersion}</version> </dependency> <!-- lombok插件导包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombokVersion}</version> <scope>provided</scope> </dependency> </dependencies> </project>
做此demo花的时间最多的就是pom.xml配置,因为之前做了ssm框架整合demo,两个框架有些jar包会有冲突,pom.xml一直报错,最后没办法,将本地仓库的jar全删除,重新下载。因此搭建框架时,jar包的配备也很关键。
上面没问题,你还是发现pom.xml文档还在报错,那是因为缺少web.xml文档,so先将项目变为web项目,项目中会自动出现webContent目录,具体操作,可以百度搜索“如何将maven项目转为web项目”。在webContent目录下的META-INF文件下创建web.xml文档,不做其他配置。报错自会消失
4.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <context:annotation-config/> <!-- 扫描Controller,并将其生命周期纳入Spring管理 --> <context:component-scan base-package="com.ssh.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 注解驱动,以使得访问路径与方法的匹配可以通过注解配置 --> <mvc:annotation-driven /> <!-- 静态页面,如html,css,js,images可以访问 --> <mvc:default-servlet-handler /> <!-- 视图定位到/WEB/INF/jsp 这个目录下 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
4.1.测试springmvc配置是否成功
4.1.1.修改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">
<!-- 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>classpath: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-->
<!-- 字符集过滤 -->
<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>
4.1.2.在controller创建TestController.java
package com.ssh.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ssh.pojo.Product;
import com.ssh.service.ProductService;
import com.ssh.service.TestService;
@Controller
public class TestController {
@RequestMapping("/test")
public String toTest(){
return "test";
}
}
4.1.4.在/WebContent/WEB-IN文件下创建jsp文件,存放jsp文件,创建 test.jsp,内容如下
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <body> <center> <h2 style="color:green">test ok!</h2> </center> </body> </html>
4.1.5.启动tomcat服务器,网页访问http://localhost/ssh/test,效果如下
5.springmvc+spring整合
5.1.配置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.ssh"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
5.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"> <!--加载Spring的配置文件到上下文中去--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 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>classpath: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--> <!-- 字符集过滤 --> <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>
5.3.创建service层
5.3.1.创建TestService.java
package com.ssh.service;
public interface TestService {
public String test();
}
5.3.2.创建TestServiceImpl.java
package com.ssh.service.impl;
import org.springframework.stereotype.Service;
import com.ssh.service.TestService;
@Service
public class TestServiceImpl implements TestService{
@Override
public String test() {
// TODO Auto-generated method stub
return "test";
}
}
5.4.修改TestController.java
package com.ssh.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ssh.pojo.Product;
import com.ssh.service.ProductService;
import com.ssh.service.TestService;
@Controller
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String toTest(){
return "test";
}
@RequestMapping("/springtest")
public String springTest(){
return testService.test();
}
}
5.5.重启tomcat服务器,在网页中访问:http://localhost:8080/ssh/springtest,效果如下图。
6.hibernate+spring+springmvc整合
6.1.jdbc.properties文档配置
#database connection
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/test?useSSL=true
jdbc.username = root
jdbc.password = dopa
#hibernate
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update
6.2.修改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"> <!--********************************************配置Spring***************************************--> <!-- 自动扫描 --> <context:component-scan base-package="com.ssh"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--********************************************配置hibernate********************************************--> <!--扫描配置文件(这里指向的是之前配置的那个config.properties)--> <context:property-placeholder location="classpath:/jdbc.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.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.ssh.pojo" /> <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.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
6.3.测试准备
6.3.1.数据源准备
6.3.1.1.创建数据库
create database test;
6.3.1.2.创建表
use test; CREATE TABLE product_ ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(30) , price float , PRIMARY KEY (id) ) DEFAULT CHARSET=UTF8;
6.3.2.创建pojo层
6.3.2.1.创建Product.java
package com.ssh.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "product_") public class Product { @Id @GeneratedValue private int id; @Column(name = "name") private String name; @Column(name = "price") private float price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
6.3.3.在service层添加ProductService.java和ProductServiceImpl.java
6.3.3.1.创建ProductService.java
package com.ssh.service; import com.ssh.pojo.Product; public interface ProductService { public Product get(int id); public void set(); }
6.3.3.2.创建ProductServiceImpl.java
package com.ssh.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssh.dao.ProductDao; import com.ssh.pojo.Product; import com.ssh.service.ProductService; @Service public class ProductServiceImpl implements ProductService{ @Autowired private ProductDao pd; @Override public Product get(int id) { // TODO Auto-generated method stub return pd.getById(id); } @Override public void set() { Product p = new Product(); p.setName("iphone"); p.setPrice(4000); pd.set(p); } }
6.3.4.修改TestController.java
package com.ssh.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ssh.pojo.Product; import com.ssh.service.ProductService; import com.ssh.service.TestService; @Controller public class TestController { @Autowired private TestService testService; @RequestMapping("/test") public String toTest(){ return "test"; } @RequestMapping("springtest") public String springTest(){ return testService.test(); } @Autowired private ProductService ps; @RequestMapping("/saveProduct") public String savePerson(){ this.ps.set(); return "test"; } @RequestMapping("/product") public String toProduct(HttpServletRequest req,Model model){ int id = Integer.parseInt(req.getParameter("id")); Product p = this.ps.get(id); model.addAttribute("p", p); return "product"; } }
6.3.5.在jsp文件下创建product.jsp文件
6.3.5.1.product.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>测试</title> </head> <body> ${p.name} </body> </html>
6.4.正式测试
6.4.1.重启tomcat服务器,在网页中访问:http://localhost:8080/ssh/saveProduct,效果如下
数据库效果:
再访问:http://localhost:8080/ssh/product?id=27,效果如下:
------------------------------------------------------------------------------------------------------------------------
ok,三大框架整合完毕,工作中需要加入第三方jar,需要在applicationContext.xml和spring-mvc.xml中添加配置,此demo只是简单三大框架整合。
本文借鉴了一位博主的文章,大家如果还有什么不明白的,可以去此链接参考:https://www.cnblogs.com/xrog/p/6359706.html
-------------再见!