springmvc+hibernate集成

阅读更多

springmvc+hibernate集成
springmvc+hibernate集成_第1张图片
 

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名
	 * 
	 * 
	 */
	@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 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 queryCustomer() {
		
		//System.out.println(sessionFactory);

		//Configuration config=new Configuration().configure("config/hibernet/hibernate.cfg.xml");
		
		//SessionFactory f=config.buildSessionFactory();
		
		Session session=sessionFactory.openSession();
		
		List 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 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映射文件


   
   
   
   	
   	
   		
   			
   		
   	
	   	
	   	
	   	
	   	
	   	
	   	
	   	
	   	
	   	   	
   	
   
   

 6、service接口实现

package com.ai.customer.service;

import java.util.List;

import com.ai.customer.model.CustomerInfo;

public interface ICustomerService {

	//查询Customer
	public List 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 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配置文件


    
     
	    
		
	
		
			
				org.hibernate.dialect.MySQLDialect
			
			
				jdbc:mysql://localhost:3306/data
			
			root
			123456
			
				com.mysql.jdbc.Driver
			
			
		
		10
		
		
		true
		
		
		50
		
		
		23
		
		
		false
		
		
		true
		
		
		gbk
	
		
		
		
		5
		
		
		500
		
		
		1800
		
		
		0
		
		
		121
		
		
		5
		
		true
	
		
	
	

    
    
   
    

 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配置文件



	
	
	
	
	
		
		 
		
		
			classpath:config/hibernet/hibernate.cfg.xml
		
		
	
	
	
	
		
	

	
	
		
		  
	          
	        
	            PROPAGATION_REQUIRED,-Exception  
	            PROPAGATION_REQUIRED,-myException  
	            PROPAGATION_REQUIRED  
	            PROPAGATION_REQUIRED,readOnly
	            PROPAGATION_REQUIRED  
	          
	      
	

 12、spring-mvc.xml配置文件



	
	



 
 



 
     
     
       10000000  
     
    



  
  
 
 
 	
 		
  
 

 13、web.xml配置文件信息



  springmvc_sh
  
    login/login.jsp
  
  
    contextConfigLocation
    classpath*:config/spring/spring-appliction.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    spring
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath*:config/spring/spring-*.xml
    
    1
  
  
    spring
    *.do
  
  
    org.springframework.web.context.request.RequestContextListener
  
  
    codeUTF-8
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
    
      forceEncoding
      true
    
  
  
    codeUTF-8
    /*
  


	
		404
		/login/loginIput.jsp
	
	
		500
		/login/login.jsp
	

 

  • springmvc+hibernate集成_第2张图片
  • 大小: 187.3 KB
  • 查看图片附件

你可能感兴趣的:(springmvc)