千家信息网

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

发表于:2026-10-31 作者:千家信息网编辑
千家信息网最后更新 2026年10月31日,1、添加数据库表使用sqlplus打开数据库sqlplus scott/tiger创建emps数据表create table emps( id varchar(32) not null,
千家信息网最后更新 2026年10月31日Spring MVC系列:(6)添加用户的小案例


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);



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 }  


演示



0