作为一个初学者,在网上找了很久都没有找到一个简单的例子。最终自己看明白了写出了一个。贴在这里,
首先是项目结构
超简单的结构,只是基本实现了mvc,hibernate/spring事务的使用。
基本实现为在index.jsp里点击一个按钮,将数据提交至后台的controller,然后对数据库进行操作,然后返回前台qiuqiu.jsp数据。
实现步骤1:
1:
建立工程,加入所有jar包
2:配置mvc
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"
id="WebApp_ID" version="3.0">
<display-name>Tests</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- spring加载多个配置文件是就要配置 context-param实际上是个键值对,作为项目的一个上下文对象
而spring的监听器ContextLoaderListener加载时,会查找名为contextConfigLocation的参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath*:com/gaoyajun/spring/xmls/*.xml</param-value>
</context-param>
<!-- 配置Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 配置Session -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2)配置springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<div yne-bulb-block="paragraph" style="white-space: pre-wrap; line-height: 1.875; font-size: 14px;"><!--视图解析器配置--></div>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<div yne-bulb-block="paragraph" style="white-space: pre-wrap; line-height: 1.875; font-size: 14px;"><!-- mvc扫描器--></div>
<mvc:annotation-driven/>
<context:component-scan base-package="com"></context:component-scan>
</beans>
当配置完这里,一个mvc的框架都配置成功了。在建立一个控制器一个前端jsp基本就可以获取到前后端通信了。
控制器:TestController
package com.gaoyajun.spring.conroller;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.gaoyajun.spring.dao.UserDao;
import com.gaoyajun.spring.entity.User;
@Controller
public class TestController {
@Resource(name="userDao")
private UserDao userdao;
@RequestMapping(value="/love.do",method=RequestMethod.POST)//注解的方式,将访问这个方法的地址设置为love.do
public ModelAndView add(User user){//使用对象的方式
ModelAndView mdv=new ModelAndView("qiuqiu");//最终要返回数据的目标jsp
System.out.println("获得数据");
System.out.println(user);
userdao.addUser(user);
return mdv;
}
@RequestMapping(value="/love1.do",method=RequestMethod.POST)
public ModelAndView query(User user){//查询的方法,
Map<String,Object> data = new HashMap<String,Object>();
user= userdao.getUser("1");
data.put("user",user);
return new ModelAndView("qiuqiu2",data) ;
}
}
此处为控制器,主要是与前端进行交互,一开始没有搞懂其他的首先做的是弄通mvc,类里面只有如下的一个简单方法没有User等实体类,方法很简单纯粹用于测试的:
@RequestMapping(value="/love0.do",method=RequestMethod.POST)
public String Test(<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">String name</span><span style="white-space: pre-wrap; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">,String age,Model model</span><span style="white-space: pre-wrap; font-family: Arial, Helvetica, sans-serif;"> ){//查询的方法,</span><pre name="code" class="java" style="font-size: 14px; line-height: 26.25px;"> <span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);"> model.addAttribute(</span><span class="string" style="margin: 0px; padding: 0px; border: none; color: blue; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">"name"</span><span style="margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">, name); </span>
<span style="white-space: pre-wrap; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">model.addAttribute(</span><span class="string" style="white-space: pre-wrap; margin: 0px; padding: 0px; border: none; color: blue; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">"age"</span><span style="white-space: pre-wrap; margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">, age); </span>
return "qiuqiu";//返回数据至qiuqiu.jsp
;}
然后写一个qiuqiu.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
获取的参数是<a>${name}</a>
获取的参数是<a>${age}</a>
</body>
</html>
基本到这里实现了一个简单的springmvc的框架。
然后向里面添加hibernate以及spring事务
3 配置hibernate,spring事务,基本主要就是配置一个xml文件。spring-common.jsp
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 此xml用于连接数据库设置事务等公用方式 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!--注解的实体 -->
<property name="annotatedClasses">
<list>
<value>com.gaoyajun.spring.entity.User</value>
</list>
</property>
</bean>
<!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置事务,使用代理的方式 -->
<bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
<!-- 为事务代理工厂Bean注入事务管理器 -->
<property name="transactionManager" ref="transactionManager"></property>
<property name="target" ref="userDao" />
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED </prop>
</props>
</property>
</bean>
<bean id="userDaoBase" class="com.gaoyajun.spring.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--注意这里的userDao,在上面transactionManager的target的指向其实是这个bean,这个是spring的事务的配置,为bean添加同一的事务管理-->
<bean id="userDao" parent="transactionProxy">
<property name="target" ref="userDaoBase" />
</bean>
</beans>
然后再配置完成后开始做简单的数据库的交互
第一步,添加用户,先写一个用户表的实体user.java
package com.gaoyajun.spring.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="T_USER")
public class User {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
@Column(length=32)
private String id;
@Column(length=32)
private String name;
@Column(length=32)
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
然后再写用户类的操作的类
UserDao,以及实现类UserDaoImpl,
package com.gaoyajun.spring.dao;
import com.gaoyajun.spring.entity.User;
public interface UserDao {
public User getUser(String id);
public boolean updateUser(User user);
public void addUser(User user);
}
package com.gaoyajun.spring.dao.impl;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import com.gaoyajun.spring.dao.UserDao;
import com.gaoyajun.spring.entity.User;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public User getUser(String id) {
String hql = "from User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (User)query.uniqueResult();
}
@Override
public boolean updateUser(User user) {
sessionFactory.getCurrentSession().save(user);
return false;
}
@Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
}
然后再看前端
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="love.do" method="post">
<input value="李四" name="name">
<input value="二十" name="age">
<input type="submit" value="提交">
</form>
</body>
</html>
流程为工程启动,进入index.jsp。点击提交,进入love.do,然后在userDao里保存数据至数据库。