The MVC pattern Design of Java Web Foundation (i)--using HttpServlet to implement MVC layered design, the DAO layer uses Dbutils to implement the link with the database.

Source: Internet
Author: User
Tags reflection java web

A: 1. The final realization:

2. The directory structure of the case:

3. Jar packages used in the case:

Two: Case of linked database hierarchy relationship: Database is: MySQL, database name: DSM, table name: Customers

The database table looks like this:

The hierarchical relationships of the classes used in the database implementation:

The source code in the Java class above:

Dao.java:

Package Com.guodiantong.mvc.dao;import Java.lang.reflect.parameterizedtype;import Java.lang.reflect.type;import Java.sql.connection;import Java.util.list;import Org.apache.commons.dbutils.queryrunner;import Org.apache.commons.dbutils.handlers.beanhandler;import Org.apache.commons.dbutils.handlers.BeanListHandler; Import Org.apache.commons.dbutils.handlers.scalarhandler;import Com.guodiantong.mvc.db.jdbcutils;public class Dao <T> {private Queryrunner queryrunner=new Queryrunner ();p rivate class<t> clazz;public Dao () {Type superclass =getclass (). Getgenericsuperclass (); if (superclass instanceof Parameterizedtype) {Parameterizedtype Parameterizedtype= (Parameterizedtype) superclass; Type[] Typeargs=parameterizedtype.getactualtypearguments (); if (typeargs!=null&&typeargs.length>0) {if (   Typeargs[0] instanceof Class) {clazz= (class<t>) typeargs[0]; }}}}/* * This method is to retrieve only one of the property values in a row of a table, that is, to return the value of a field, such as returning a record's customername, or returning the number of records in a datasheet. */public <E> E Getforvalue(String sql,object ... args) {Connection Connection=null;try {connection=jdbcutils.getconnection (); return (E) queryrunner.query (Connection, SQL, New Scalarhandler (), args);} catch (Exception e) {e.printstacktrace ();} Finally{jdbcutils.releaseconnection (connection);} return null;} /* * This method returns a set of data object entity classes, returning the List for T, which is essentially querying */public list<t> getforlist (String sql,object ... agrs) {Connection Connection=null;try {connection=jdbcutils.getconnection (); return queryrunner.query (Connection, SQL, new Beanlisthandler<t> (Clazz), AGRs);} catch (Exception e) {e.printstacktrace ();} Finally{jdbcutils.releaseconnection (connection);} return null;} /* Execute the query, and the result is an object in the data table (a record) whose essence is the query!  */Public T get (String sql,object ... agrs) {Connection connection=null; try {connection=jdbcutils.getconnection (); return queryrunner.query (Connection, SQL, new beanhandler<t> (Clazz) , AGRs);} catch (Exception e) {e.printstacktrace ();} Finally{jdbcutils.releaseconnection(connection);}  return null; }/* * This method encapsulates the insert, UPDATE, delete operation * SQL is the SQL statement * args is a placeholder */public void UPDATE (String sql,object ... args) {Connection conn Ection=null;try {connection=jdbcutils.getconnection (); Queryrunner.update (connection, SQL, args);} catch (Exception E ) {e.printstacktrace ();} Finally{jdbcutils.releaseconnection (connection);}}}

Jdbcutils.java

