Java框架_Maven_day02

目录

五、使用 Maven 搭建 WEB 项目

5.1 需求

5.2 代码实现

5.2.1 创建数据库test,建表

5.2.2 依赖管理

5.2.3 创建 JavaBean(Customer.java)

5.2.4 在 webapp 下创建 index.jsp 页面

5.2.5 在 webapp 下创建 /WEB-INF/web.xml 文件

5.2.6 在 resource 下创建配置文件

5.2.7 创建 CustomerServlet.java 文件

5.2.8  创建 CustomerService 接口和 CustomerServiceImpl 实现类

5.2.9  创建 CustomerDao 接口和 CustomerDaoImpl 实现类

5.2.10 创建 C3P0Utils.java 工具类

5.2.11 测试


五、使用 Maven 搭建 WEB 项目

5.1 需求

        完成添加用户信息的操作:要求有客户名称、客户来源、客户级别、客户行业、客户手机、客户电话等信息

5.2 代码实现

5.2.1 创建数据库test,建表

create table `cst_customer` (
  `cust_id` bigint(32) not null auto_increment comment '客户编号(主键)',
  `cust_name` varchar(32) not null comment '客户名称(公司名称)',
  `cust_source` varchar(32) default NULL comment '客户信息来源',
  `cust_industry` varchar(32) default NULL comment '客户所属行业',
  `cust_level` varchar(32) default NULL comment '客户级别',
  `cust_phone` varchar(64) default NULL comment  '固定电话',
  `cust_mobile` varchar(16) default NULL comment '移动电话',
  primary key (`cust_id`)
)
 

5.2.2 依赖管理

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cpz</groupId>
    <artifactId>maven_customer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!--servlet,3.1.0可以使用配置文件配置,也可以使用注解-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!--c3p0连接池-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--jdbcTemplate-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
            <scope>compile</scope>
        </dependency>
        <!--beanUtils-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--jdk编译插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <!--tomcat插件-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <!-- 指定端口 -->
                    <port>83</port>
                    <!-- 请求路径 -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

5.2.3 创建 JavaBean(Customer.java)

package com.cpz.domain;

public class Customer {
    private Long cust_id;
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_phone;
    private String cust_mobile;

    public Long getCust_id() {
        return cust_id;
    }

    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }

    public String getCust_name() {
        return cust_name;
    }

    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }

    public String getCust_source() {
        return cust_source;
    }

    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }

    public String getCust_industry() {
        return cust_industry;
    }

    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }

    public String getCust_level() {
        return cust_level;
    }

    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }

    public String getCust_phone() {
        return cust_phone;
    }

    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }

    public String getCust_mobile() {
        return cust_mobile;
    }

    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "cust_id=" + cust_id +
                ", cust_name='" + cust_name + '\'' +
                ", cust_source='" + cust_source + '\'' +
                ", cust_industry='" + cust_industry + '\'' +
                ", cust_level='" + cust_level + '\'' +
                ", cust_phone='" + cust_phone + '\'' +
                ", cust_mobile='" + cust_mobile + '\'' +
                '}';
    }
}

5.2.4 在 webapp 下创建 index.jsp 页面

<%--
  Created by IntelliJ IDEA.
  User: cpz
  Date: 2019/7/29
  Time: 10:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>客户添加</title>
</head>
<body>
    <form action="/CustomerServlet" method="post">
        客户名称:<input type="text" name="cust_name"/><br/>
        客户来源:<input type="text" name="cust_source"/><br/>
        客户级别;<input type="text" name="cust_level"/><br/>
        客户行业;<input type="text" name="cust_industry"/><br/>
        客户手机:<input type="text" name="cust_mobile"/><br/>
        客户电话:<input type="text" name="cust_phone"/><br/>
        <input type="submit" value="保存"/>
    </form>
</body>
</html>

5.2.5 在 webapp 下创建 /WEB-INF/web.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_3_0.xsd">

</web-app>

5.2.6 在 resource 下创建配置文件

<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        <property name="user">root</property>
        <property name="password">1234</property>
        <property name="initialPoolSize">5</property>
    </default-config>
</c3p0-config>

5.2.7 创建 CustomerServlet.java 文件

    注意:@WebServlet("/addCustomerServlet")不要添加生成的name属性

package com.cpz.servlet;

import com.cpz.domain.Customer;
import com.cpz.service.CustomerService;
import com.cpz.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/CustomerServlet")
public class CustomerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1:处理乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        // 2:获取请求参数(封装成一个javabean)
        Map<String, String[]> map = request.getParameterMap();
        Customer customer = new Customer();
        try {
            BeanUtils.populate(customer,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 3:调用业务,保存
        CustomerService customerService = new CustomerServiceImpl();
        int rows = customerService.saveCustomer(customer);

        // 4:响应
        if (rows > 0) {
            response.getWriter().println("保存成功");
        }
    }
}

5.2.8  创建 CustomerService 接口和 CustomerServiceImpl 实现类

package com.cpz.service;

import com.cpz.domain.Customer;

public interface CustomerService {
    int saveCustomer(Customer customer);
}
package com.cpz.service.impl;

import com.cpz.dao.CustomerDao;
import com.cpz.dao.impl.CustomerDaoImpl;
import com.cpz.domain.Customer;
import com.cpz.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {
    CustomerDao customerDao = new CustomerDaoImpl();

    @Override
    public int saveCustomer(Customer customer) {
        int rows = customerDao.save(customer);
        return rows;
    }
}

5.2.9  创建 CustomerDao 接口和 CustomerDaoImpl 实现类

package com.cpz.dao;

import com.cpz.domain.Customer;

public interface CustomerDao {
    int save(Customer customer);
}
package com.cpz.dao.impl;

import com.cpz.dao.CustomerDao;
import com.cpz.domain.Customer;
import com.cpz.utils.C3P0Utils;
import org.springframework.jdbc.core.JdbcTemplate;

public class CustomerDaoImpl implements CustomerDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(C3P0Utils.getDataSource());

    @Override
    public int save(Customer customer) {
        String sql = "insert into cst_customer (cust_name,cust_source,cust_industry,cust_level,cust_mobile,cust_phone) values (?,?,?,?,?,?)";
        Object[] params = {customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),customer.getCust_level(),customer.getCust_mobile(),customer.getCust_phone()};
        int rows = jdbcTemplate.update(sql, params);
        return rows;
    }
}

5.2.10 创建 C3P0Utils.java 工具类

package com.cpz.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * c3p0工具类(数据库连接池工具),用于管理多个数据库连接对象。
 * 与DBCP不同的是,c3p0不用手动加载配置文件,只需将配置文件(c3p0-config.xml)放到resources目录即可。
 */
public class C3P0Utils {

    // 得到一个数据源(连接池)
    private static DataSource ds = new ComboPooledDataSource();

    public static DataSource getDataSource() {
        return ds;
    }

    /**
     * 得到数据库连接对象
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn;
        try {
            conn = ds.getConnection();
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException("服务器忙。。。");
        }
    }

    /**
     * 关闭所有资源连接
     *
     * @param conn
     * @param ps
     * @param rs
     */
    public static void releaseAll(Connection conn, Statement ps, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn = null;
        }

        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ps = null;
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            rs = null;
        }
    }
}

5.2.11 测试

访问:http://localhost:83

输入:

查看页面:

查看数据库:

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值