springmvc + jdbcTemplate + mysql

         使用springmv 和 springjdbc  加上mysql数据库做了个练习,具体的代码如下:

         1.web.xml

         

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
  
	<!-- 注册springmvc核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	
	<!-- 注册争对POST请求的编码器 -->
		<filter>
		<filter-name>CharacterEncodingFilter</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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	

</web-app>

          spring-emp.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:p="http://www.springframework.org/schema/p"
	    xmlns:context="http://www.springframework.org/schema/context"
		
      xsi:schemaLocation="
	
	  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.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">
      
      <!-- 1. 数据源对象: C3P0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
		<property name="user" value="root"></property>
		<property name="password" value="root"></property>
		<property name="initialPoolSize" value="3"></property>
		<property name="maxPoolSize" value="10"></property>
		<property name="maxStatements" value="100"></property>
		<property name="acquireIncrement" value="2"></property>
	</bean>
	
	
	<!-- 2. 创建JdbcTemplate对象 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- dao 实例 -->
	<bean id="empDaoID" class="com.example.emp.dao.UserDao">
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>

      

      
      <!-- 注册EmpService类 -->
      <bean id="empServiceID" class="com.example.emp.service.EmpService">
      		<property name="empDao" ref="empDaoID"/>
      </bean>
      

	  <!-- 注册Action -->
      <bean name="/add.do" class="com.example.emp.action.EmpAction">
      	<property name="empService" ref="empServiceID"/>
      </bean>
		
	  <!-- 映射器 -->	      
      <!-- 适配器 -->
      
      <!-- 视图解析器 -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		<property name="prefix" value="/"/>
      		<property name="suffix" value=".jsp"/>
      </bean>

</beans>      
	
	
	
	
	
	
	

3.EmpAction

 

 

package com.example.emp.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

import com.example.emp.entity.Emp;
import com.example.emp.service.EmpService;


/**
 * 员工管理模块
 * 控制器
 * @author AdminTC
 */
@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
	//业务层
	private EmpService empService;
	public void setEmpService(EmpService empService) {
		this.empService = empService;
	}
	//将表单参数封装到Emp实体中
	public EmpAction(){
		this.setCommandClass(Emp.class);
	}
	//自定义String->Date的转换器
	@Override
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("dd-MM-yy"),true));
	}
	@Override
	protected ModelAndView handle(
			HttpServletRequest request,
			HttpServletResponse response, 
			Object obj, 
			BindException error)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		Emp emp = (Emp) obj;
		System.out.println(emp.getHiredate());
		empService.register(emp);
		
		modelAndView.addObject("message","操作成功");
		modelAndView.setViewName("success");
		return modelAndView;
	}
}






2.dao

 

 

package com.example.emp.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;

import com.example.emp.Dept;
import com.example.emp.entity.Emp;

public class UserDao {
	
	// IOC容器注入
//	private DataSource dataSource;
//	public void setDataSource(DataSource dataSource) {
//		this.dataSource = dataSource;
//	}
	
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	
	public void save(Emp emp) {
		String id = "8";
		String sql = "insert into emps values( " + id + "," + "'" +  emp.getUsername() + "'" + "," + "'" +  emp.getSalary() + "'" + "," + "'" +  emp.getHiredate() + "'"      +      " );";
		jdbcTemplate.update(sql);
	}
	
	public Dept findById(int id) {
		String sql = "select * from Dept where deptId=?";
		List<Dept> list = jdbcTemplate.query(sql,new MyResult(), id);
		return (list!=null && list.size()>0) ? list.get(0) : null;
	}
	
	public List<Dept> getAll() {
		String sql = "select * from t_dept";
		List<Dept> list = jdbcTemplate.query(sql, new MyResult());
		return list;
	}
	
	
	
	
	class MyResult implements RowMapper<Dept>{
		// 如何封装一行记录
		public Dept mapRow(ResultSet rs, int arg1) throws SQLException {
			Dept dept = new Dept();
			dept.setDeptId(rs.getInt("deptId"));
			dept.setDeptName(rs.getString("deptName"));
			return dept;
		}

		
		
		
	}
}








3.service

 

 

package com.example.emp.service;

import com.example.emp.dao.UserDao;
import com.example.emp.entity.Emp;



/**
 * 员工管理模块
 * 业务层实现类
 * @author AdminTC
 */
public class EmpService {
	private UserDao empDao;
	public void setEmpDao(UserDao empDao) {
		this.empDao = empDao;
	}
	/**
	 * 增加员工
	 */
	public void register(Emp emp) throws Exception{
		empDao.save(emp);
	}
}









4.entity

 

 

package com.example.emp.entity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 员工 
 * @author AdminTC
 */
public class Emp {
	private String id;//编号
	private String username;//姓名
	private String salary;//薪水
	private String hiredate;//入职时间
	public Emp(){}
	public String getId() {
		return UUID.randomUUID().toString();
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
}






欢迎加Q群交流学习:819443769

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值