Package Com.guodiantong.mvc.db;import Java.sql.connection;import Java.sql.sqlexception;import Javax.sql.DataSource Import Com.mchange.v2.c3p0.combopooleddatasource;public class Jdbcutils {/* * release connection to database *  */public static void Releaseconnection (Connection Connection) {try {if (Connection!=null) {connection.close ();}} catch (Exception e) {          E.printstacktrace ();}} The private static DataSource datasource=null;static {/* * data source can only be created once */datasource=new combopooleddatasource ("Mvcapp");} public static Connection getconnection () throws Sqlexception{//datasource=new Combopooleddatasource ("Mvcapp"); If you want to place it here, you can create it once and compare the memory return datasource.getconnection ();}}

Customer.java:

Package Com.guodiantong.mvc.domain;public class Customer {  private Integer ID;  private String name;  Private String address;  Private String phone;public Integer getId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} Public String Getphone () {return phone;} public void Setphone (String phone) {this.phone = phone;}  Public Customer (Integer ID, string name, string address, String phone) {super (); this.id = Id;this.name = name;this.address = Address;this.phone = phone;} Public Customer () {super ();} @Overridepublic String toString () {return "Customer [id=" + ID + ", name=" + name + ", address=" + address+ ", phone=" + p Hone + "]";}  }

Customerdao.java:

Package Com.guodiantong.mvc.dao;import Java.util.list;import Com.guodiantong.mvc.domain.criteriacustomer;import Com.guodiantong.mvc.domain.customer;public interface Customerdao {public    list<customer> Getforlistwithcriteriacustomer (criteriacustomer cc);p ublic list<customer> getAll ();p ublic void Save (Customer Customer);p ublic customer get (integer ID);p ublic void Delete (integer ID); */* Returns the number of data bars using the name, based on the name of the query */public long GetCount Withname (String name);p ublic void update (Customer customer);}

Customerdaojdbcimpl.java:

Package Com.guodiantong.mvc.impl;import Java.util.list;import Com.guodiantong.mvc.dao.customerdao;import Com.guodiantong.mvc.dao.dao;import Com.guodiantong.mvc.domain.criteriacustomer;import Com.guodiantong.mvc.domain.customer;public class Customerdaojdbcimpl extends Dao<customer>implements Customerdao {public list<customer> Getforlistwithcriteriacustomer (Criteriacustomer cc) {String sql= "select ID, Name,address,phone from Customers WHERE "+" name? and address like? And phone like? "; return getforlist (SQL, Cc.getname (), cc.getaddress (), Cc.getphone ());} @Overridepublic list<customer> GetAll () {String sql= "select Id,name,address,phone from Customers"; return Getforlist (SQL);} @Overridepublic void Save (Customer customer) {String sql= "INSERT into Customers (Name,address,phone) VALUES (?,?,?)"; Update (SQL, Customer.getname (), customer.getaddress (), Customer.getphone ());;} @Overridepublic Customer get (Integer id) {String sql= "select Id,name,address,phone from Customers WHERE id=?"; return get (SQL, id);}      @Overridepublic void Delete (Integer id) {String sql= "delete from customers WHERE id=?"; Update (SQL, ID);} @Overridepublic long Getcountwithname (string name) {string Sql= "SELECT count (ID) from customers WHERE name=?"; return getforvalue (SQL, name);} @Overridepublic void Update (Customer customer) {String sql= "update customers SET name=?, address=?, phone=? WHERE id=? "; Update (SQL, Customer.getname (), customer.getaddress (), Customer.getphone (), Customer.getid ());}}

  Description: Dao.java and Jdbcutils.java are portable, in which projects can be used, Customerdao.java and Customerdaoimpl.java are based on specific projects to abstract the possible methods, Then let the bottom Dao.java the most basic additions and deletions and other functions to piece together the project page in the abstract method

Three: Writing JSP files in the project (JSP is essentially a servlet)

The most used in the case is HttpServletRequest request,httpservletresponse response The two parameters combine the form form in the page and the forwarding method to pass data between the page and the background servlet.

Jsp:index.jsp of the Start page:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ page import=" java.util.List "%> <%@ page import=" com.guodiant Ong.mvc.domain.Customer "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Jsp:addCustomer.jsp of new pages:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Edit the jsp:edit.jsp of the page:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ page import=" Com.guodiantong.mvc.domain.Customer "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Four. Control class servlet   Customerservlet.java in the background

Package Com.guodiantong.mvc.servlet;import Java.io.ioexception;import Java.lang.reflect.method;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.guodiantong.mvc.dao.customerdao;import Com.guodiantong.mvc.domain.criteriacustomer;import Com.guodiantong.mvc.domain.customer;import Com.guodiantong.mvc.impl.customerdaojdbcimpl;public Class Customerservlet extends HttpServlet {Customerdao customerdao=new customerdaojdbcimpl (); @Overrideprotected void Doget ( HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {doPost (req, resp);}     @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {     String Servletpath=req.getservletpath ();     System.out.println (Servletpath);            String methodname=servletpath.substring (1); Methodname=methodnamE.substring (0, Methodname.length ()-3); /* * Use reflection to get methodName corresponding method */try {method Method=getclass (). Getdeclaredmethod (MethodName, Ht     Tpservletrequest.class, Httpservletresponse.class); Use reflection to call the corresponding method Method.invoke (this, REQ,RESP);}     catch (Exception e) {e.printstacktrace (); Resp.sendredirect ("error.jsp");} }private void query (HttpServletRequest request,httpservletresponse response) throws Servletexception, ioexception{ String name=request.getparameter ("name"); String address=request.getparameter ("address"); String phone=request.getparameter ("phone"); Criteriacustomer criteriacustomer=new Criteriacustomer (name, address, phone); List<customer> Customers=customerdao.getforlistwithcriteriacustomer (Criteriacustomer); SYSTEM.OUT.PRINTLN (Customers); Request.setattribute ("Customers", customers); Request.getrequestdispatcher ("/    Index.jsp "). Forward (request, response);} private void Delete (HttpServletRequest request,httpservletresponse response) throwS ioexception{String idstr=request.getparameter ("id");        int id=0; try {id=integer.parseint (IDSTR); SYSTEM.OUT.PRINTLN (ID); Customerdao.delete (ID);}    catch (Exception e) {} response.sendredirect ("Query.do"); } private void Addcustomer (HttpServletRequest resquest,httpservletresponse response) throws IOException, Servletexc    eption{String name=resquest.getparameter ("name");    String address=resquest.getparameter ("address");    String phone=resquest.getparameter ("phone");    String message= "User" + name + "already registered";    Long Count=customerdao.getcountwithname (name);    if (count>0) {//resquest.setattribute ("Count", count);    Resquest.setattribute ("message", "user" + name + "already registered");    Resquest.setattribute ("Address", address);    Resquest.setattribute ("Phone", phone);    Resquest.getrequestdispatcher ("/addcustomer.jsp"). Forward (resquest, response);            } else{customer Customer=new customer (null, name, address, phone); Customerdao.save (Customer);    Response.sendredirect ("Query.do");} } private void edit (httpservletrequest request,httpservletresponse response) {String idstr=request.getparameter ("id"    );        int id=0; try {id=integer.parseint (IDSTR); Customer cus=customerdao.get (ID);//string name=cus.getname ();//string address=cus.getaddress ();//string phone= Cus.getphone ();//request.setattribute ("name", name),//request.setattribute ("address", address); Request.setattribute ("Customer", cus), Request.getrequestdispatcher ("/edit.jsp"). Forward (request, response);} catch (Exception e) {//Todo:handle Exception}} private void Update (HttpServletRequest request,httpservletres Ponse response) throws Servletexception, ioexception{//1. Get form parameters: ID, name, address, phone, oldnamestring ID = req Uest.getparameter ("id"); String name = Request.getparameter ("name"); String phone = request.getparameter ("Phone"); String address = Request.getparameter ("Address"); String oldname = Request.getparameter ("Oldname");//2. Test NAWhether me is already occupied://2.1 Compare name and oldname if the same description name is available. 2.1 If it is not the same, call Customerdao's Getcountwithname (String name) to get the name in the database if (!oldname.equalsignorecase (name)) {Long Count = Customerdao.getcountwithname (name);//2.2 if the return value is greater than 0, respond to the updatecustomer.jsp page: by forwarding the NEWCUSTOMER.JSPIF ( Count > 0) {//2.2.1 displays an error message on the updatecustomer.jsp page: username name is already occupied, please re-select!//put a property message in Request: Username name is already occupied, Please re-select!,//On the page by Request.getattribute ("message") to display the Request.setattribute ("message", "username" + name + "is already occupied, please re-select!"); The form values of the/2.2.2 newcustomer.jsp can be echoed. Address, the phone displays the new value of the submitted form, and name displays oldname instead of the newly submitted name//2.2.3 End method: Return Request.getrequestdispatcher ("/updatecus Tomer.jsp "). Forward (request, response); return;}} 3. If validation passes, the form parameter is encapsulated as a customer object Customercustomer customer = new Customer (null, name, address, phone); Customer.setid (intege R.parseint (ID)); 4. Call Customerdao's update (customer customer) to perform the updating Operation Customerdao.update (customer);//5. Redirect to Query.doresponse.sendRedirect ("Query.do"); }}

  

The MVC pattern Design of Java Web Foundation (i)--using HttpServlet to implement MVC layered design, the DAO layer uses Dbutils to implement the link with the database.

Related Article

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.