使用spring+jdbcTemplate建立一個小項目

作業

1.建表 英雄表hero(id,name,atk,def,spd)
2.建實體類
3.創建dao類。
4.創建業務類。
5.創建Test。


提示請用戶選擇要做的操作
	1.查看所有的英雄。
	2.添加英雄,
	3.刪除英雄。
	4.根據id查看英雄詳細信息。
	5.退出
1
程序羅列出所有的英雄信息。

提示請用戶選擇要做的操作
	1.查看所有的英雄。
	2.添加英雄,
	3.刪除英雄。
	4.根據id查看英雄詳細信息。
	5.退出
4,
請輸入要查詢的英雄的編號
1
把id爲1的英雄信息展示到控制檯上。


提示請用戶選擇要做的操作
	1.查看所有的英雄。
	2.添加英雄,
	3.刪除英雄。
	4.根據id查看英雄詳細信息。
	5.退出

實現項目結構

1:創建數據庫和表hero(id,name,atk,def,spd)
使用cmd方式創建:

1.輸入password

2.查看已有數據庫
show databases;

3.如果使用已有數據庫:use xxx;
如果沒有,需要創建一個database:create database xxx;

4.查看數據庫中的表:show tables;
創建新表:create table xxx(屬性);
查看錶內容:select * from xxx;
插入數據:insert into xxx values();

在這裏插入圖片描述
2:創建Hero實體類(entity)
在這裏插入圖片描述
將表中的列對應到實體類的屬性中

3:創建dao類與其實現類(dao)
在這裏插入圖片描述
4:創建業務類(service)
在這裏插入圖片描述
5:創建Test(test)
在這裏插入圖片描述
6:添加項目依賴:
在這裏插入圖片描述
7:啓動spring應用
在這裏插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

</web-app>

8.項目的整體目錄
在這裏插入圖片描述
將項目整合起來,使用spring框架ioc控制反轉,讓spring工廠來new類
使用spring的DI思想,將類依賴注入到其他類的屬性中

將項目架構起來

1:如何將一個普通的java項目轉換成web項目並用maven管理jar包

在這裏插入圖片描述
or
在這裏插入圖片描述
設置成web模式:
在這裏插入圖片描述
管理項目的文件夾類型
在這裏插入圖片描述
將項目設置成maven來管理jar包

在這裏插入代碼片選中項目——>右鍵——>選擇Add Framworks Support——>選擇maven
這時項目中會生成pom.xml文件
將pom.xml文件修改成jdk版本爲1.8:
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

2:spring框架

spring的核心內容是ioc(控制反轉)和aop(面向切面編程)
使用:1.導入相關jar包;

spring相關的jar包:
spring-core:spring的核心jar包
spring-beans:用來管理bean對象的
spring-context:上下文支持jar包
spring-aop:面向切面編程使用的jar包
spring-expression:spring中一個表達式解析jar包
spring-web:支持spring開發jar包,Servlet類

2.在resource目錄(src)下創建applicationContext.xml(or spring.xml,命名隨意)文件,
在這裏插入圖片描述
並將其添加到spring的框架中;
在這裏插入圖片描述
3.在web.xml中啓動spring

<!--初始化spring配置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--啓動Web容器時,自動裝配applicationContext.xml的配置信息,執行它所實現的方法。
如果沒有該文件,需在context-param 指定一個Spring容器的初始化配置文件,本例中是applicationContext.xml-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

相當於:

public static void main(String[] args) {
    
    // 得到Spring工廠類,參數是我們配置文件的路徑。classpath表示src文件夾,也就是java類編譯後的目錄
    ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    
    // 根據工廠類創建出對象,參數就是我們配置文件中bean的id屬性
    //此時的spring配置文件:
    //<!-- 針對我們寫的類進行配置,讓spring幫助我們創建類的對象 -->
	//<bean id="ua" class="com.baizhi.action.UserAction">
     UserAction ua = (UserAction)ac.getBean("ua");
    
    //使用spring創建出來的對象...
}

3:使用spring框架(springJDBC)管理對數據庫操作,在dao層實現

在spring的配置文件中將數據庫屬性添加到相關類中:

<!--1.加載db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"/>

db.properties:

jdbc.driverClassName:com.mysql.jdbc.Driver
jdbc.url:jdbc:mysql://localhost:3306/hero?serverTimezone=UTC
jdbc.username:root
jdbc.password:root

注:value中必須以jdbc.xxx的形式來實現值的注入

<!--2.數據源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

注:中property標籤的name必須有對應的set方法(使用set方法依賴注入)

<!--3.spring提供簡化JDBC操作的模板JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

在這裏插入圖片描述
在這裏插入圖片描述
然後可以將jdbcTemplate注入到xxxdaoImpl中使用,

<bean id="dh" class="dao.HeroDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>

此時的jdbc中包含有DataSource類,並通過數據源已經和數據庫連接上了。

創建實體類對應的dao與daoImpl方法:
實體類:entity

package entity;

/**
 * 實體類hero
 */
public class Hero {
    private Integer id;
    //屬性...

    //構造方法...

    //get & set...

    //toString...
}

對應的dao接口(將對jdbcTemplate的操作方法寫到dao中)

public interface HeroDao {
    void insert(Hero hero)throws Exception;

    void delete(int id)throws Exception;

    void update(Hero hero)throws Exception;

    Hero select(int id)throws Exception;

    List<Hero> selectAll()throws Exception;
}

對應的daoImpl實現類(將jdbcTemplate注入dao中,並實現對jdbcTemplate的相關方法的調用)

package dao;

@Repository
public class HeroDaoImpl implements HeroDao {

    private JdbcTemplate jdbcTemplate;
    //使用的是set注入方法,將jdbcTemplate注入到dao中
    //
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    //對dao中的方法的實現
}

4.使用service層將操作包裝成業務,調用dao層的方法,添加邏輯處理

xxxService接口

public interface HeroService {
    void save(Hero hero)throws Exception;

    void remove(int id)throws Exception;

    void modify(Hero hero)throws Exception;

    Hero findById(int id)throws Exception;

    List<Hero> findAll()throws Exception;
}

xxxServiceImpl實現類

package service;

@Service
@Transactional(readOnly = true)
public class HeroServiceImpl implements HeroService {

    //使用set注入dao實現類
    //<bean id="ss" class="service.HeroServiceImpl">
    //<property name="heroDao" ref="dh"/>
    //</bean>
    private HeroDao heroDao;
    public void setHeroDao(HeroDao heroDao) {
        this.heroDao = heroDao;
    }

    //添加業務邏輯,調用dao中的方法實現業務
}

5.將servlet用test實現,不再寫頁面(java or jsp or html+templates)了

import ...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HeroServlet {
    //將業務類注入
    @Autowired
    private HeroService heroService;

    @Test
    public void menu() throws Exception {
        try {
            do {
                //調用業務
                }
            } while (choose != 6);
        }catch (InputMismatchException e){
            System.out.println("輸入格式有誤");
            menu();//回調
        }
    }
}

所遇到的問題

1:jdbcTemplate爲null

1.已經注入到spring框架中的類不用再new了

2:將spring和junit結合起來

1>test類輸入臺無法進行輸入操作

Help–>Edit Custom VM Options…

-Deditable.java.test.console=true

2>test中無法引用junit

不能把測試類命名爲Test

3:applicationContext.xml沒有加載到spring中

在這裏插入圖片描述

4:數據庫用戶名亂碼

在配置文件中加上
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章