Spring MVC系列:(6)添加用户的小案例
admin
2023-06-05 21:21:53
0


1、添加数据库表

使用sqlplus打开数据库

sqlplus scott/tiger

创建emps数据表

create table emps(
	id varchar(32) not null,
	username varchar(20) not null,
	salary number(6,2),
	hiredate date
);


Spring MVC系列:(6)添加用户的小案例


2、添加jar包

项目需要的jar包有spring-core、spring-web、spring-webmvc、oracle数据库驱动、c3p0数据库连接池、dbutils。


jar包分类具体jar包
spring-core


commons-logging-1.2.jar

spring-beans-3.2.5.RELEASE.jar

spring-context-3.2.5.RELEASE.jar

spring-core-3.2.5.RELEASE.jar

spring-expression-3.2.5.RELEASE.jar


spring-webspring-web-3.2.5.RELEASE.jar
spring-webmvcspring-webmvc-3.2.5.RELEASE.jar
oracle数据库驱动

ojdbc5.jar

位于:OracleDB\product\11.2.0\dbhome_1\jdbc\lib\ojdbc5.jar

c3p0数据库连接池
c3p0-0.9.1.2.jar
dbutilscommons-dbutils-1.6.jar


3、配置

添加jar包之后,要进行配置:

(1)将springmvc加入到web项目中,需要配置web.xml、springmvc.xml文件

(2)使用c3p0,需要配置c3p0-config.xml文件


web.xml



  emp
  
    index.jsp
  
  
  
  	springmvc
  	org.springframework.web.servlet.DispatcherServlet
	
        contextConfigLocation
        classpath:springmvc.xml
      
  
  
  	springmvc
  	*.action
  
  
  
  
      CharacterEncodingFilter
      org.springframework.web.filter.CharacterEncodingFilter
      
            encoding
            UTF-8
        
  
  
      CharacterEncodingFilter
      /*
    

springmvc.xml




	

c3p0-config.xml


    
        jdbc:oracle:thin:@127.0.0.1:1521:orcl
        oracle.jdbc.driver.OracleDriver
        scott
        tiger
		2
		5
		1
		5
        1000
    


4、工具类编写

SecurityUtils用来提供UUID,而JDBCUtils用来获取DataSource。


SecurityUtils.java

package com.rk.utils;

import java.util.UUID;

public class SecurityUtils {
	public static String getUUID()
    {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

JDBCUtils.java

package com.rk.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
	/**
	 * 去src目录下加载c3p0-config.xml配置文件
	 */
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	/**
	 * 获取数据源
	 */	
	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}
}


5、从entity到action


Employee.java

package com.rk.entity;

import java.util.Date;

public class Employee {
	private String id;
	private String username;
	private Double salary;
	private Date hiredate;
	public Employee(){}
	
	public Employee(String id, String username, Double salary, Date hiredate) {
		this.id = id;
		this.username = username;
		this.salary = salary;
		this.hiredate = hiredate;
	}


	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
	
}


EmpDao.java

package com.rk.dao;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import com.rk.entity.Employee;
import com.rk.utils.JDBCUtils;
import com.rk.utils.SecurityUtils;

public class EmpDao {
	public void add(Employee emp) throws Exception{
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "insert into emps(id,username,salary,hiredate) values(?,?,?,?)";
		Object[] params = {SecurityUtils.getUUID(),emp.getUsername(),emp.getSalary(),new Timestamp(emp.getHiredate().getTime())};
		queryRunner.update(sql,params);
	}
	
	@Test
	public void run() throws Exception{
		Employee emp = new Employee();
		emp.setUsername("小明");
		emp.setSalary(88.88);
		emp.setHiredate(new Date());
		add(emp);
	}
}


EmpService.java

package com.rk.service;

import com.rk.dao.EmpDao;
import com.rk.entity.Employee;

public class EmpService {
	private EmpDao empDao;
	public void setEmpDao(EmpDao empDao) {
		this.empDao = empDao;
	}
	
	public void register(Employee emp) throws Exception{
		empDao.add(emp);
	}
}


EmpAction.java

package com.rk.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.rk.entity.Employee;
import com.rk.service.EmpService;

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

}


6、对dao/service/action的配置


spring-emp.xml




	
	
      
	
	
		
	

	
	
		
	

	
	
		
	

      
     
       
      
      
	
	
	
		
		
	


7、JSP页面


WebRoot/jsp/index.jsp

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



  
    添加员工
  
  
  
    
    	
    		
    			员工姓名:
    			
    		
    		
    			员工薪水:
    			
    		
    		
    			入职时间:
    			
    		
    		
    			
    				
    			
    		
    	
    
  


WebRoot/jsp/success.jsp

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



  
    添加成功
  
  
  
	${message }
  


演示

Spring MVC系列:(6)添加用户的小案例



相关内容

热门资讯

真实感,AI时代写作的生命力所... AI时代,对于许多人来说,因为有了各种智能工具的加持,写作似乎变得容易了。通过提出命题、投喂内容,无...
一个以科技为名的节日,在一座深... 5月23日,2026年上海科技节在上海科技馆正式开幕,同日还将举办第五届上海科技传播大会,并见证上海...
原创 靠... 谁能想到,一笔眼看能让90后创始人躺赚140亿的AI公司收购案,会被商务部一记重拳紧急喊停。 江西小...
特朗普称美伊协议基本谈成 美东时间23日下午,美国总统特朗普在社交媒体发文,称美国与伊朗已经基本谈成一份协议。(央视记者 刘骁...
以媒:美伊协议或“非常不利”,... 新华社耶路撒冷5月23日电(记者陈君清 庞昕熠)以色列媒体23日报道,以总理内塔尼亚胡当晚召集执政联...
独属于AI时代的故事|新华走笔 来源:5月22日《新华每日电讯》 作者:孙正好 AI浪潮激荡,总会在那些平凡而普通的个体生命中,惊起...
原创 i... 2026年5月20日,iQOO带来了全新旗舰机型iQOO 15T,同时一口气上新iQOO Pad6 ...
巴基斯坦消息人士:美伊接近达成... 新华社伊斯兰堡5月23日电(记者杨恺)巴基斯坦官方消息人士23日告诉新华社记者,美国与伊朗接近达成一...
特朗普又说美伊“越来越接近”达... 新华社华盛顿5月23日电(记者黄强 徐剑梅)美国总统特朗普23日说,美国与伊朗的谈判“越来越接近”达...