JdbcTemplate实例

一、项目环境

  • 开发系统:Window10
  • 开发工具:IDEA
  • JDK:1.8
  • 框架:Maven+Spring
  • 数据库:Mysql

二、项目结构

项目构成文件:
JdbcTemplate实例_第1张图片

三、Maven配置

pom.xml文件的配置:

<properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    
    <spring.version>4.1.1.RELEASEspring.version>
    
    <slf4j.version>1.7.7slf4j.version>
    <log4j.version>1.2.17log4j.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
    dependency>

    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.1version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.4version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.34version>
    dependency>
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    

    <dependency>
      <groupId>javax.servlet.jsp.jstlgroupId>
      <artifactId>javax.servlet.jsp.jstl-apiartifactId>
      <version>1.2.1version>
    dependency>

    <dependency>
      <groupId>org.glassfish.webgroupId>
      <artifactId>jstl-implartifactId>
      <version>1.2version>
    dependency>

  dependencies>

四、applicationContext配置

applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    
    <mvc:annotation-driven/>
    
    <context:component-scan base-package="com"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    bean>

    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="maxActive" value="50"/>
        <property name="minIdle" value="5"/>
        <property name="maxWait" value="5000"/>
    bean>

    <bean id="jdbcTemplate"
          class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    bean>

beans>

五、数据库表

人员信息表:
JdbcTemplate实例_第2张图片

用户信息表:
这里写图片描述

六、各层代码

实体类(entity)
User:

package com.entity;

public class User {
    private int uid;//人员编号
    private String uname;//姓名
    private String telephone;//电话
    private String job;//职业
    private String address;//地址
    private String nationality;//国籍

    @Override
    public String toString() {
        return "User{" +
            "uid=" + uid +
            ", uname='" + uname + '\'' +
            ", telephone='" + telephone + '\'' +
            ", job='" + job + '\'' +
            ", address='" + address + '\'' +
            ", nationality='" + nationality + '\'' +
            '}';
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    public int getUid() {

        return uid;
    }

    public String getUname() {
        return uname;
    }

    public String getTelephone() {
        return telephone;
    }

    public String getJob() {
        return job;
    }

    public String getAddress() {
        return address;
    }

    public String getNationality() {
        return nationality;
    }

    public User() {

    }

    public User(int uid, String uname, String telephone, String job, String address, String nationality) {

        this.uid = uid;
        this.uname = uname;
        this.telephone = telephone;
        this.job = job;
        this.address = address;
        this.nationality = nationality;
    }
}

Member:

package com.entity;

public class Member {
    private int mid;//用户编号
    private String mname;//用户名
    private String pwd;//密码
    private String member_type;//用户类型

    public Member() {
    }

    @Override
    public String toString() {
        return "Member{" +
            "mid=" + mid +
            ", mname='" + mname + '\'' +
            ", pwd='" + pwd + '\'' +
            ", member_type='" + member_type + '\'' +
            '}';
    }

    public Member(int mid, String mname, String pwd, String member_type) {
        this.mid = mid;
        this.mname = mname;
        this.pwd = pwd;
        this.member_type = member_type;
    }

    public void setMid(int mid) {

        this.mid = mid;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public void setMember_type(String member_type) {
        this.member_type = member_type;
    }

    public int getMid() {

        return mid;
    }

    public String getMname() {
        return mname;
    }

    public String getPwd() {
        return pwd;
    }

    public String getMember_type() {
        return member_type;
    }
}

持久层(Dao类)
UserDaoImpl:

package com.dao;

import com.entity.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("userDao")
public class UserDaoImpl extends JdbcDaoSupport {

    //若是继承JdbcDaoSupport类则要用Set方法进行自动装配
    @Autowired
    public void setTemplate(JdbcTemplate template) {
        setJdbcTemplate(template);
    }

