[SpringMVC+Hibernate]整合搭框架以及RESTFUL风格的CRUD

一步步搭框架……主要还是myeclipse+Tomat+mysql

准备工作:准备jar包(我已经是一股脑的全部加进去了我也不知道哪些要不要了)已经配置好tomact,以及新建好myqsl数据库。新建web工程,webroot下记得要有web.xml,jar包放在lib里!

对于Hibernate我已经能用注解就用注解了

目录结构


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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>SpringMVC</display-name>

	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>

	</servlet>
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 配置过滤器 作用是把Post请求转换为delete和put -->
	<filter>
	<filter-name>HiddenHttpMethodFilter</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


</web-app>

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

	<!-- 自动扫描的包 -->
	<context:component-scan base-package="com.yiki"></context:component-scan>
	<!-- 可以使用注解是注入 -->
	<context:annotation-config />

	<!-- 数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="******" />
		<!-- 连接池启动的初始值 -->
		<property name="initialSize" value="1"></property>
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="500"></property>
	</bean>


	<!-- 它充当数据存储源的代理,并负责创建Session对象 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	
		<property name="annotatedClasses">
            <list>
                <value>com.yiki.POJO.Person</value>
            </list>
        </property>  

		<property name="hibernateProperties"><!-- 配置hibernate的属性映射 -->
			<props>
				<!-- 方言 -->
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<!-- 自动建表 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
				</prop>
			</props>
		</property>
	</bean>

	<!-- 事务管理器 -->
	<bean id="txManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 需要tx命名空间 注解方式实现事务,此功能为注解解析 -->
	<tx:annotation-driven transaction-manager="txManager" />



	<!-- 配置视图解析器:如何把handler方法解析为实际屋里视图 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		id="internalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/WEB-INF/view/" />
		<!-- 后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 配置直接转发的页面 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:view-controller path="/success" view-name="success"></mvc:view-controller>

	<!-- 配置视图解析器 ,使用视图的名字来解析视图,order可以定义视图优先级 -->
	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
		<property name="order" value="100"></property>

	</bean>

<!-- 对Hibernate定义bean 
-->
	<bean id="personService" class="com.yiki.Model.PersonService"></bean>


</beans>

根据配置文件写的前缀和后缀新建对应的文件夹和文件

比如view文件夹下的success.jsp

实体类

package com.yiki.POJO;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity(name="person")
public class Person {
	@Id
	@GeneratedValue//mysql底层是自动增长
	private int pid;
	private String name;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}
	
	public Person(String name) {
	this.name=name;
	}
	
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Person [pid=" + pid + ", name=" + name + "]";
	}
	

}

模型层(增删查改的hibernate和spring的事务)

package com.yiki.Model;

import java.util.List;

import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yiki.POJO.Person;


//读取的操作都不需要开启事务!
@Transactional
public class PersonService {//是一个业务bean

	@Resource // 默认按名称注入,注意同名
	private SessionFactory sessionFactory;

	public void save(Person person) {
		sessionFactory.getCurrentSession().persist(person);// 得到spring管理的session
	}

	public void update(Person person) {
		sessionFactory.getCurrentSession().merge(person);
	}
	//@Transactional(propagation=Propagation.REQUIRED,readOnly=true) 
	public Person getPerson(int id) {
	return (Person) sessionFactory.getCurrentSession().get(Person.class, id);
	//	return (Person) sessionFactory.openSession().get(Person.class, id);//open会不起作用
	}
	
	//@Transactional(noRollbackFor={Exception.class})如果设置不回滚
	public void delete(int id) {
		sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(Person.class, id));
		//throw new RuntimeException("测试回滚");

	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)  //要疯了propagation死也不起作用??????
	public List<Person> getPerson() {//from 类名不是表名
		return sessionFactory.getCurrentSession().createQuery("from Person").list();

	}

}

控制层

package com.yiki.Handle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yiki.Model.PersonService;
import com.yiki.POJO.Person;

@RequestMapping("/restStyle")
@Controller
public class RestMapping {

	private PersonService service;

	public void start() {

		ApplicationContext cxt = new ClassPathXmlApplicationContext("springmvc.xml");
		service = (PersonService) cxt.getBean("personService");
	}

	private static final String SUCCESS = "success";

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
	public String testRestGet(@PathVariable Integer id) {
		start();
		Person person = service.getPerson(id);
		System.out.println("GET :" + id + person);
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest", method = RequestMethod.POST)
	public String testRestPost() {
		System.out.println("POST");
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
	public String testResDeletet(@PathVariable Integer id) {
		System.out.println("Delete :" + id);
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
	public String testResPut(@PathVariable Integer id) {
		System.out.println("PUT  :" + id);
		return SUCCESS;
	}

}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
  
  <a href="restStyle/testRest/22">Get</a>
	<br>
	<form action="restStyle/testRest" method="Post">
		<input type="submit" value="Post">
	</form>
	<br>
	<form action="restStyle/testRest/1" method="Post">
		<input type="hidden" name="_method" value="DELETE"> <input
			type="submit" value="Delete">
	</form>
	<br>
	<form action="restStyle/testRest/2" method="Post">
		<input type="hidden" name="_method" value="PUT"> <input
			type="submit" value="PUT">
	</form>
  
  
  <a href="helloworld">helloworld</a><br>
  </body>
</html>
点击index的get能有查到数据库的东西并在控制台打印出来即为成功~其他的可以自己加

猜你喜欢

转载自blog.csdn.net/qq_38277033/article/details/80726232