基於springboot的ssm框架搭建以及三層架構應用

上一節中討論瞭如何搭建springboot的開發環境,這節咱們繼續在上一屆基礎上搭建ssm框架進行項目的開發。簡單回顧了以前搭建ssm框架的過程,建立項目->集成springmvc->集成spring->集成mybatis->調試.手動搭建過程仍是比較複雜的。不過建議初學者仍是一步步來。不過在開發過程當中,你們仍是喜歡快一些。

1.初始化項目 ssm

有了springboot以後,咱們將會從繁重的項目搭建工做脫離出來。只須要執行幾個簡單的命令便可完成項目的建立和框架的搭建。html

spring init -g=com.briup.apps -a=app02 -p=war -d=web,mysql,mybatis app02

clipboard.png

建立項目的時候指定依賴web,mysql,mybatis。而後進入到該項目中安裝依賴便可前端

clipboard.png

依賴安裝完畢以後會發現控制檯報錯!以下mysql

clipboard.png
經分析,是沒有指定數據源,也就是說springboot不清楚你到底要鏈接哪一個數據庫(mysql?oracle?)
這時候咱們能夠在application.properties中添加以下數據源配置git

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root

若是你用的是oracle XE數據庫,須要添加以下依賴和配置github

......
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
spring.datasource.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=test
spring.datasource.password=test
server.port=8081

clipboard.png

從新執行一次 mvn install將不會再報錯!web

經過eclipse打開項目。找到pom.xml,在依賴中添加以下代碼以添加動態部署功能。這樣咱們修改代碼後就不用再重啓項目了。tomcat將會在咱們保存代碼以後自動重啓。spring

clipboard.png

至此,ssm框架已經搭建好!對,你沒有聽錯。
那麼咱們應該如何進行開發呢?sql

2.三層架構

三層架構和多層架構是咱們在開發過程當中經常使用的架構方式,用於解耦。每部分代碼完成特定功能。這裏,mybatis主要應用在數據訪問層,springmvc應用於視圖層,爲前端提供數據接口(固然也能夠直接渲染前端頁面)。spring貫穿整個框架中。數據庫

clipboard.png

2.1 數據訪問層

建立實體類編程

public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private Long id;
    private String name;
    private String gender;
    private String birth;
    public User() {
        
    }
    
    public User(Long id, String name, String gender, String birth) {
        super();
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.birth = birth;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getBirth() {
        return birth;
    }
    public void setBirth(String birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", gender=" + gender + ", birth=" + birth + "]";
    }
}

建立Mapper接口

mybatis是一個輕量級的orm框架。建議在使用以前熟讀官方文檔http://www.mybatis.org/mybati...。 後面章節將會仔細介紹。這裏僅使用。

爲了使系統能掃描到mapper,須要在DemoApplication添加註釋,@MapperScan("com.briup.apps.app02.dao")

@SpringBootApplication
@MapperScan("com.briup.apps.app02.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
public interface UserMapper {
    /**
     * 查詢全部
     * */
    @Select("select * from tbl_user")
    List<User> findAll() throws Exception;
    
    /**
     * 經過id查詢
     * */
    @Select("select * from tbl_user where id = #{id}")
    User findById(long id) throws Exception;
    
    /**
     * 保存
     * */
    @Insert("insert into tbl_user values(null,#{name},#{gender},#{birth})")
    void save(User user);
}

2.2 業務邏輯層

在這一層,須要面向接口編程,實際上也是對於springmvc的應用,在後面的文章中將逐步對每一個技術細化,這裏推薦搭建查看spring-mvc的官方文檔進行學習https://docs.spring.io/spring...

IUserService

public interface IUserService {
    List<User> findAll() throws Exception;
    
    User findById(long id) throws Exception;
    
    void save(User user) throws Exception;
}

UserServiceImpl

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public List<User> findAll() throws Exception {
        return userMapper.findAll();
    }

    @Override
    public User findById(long id) throws Exception {
        return userMapper.findById(id);
    }

    @Override
    public void save(User user) throws Exception {
        userMapper.save(user);
    }

}

2.3 業務邏輯層

這裏演示了添加查詢的功能。
UserController

@RestController
@RequestMapping(path= {"/users"})
public class UserController {
    @Autowired
    private IUserService userService;
    
    @GetMapping(path= {"/findAll"})
    @JsonRawValue
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        try {
            users = userService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }
    
    @GetMapping(path= {"/findById"})
    @JsonRawValue
    public User findById(@RequestParam long id) {
        User user = null;
        try {
            user = userService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
    
    @PostMapping(path= {"/save"}, consumes= {"application/x-www-form-urlencoded"})
    public String save(@ModelAttribute User user) {
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功啦";
    }
}

3. 測試

測試查詢全部用戶
clipboard.png

測試錄入用戶

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表單</title>
</head>
<body>
    <h2>用戶添加</h2>
    <hr>
    <form action="http://localhost:8080/users/save" method="post">
        name: <input type="text" name="name"> <br>
        gender: 
            <label for="gender_male">
                男<input id="gender_male" type="radio" value="男" name="gender" checked=""> 
            </label>
            <label for="gender_female">
                女<input id="gender_female" type="radio" value="女" name="gender"> 
            </label> <br>
        birth:
            <input type="text" name="birth"> <br>
            <input type="submit" value="保存">
    </form>
</body>
</html>
思考! 在實際開發中,對於每一個實體類咱們都須要提供最基礎增刪改查的業務邏輯和數據訪問,若是針對每一個實體都寫這麼一堆勢必形成代碼的冗餘,那麼如何簡化封裝代碼呢?以前咱們項目中用到ssh,我封裝了baseDao和baseService。那麼這種思想一樣能夠應用到如今的ssm結構中。

代碼地址:
https://github.com/pluslicy/s...

相關文章
相關標籤/搜索