Spring MVC series: (6) Adding a user's small case

Source: Internet
Author: User


1. Adding database tables

Open a database using Sqlplus

Sqlplus Scott/tiger

Creating Emps Data tables

CREATE TABLE emps (id varchar (+) not null,username varchar (a) not null,salary number (6,2), hiredate date);


650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M00/87/BA/wKioL1fgPVKwOeYcAABg9y-LE3c091.jpg "title=" 001. JPG "alt=" wkiol1fgpvkwoeycaabg9y-le3c091.jpg "/>


2. Add JAR Package

The jar packages required for the project are spring-core, spring-web, spring-webmvc, Oracle Database driver, c3p0 database connection pool, Dbutils.


JAR Package Classification Specific JAR Package
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-web Spring-web-3.2.5.release.jar
Spring-webmvc Spring-webmvc-3.2.5.release.jar
Oracle Database Driver

Ojdbc5.jar

Located in:Oracledb\product\11.2.0\dbhome_1\jdbc\lib\ojdbc5.jar

C3P0 Database Connection Pool
C3p0-0.9.1.2.jar
Dbutils Commons-dbutils-1.6.jar


3. Configuration

After adding the jar package, configure:

(1) add Springmvc to the Web project, you need to configure The. xml, springmvc.xml file

(2) use c3p0, need to configure C3p0-config.xml file


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>emp</display-name>  <welcome-file-list>     <welcome-file>index.jsp</welcome-file>  </welcome-file-list >  <!--  Register SPRINGMVC Framework Core Controllers  -->  <servlet>  < Servlet-name>springmvc</servlet-name>  <servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param>         <param-name>contextConfigLocation</param-name>         <param-value>classpath:springmvc.xml</param-value>      </init-param>  </servlet>   <servlet-mapping>  <servlet-name>springmvc</servlet-name>  < url-pattern>*.action</url-pattern>  </servlet-mapping>    <!--   Coding Filters  -->  <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>

Springmvc.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/schema/beans" xmlns: mvc= "http://www.springframework.org/schema/mvc" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://www.springframework.org/schema/beans HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/BEANS/SPR Ing-beans.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc . xsd "><import resource=" com/rk/config/spring-emp.xml "/></beans>

C3p0-config.xml

<c3p0-config> <default-config> <property name= "jdbcurl" >jdbc:oracle:thin:@127.0.0.1:1521:orcl& lt;/property> <property name= "driverclass" >oracle.jdbc.driver.OracleDriver</property> <pro Perty name= "user" >scott</property> <property name= "password" >tiger</property><property Nam e= "acquireincrement" >2</property><property name= "initialpoolsize" >5</property><property Name= "minpoolsize" >1</property><property name= "maxpoolsize" >5</property> <property name= " MaxIdleTime ">1000</property> </default-config></c3p0-config>


4, the tool class writing

Securityutils is used to provide uuid, while jdbcutils is used to get datasource.


Securityutils.java

Package Com.rk.utils;import Java.util.uuid;public class securityutils {public static String getuuid () {return U    Uid.randomuuid (). toString (). replaceall ("-", "" "); }}

Jdbcutils.java

Package Com.rk.utils;import Com.mchange.v2.c3p0.combopooleddatasource;public class jdbcutils {/** * Go to src directory to load the C3p0-config.xml configuration file */private static Combopooleddatasource DataSource = new Combopooleddatasource ();/** * Get data source */public static Combopooleddatasource getdatasource () {return dataSource;}}


5. From entity to 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 (?,?,?,?)"; O Bject[] params = {securityutils.getuuid (), emp.getusername (), emp.getsalary (), new Timestamp ( Emp.gethiredate (). getTime ())};queryrunner.update (sql,params);} @Testpublic  void run ()  throws exception{employee emp = new employee (); Emp.setusername ("xiaoming"); 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 {//business Layer private empservice empservice;public void  Setempservice (empservice empservice)  {this.empservice = empservice;} Encapsulates form parameters into the Employee entity public empaction () {this.setcommandclass (employee.class);} Custom String->date Converters @overrideprotected void&nbSp;initbinder (httpservletrequest request, servletrequestdatabinder binder)  throws  Exception {binder.registercustomeditor (date.class, new customdateeditor (new  SimpleDateFormat ("yyyy-mm-dd"),  true));} @Overrideprotected  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",   "operation succeeded"); modelandview.setviewname ("success"); return modelandview;}}


6, the configuration of dao/service/action


Spring-emp.xml

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "    xmlns:mvc=" Http://www.springframework.org/schema/mvc "     xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"     xsi:schemalocation= "         http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--  Register Empdao class  --><bean  id= "empdaoid"  class= "com.rk.dao.EmpDao" ></bean>      <!--   Register Empservice class  --><bean id= "empserviceid"  class= "com.rk.service.EmpService" >< Property name= "EMPDAO " ref=" empdaoid "/></bean><!--  Registration Action --><bean name="/add.action "  class= "com.rk.action.EmpAction" ><property name= "empservice"  ref= "empserviceid"/></ Bean><!-- /index.action request, forward directly to/jsp/index.jsp page  --><bean name= "/index.action"   class= "org.springframework.web.servlet.mvc.ParameterizableViewController" ><property name= "viewName"  value= "index" ></property></bean>    <!--  Mapper (frame)  -->       <bean class= " Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping "></bean>             <!--  Adapters (frames)  -->       <bean class= "org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" ></bean >  <!--  View Resolver (frame)  --><bean class= "org. springframework.web.servlet.view.InternalResourceViewResolver "><property name=" Prefix " value= "/jsp/" ></property><property name= "suffix"  value= ". jsp" ></property></bean ></beans>


7. JSP Page


webroot/jsp/index.jsp

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >


webroot/jsp/success.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML public "-//w3c//dtd HTML 4.01 transitional//en" >


Demonstrate

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/87/BE/wKiom1fgPS7zTDLcAAB5kVpk4TI450.gif "title=" 002. GIF "alt=" wkiom1fgps7ztdlcaab5kvpk4ti450.gif "/>



Spring MVC series: (6) Adding a user's small case

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.