    //查找所有用户
    public List findAll() {
        String sql = "select * from users";
        List list = getJdbcTemplate().query(sql,
            rs -> {
                List list1 = new ArrayList<>();
                while (rs.next())
                    list1.add(new User(rs.getInt("uid"), rs.getString("uname"), rs.getString("telephone"),
                        rs.getString("job"), rs.getString("address"), rs.getString("nationality")));
                return list1;
            }
        );
        return list;
    }
}

MemberDaoImpl:

package com.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Component;

@Component("memberDao")
public class MemberDaoImpl extends JdbcDaoSupport {

    @Autowired
    public void setTemplate(JdbcTemplate template) {
        setJdbcTemplate(template);
    }

    //登陆
    public int login(String mname, String pwd, String member_type) {

        String sql = "select count(1) from member where mname = ? and pwd = ? and member_type = ?";

        return getJdbcTemplate().queryForObject(sql, new Object[]{mname, pwd, member_type},Integer.class);
    }
}

业务层
UserServiceImpl:

package com.service;

import com.dao.UserDaoImpl;
import com.entity.User;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import javax.annotation.Resource;

@Transactional
@Component("userService")
public class UserServiceImpl {

    //与@AutoWired类似,Resource默认按属性名自动装配,是J2EE提供的注解
    @Resource
    private UserDaoImpl userDao;

    public List findAll() {
        return userDao.findAll();
    }
}

控制器
UserController:

package com.controller;

import com.dao.UserDaoImpl;
import com.entity.User;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserDaoImpl userDao;

    public void setUserDao(UserDaoImpl userDao) {
        this.userDao = userDao;
    }

    public UserDaoImpl getUserDao() {
        return userDao;
    }

    @RequestMapping("/findall")
    public String findall(HttpServletRequest request) {
        List list = userDao.findAll();
        request.setAttribute("userlist",list);

        return "show";
    }
}

MemberController:

package com.controller;

import com.dao.MemberDaoImpl;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberDaoImpl memberDao;

    public void setMemberDao(MemberDaoImpl memberDao) {
        this.memberDao = memberDao;
    }

    public MemberDaoImpl getMemberDao() {
        return memberDao;
    }

    @RequestMapping("/login")
    public String login(@RequestParam("mname")String mname, @RequestParam("pwd")String pwd,@RequestParam("member_type")String member_type,HttpServletRequest request) {
        int i = memberDao.login(mname,pwd,member_type);
        if (i==1)
            return "forward:/user/findall";
        else {
            String msg = "用户名或密码错误!!";
            request.setAttribute("msg", msg);
            return "index";
        }
    }
}

七、web.xml配置

<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"
         version="2.5">
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
    listener>
    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <servlet>
        <servlet-name>userServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext*.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>userServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

web-app>

八、页面代码

index.jsp:

<html>
<body>
    <form action="/member/login">
        ${msg} <br/>
        用户名:<input type="text" name="mname" /><br />
        密码:<input type="password" name="pwd"><br />
        用户类型:<select name="member_type">
            <option value="管理员">管理员option>
            <option value="用户">用户option>
        select><br />
        <input type="submit" value="登陆">
    form>
body>
html>

show.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>Titletitle>
head>
<body>
    <center>
        <table border="1">
            <tr>
                <td>人员IDtd>
                <td>姓名td>
                <td>手机号td>
                <td>职业td>
                <td>住址td>
                <td>国籍td>
            tr>
            <c:forEach items="${userlist}" var="list">
                <tr>
                    <td>${list.uid}td>
                    <td>${list.uname}td>
                    <td>${list.telephone}td>
                    <td>${list.job}td>
                    <td>${list.address}td>
                    <td>${list.nationality}td>
                tr>
            c:forEach>
        table>
    center>
body>
html>

运行Tomcat进行测试:
http://localhost:8080 访问index.jsp

若用户名密码输入错误:
JdbcTemplate实例_第3张图片

输入正确的用户名后,跳转至:
JdbcTemplate实例_第4张图片

你可能感兴趣的:(实习)