springmvc+hibernate集成
1、控制器
package com.ai.customer.controller;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;
import com.ai.customer.model.CustomerInfo;
import com.ai.customer.service.ICustomerService;
/*
* @Controller
* 控制器
*
* @Service
* 用于标注业务层组件
*
* @Repository
* 用于标注数据访问组件,即DAO组件
*
* @Component
* 泛指组件,当组件不好归类的时候我们可以使用这个注解进行标注,(现在可以都用此注解)
* 同上其实跟@Service/@Repository/@Controller 一样只不过它们 利用分层 好区分
*
* @Autowired\@Resource
* 自动注入 实现的的是 setXxx()方法 getXxx()方法
*
* @RequestMapping(value='xxx.do',method=RequestMethod.GET/RequestMethod.POST/..)
* value访问路径/method请发的方法,注:请求方法一旦设定只能使用指定的方法访问
* 在类前面定义,则将url和类绑定。
* 在方法前面定义,则将url和类的方法绑定
*
* @RequestParam("name") ==uname
* 一般用于将指定的请求参数付给方法中形参
*
* @Scope
* 创建 bean的作用域 singleton-->多例 Property-->多例 还有request 等等
* 使用reqeust 需要在web.xml 配置监听器 具体去网上搜索
*
*/
@Controller
public class CustomerAction {
@Autowired
private ICustomerService customerService;
@RequestMapping(value="/login.do")
public String postLogingMethod(HttpServletRequest reqeust){
System.out.println("访问到了控制器");
System.out.println(customerService);
CustomerInfo cus=customerService.queryCustomer().get(0);
System.out.println("身份证Id"+cus.getCardid());
reqeust.getSession().setAttribute("cus", cus);
return "page/admin/index";
}
/*
* @RequestParam 使用
* @RequestParam("name") ==uname 一般用于将指定的请求参数付给方法中形参
*/
@RequestMapping("/param.do" )
public String paramMethod(@RequestParam("name")String uname){
System.out.println("uname:"+uname);
//重定向 页面
return "redirect:index.jsp";
}
/*
* 页面传递过来的参数 自动赋值 xxx.do?name=张三&customerid=12342423 post get请求皆可
* ajax $.xxx("xxx.do",{name:'张三',customerid:'123435345'},function(data){});
*/
@RequestMapping("/rq.do")
public String allMethod(String customerid,String name){
System.out.println(customerid+":"+name);
return "index";
}
/*
* 封装实体对象 表单提交数据 表单中cus.name名
* <input type="text" name="cus.name">
* <input type="text" name="cus.customerid">
*/
@RequestMapping("/cus.do")
public String setCustomer(CustomerInfo cus){
System.out.println(cus.getCustomerid()+":"+cus.getName());
return "index";
}
/*springmvc 中获取request对象
* 1、可以直接在方法中定义 getReqeust(CustomerInfo cus,HttpServletRequest req)
*
* 2、使用注解Autowired
* @Autowired
* private HttpServletRequest request;
*
* 3、使用如下方法
* ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
* servletRequestAttributes.getRequest();
*
*/
@RequestMapping("/reqeust.do")
public String getReqeust(CustomerInfo cus,HttpServletRequest req){
//获取reqeust对象
req.setAttribute("cus", cus);
//获取session对象
req.getSession();
return "index";
}
/* 获取reponse 可以使用如下方法 也可以使用:在方法中传递
* getResponse(String name,String customerid,HttpservletResponse response)
*/
@RequestMapping("/response.do")
public void getResponse(String name,String customerid,HttpServletResponse response){
response.setContentType("text/html;charset=utf-8");
System.out.println(name+":"+customerid);
try {
response.getWriter().write(customerid.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
/*ModelAndView 与 ModelMap 的区别
*
* ModelAndView
* 作用一 :设置转向地址/对象必须手动创建(主要区别)
*
* 作用二:用于传递控制方法处理结果数据到结果页面,
* 也就是说我们把需要在结果页面上需要的数
* 据放到ModelAndView对象中即可,他
* 的作用类似于request对象的setAttr
* ibute方法的作用,用来在一个请求过程中
* 传递处理的数据。通过以下方法向页面传递 参数:addObject(String key,Object value);
*
*
* ModelMap
*一、 ModelMap的实例是由bboss mvc框架自动创建并作为控制器方法参数传入,
* 用户无需自己创建。
*
* 二、ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,
* 他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数:
* addAttribute(String key,Object value);
* 在页面上可以通过el变量方式$key或者bboss的一系列数据展示标签获取并展示modelmap中的数据。
* modelmap本身不能设置页面跳转的url地址别名或者物理跳转地址,那么我们可以通过控制器方法的返回值来设置跳转url地址
* 别名或者物理跳转地址。
*/
@RequestMapping("/modelmap.do")
public String modelMapMethod(String name,ModelMap model) {
//将数据放置到ModelMap对象model中,第二个参数可以是任何java类型
model.addAttribute("modelMap",name);
//返回跳转地址
return "index";
}
@RequestMapping("/modelandmap.do")
public ModelAndView modelAndMapMethod(String name) {
//构建ModelAndView实例,并设置跳转地址
ModelAndView view = new ModelAndView("index");
//将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
view.addObject("modelAndMap",name);
//返回ModelAndView对象view
return view;
}
}
2、dao接口
package com.ai.customer.dao;
import java.util.List;
import com.ai.customer.model.CustomerInfo;
public interface ICustomerDao {
//查询Customer
public List<CustomerInfo> queryCustomer();
public String all();
}
3、dao接口实现
package com.ai.customer.daoimpl;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.ai.customer.dao.ICustomerDao;
import com.ai.customer.model.CustomerInfo;
@Repository
public class CustomerDao implements ICustomerDao {
@Autowired
private SessionFactory sessionFactory;
// public void setSessionFactory(SessionFactory sessionFactory) {
// this.sessionFactory = sessionFactory;
// }
public List<CustomerInfo> queryCustomer() {
//System.out.println(sessionFactory);
//Configuration config=new Configuration().configure("config/hibernet/hibernate.cfg.xml");
//SessionFactory f=config.buildSessionFactory();
Session session=sessionFactory.openSession();
List<CustomerInfo> cus=session.createQuery("from CustomerInfo").list();
session.close();
return cus;
}
public String all(){
return "注解成功";
}
public static void main(String[] args) {
Configuration config=new Configuration().configure("config/hibernet/hibernate.cfg.xml");
SessionFactory f=config.buildSessionFactory();
Session session=f.openSession();
List<CustomerInfo> cus=session.createQuery("from CustomerInfo").list();
session.close();
System.out.println(cus.get(0).getCustomerid());
// System.out.println(f.getCurrentSession().createQuery("from CustomerInfo").list());
}
}
4、实体类
package com.ai.customer.model;
import java.io.Serializable;
public class CustomerInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String customerid;//个人编号
private String cardid;//身份证id
private String name;//姓名
private String sex;//性别(男、女)
private String birthDate;//出生日期
private String householdRegister;//户籍所在地址
private String photo;//照片
private String regTime;
private String loginCount;
private String lastLoginTime;
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
public String getCardid() {
return cardid;
}
public void setCardid(String cardid) {
this.cardid = cardid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getHouseholdRegister() {
return householdRegister;
}
public void setHouseholdRegister(String householdRegister) {
this.householdRegister = householdRegister;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) {
this.regTime = regTime;
}
public String getLoginCount() {
return loginCount;
}
public void setLoginCount(String loginCount) {
this.loginCount = loginCount;
}
public String getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(String lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
5、customerinfo.hbm.xml映射文件
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.ai.customer.model.CustomerInfo" table="customerInfo"> <id name="customerid" column="customerid" type="java.lang.String"> <generator class="assigned"/> </id> <property name="cardid" type="java.lang.String"/> <property name="name" type="java.lang.String"/> <property name="sex" type="java.lang.String"/> <property name="birthDate" type="java.lang.String"/> <property name="householdRegister" type="java.lang.String"/> <property name="photo" type="java.lang.String"/> <property name="regTime" type="java.lang.String"/> <property name="loginCount" type="java.lang.String"/> <property name="lastLoginTime" type="java.lang.String"/> </class> </hibernate-mapping>
6、service接口实现
package com.ai.customer.service;
import java.util.List;
import com.ai.customer.model.CustomerInfo;
public interface ICustomerService {
//查询Customer
public List<CustomerInfo> queryCustomer();
public String all();
}
7、接口实现
package com.ai.customer.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.ai.customer.dao.ICustomerDao;
import com.ai.customer.model.CustomerInfo;
import com.ai.customer.service.ICustomerService;
@Service
public class CustomerService implements ICustomerService{
@Autowired
private ICustomerDao customerDao;
public List<CustomerInfo> queryCustomer() {
return customerDao.queryCustomer();
}
public String all() {
// TODO Auto-generated method stub
return customerDao.all();
}
}
8、JDBC类
package com.ai.util;
import java.beans.PropertyVetoException;
import java.io.*;
import java.sql.*;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtil {
private static Logger log=Logger.getLogger(JDBCUtil.class);
//使用c3p0 连接池
private static ComboPooledDataSource ds;
static {
ds=new ComboPooledDataSource();
//加载驱动
try {
ds.setDriverClass(getProperties("jdbc.driver"));
} catch (PropertyVetoException e) {
log.error("加载驱动失败",e);
e.printStackTrace();
}
//数据库连接
ds.setJdbcUrl(getProperties("jdbc.url"));
//用户
ds.setUser(getProperties("jdbc.username"));
//密码
ds.setPassword(getProperties("jdbc.password"));
//初始化开几个连接
ds.setInitialPoolSize(Integer.parseInt(getProperties("jdbc.initialPoolSize")));
//最大开几个
ds.setMaxPoolSize(Integer.parseInt(getProperties("jdbc.maxPoolSize")));
//最小开几个
ds.setMinPoolSize(Integer.parseInt(getProperties("jdbc.minPoolSize")));
//设置等待时间
ds.setMaxIdleTime(Integer.parseInt(getProperties("jdbc.maxIdleTime")));
}
public final static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException e) {
log.error("获取连接失败",e);
e.printStackTrace();
}
return null;
}
//关闭连接
public final static void closeConntion(ResultSet re,PreparedStatement psnt,Connection conn){
if(re!=null)
try {
re.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(psnt!=null)
try {
psnt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 读取连接数据文件
public final static String getProperties(String name){
InputStream str=Thread.currentThread().getContextClassLoader().getResourceAsStream("config/hibernet/jdbc.properties");
Properties properties=new Properties();
try {
properties.load(str);
return properties.getProperty(name);
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error("读取jdbc.properties文件不存在",e);
} catch (IOException e) {
e.printStackTrace();
log.error("读取jdbc.properties文件异常",e);
}
return "";
}
public static String query(){
Connection conn=JDBCUtil.getConnection();
PreparedStatement psnt=null;
ResultSet re=null;
String sql="select * from customerinfo";
try {
psnt=conn.prepareStatement(sql);
re=psnt.executeQuery();
if(re.next()){
return re.getString("customerid");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeConntion(re, psnt, conn);
}
return "";
}
public static void main(String[] args) {
System.out.println(JDBCUtil.query());
// System.out.println(getConnection());
// System.out.println(getProperties("driver"));
// System.out.println(getProperties("username"));
// System.out.println(getProperties("password"));
// System.out.println(getProperties("url"));
}
}
9、hibernate.cfg.xml配置文件
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!--表明以下的配置是针对session-factory配置的,SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操作-->
<session-factory>
<!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。-->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/data
</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!--数据库连接池的大小-->
<property name="hibernate.connection.pool.size">10</property>
<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率-->
<property name="hibernate.show_sql">true</property>
<!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->
<property name="jdbc.fetch_size">50</property>
<!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->
<property name="jdbc.batch_size">23</property>
<!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置非常有帮助-->
<property name="jdbc.use_scrollable_resultset">false</property>
<!--connection.useUnicode连接数据库时是否使用Unicode编码-->
<property name="Connection.useUnicode">true</property>
<!--connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为gbk,用gb2312有的字符不全-->
<property name="connection.characterEncoding">gbk</property>
<!--连接池的最小连接数-->
<property name="hibernate.c3p0.min_size">5</property>
<!--最大连接数-->
<property name="hibernate.c3p0.max_size">500</property>
<!--连接超时时间-->
<property name="hibernate.c3p0.timeout">1800</property>
<!--statemnets缓存大小-->
<property name="hibernate.c3p0.max_statements">0</property>
<!--每隔多少秒检测连接是否可正常使用 -->
<property name="hibernate.c3p0.idle_test_period">121</property>
<!--当池中的连接耗尽的时候,一次性增加的连接数量,默认为3-->
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.validate">true</property>
<mapping resource="com/ai/customer/model/CustomerInfo.hbm.xml" />
</session-factory>
</hibernate-configuration>
10、jdbc.properties配置文件
#JDBC连接驱动
jdbc.driver=com.mysql.jdbc.Driver
#服务器连接地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/data?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
#用户名
jdbc.username=root
#密码
jdbc.password=123456
#连接池
#初始化连接
jdbc.initialPoolSize=10
# 最大连接
jdbc.maxPoolSize=20
#最小连接
jdbc.minPoolSize=5
#等待时间s
jdbc.maxIdleTime=30000
11、spring-appliction.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 配置数据源 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/data"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> --> <!-- hibernet 配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- <property name="dataSource" ref="dataSource"/> --> <property name="configLocation"> <value>classpath:config/hibernet/hibernate.cfg.xml</value> </property> </bean> <!-- 配置事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 使用代理配置事务管理 --> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager" /> <property name="transactionAttributes"> <props> <!-- 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。 --> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop> <prop key="del*">PROPAGATION_REQUIRED</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>
12、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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.ai.customer" />
<!-- 启动注解 -->
<mvc:annotation-driven />
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为10MB -->
<property name="maxUploadSize">
<value>10000000</value>
</property>
</bean>
<!-- 静态文件访问 -->
<mvc:default-servlet-handler/>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
13、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_sh</display-name> <welcome-file-list> <welcome-file>login/login.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring/spring-appliction.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring/spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <filter> <filter-name>codeUTF-8</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>codeUTF-8</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/login/loginIput.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/login/login.jsp</location> </error-page> </web-app>