SpringBoot+Mybatis+Thymeleaf一個完整demo

今天實現(xiàn)了一個SpringBoot+Mybatis+Thymeleaf 的小demo,雖然比較簡單,但是作為一個新手我來說還是碰到了很多因為不專業(yè)而造成的稀奇古怪的問題,我盡量把遇到的問題陳述出來,希望大家能夠明白和避免這種問題。這是存放代碼的地址 https://gitee.com/neimenggudaxue/SPtest3

1.首先搭建SpringBoot+Mybatis+Thymeleaf 環(huán)境,參考(都是筆者親自試驗的結(jié)果):

http://www.itdecent.cn/p/66ca10f213b5
http://www.itdecent.cn/p/85824b992af2

項目目錄結(jié)構(gòu)圖

2.本項目實現(xiàn)用戶登錄

1.提供一個頁面,供用戶輸入用戶名、密碼

2.校驗用戶名、密碼是否對應(yīng),如果密碼正確,則返回字符串"登錄成功",否則返回"登錄失敗"
登錄頁面
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index page</title>
</head>
<body>

    <form action="" th:action="@{/loginResult}" method="post">
        用戶名<input type="text" name="name">
        密碼<input type="password" name="passwd">
        <input type="submit" value="確定">
    </form>
</body>
</html>

路由controller文件,注意:

1.注解@Controller @RestController 不可同時使用。這就導致了我只能返回一些restAPI或者json數(shù)據(jù),實際上可以配合@ResponseBody,既可以返回"login"這種頁面,也可以返回"登錄成功"這種文案
2.使用了自動裝入注解@AutoWired


@RestController注解相當于@ResponseBody + @Controller合在一起的作用。

  1. 如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。
  2. 如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
    如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁面,則需要在對應(yīng)的方法上加上@ResponseBody注解。
@Controller
public class LoginController {

    @Autowired
    ImpleLoginService impleLoginService;
    @Autowired
    User user;

    @RequestMapping("/login")
    public String  login(){
        return "login";
    }

    @RequestMapping("/loginResult")
    @ResponseBody
    public String home(HttpServletRequest request){
        String name=request.getParameter("name");
        String passwd=request.getParameter("passwd");
        user=impleLoginService.loginResult(name,passwd);
        if(passwd.equals(user.getPasswd()))
            return "登錄成功";
        else
            return "登錄失敗";
    }
}

service層代碼,設(shè)計為面向?qū)ο蟮慕涌谂c實現(xiàn)分離
--@Autowired 裝載mapper
--@service 注解service層

@Service
public class ImpleLoginService implements InterLoginService {

    @Autowired
    UserMapper userMapper;
    public User loginResult(String name,String passwd){
        return userMapper.findByUsernameAndPassword(name,passwd);
    }
}

mapper層即Dao 層代碼,
--該層類也是接口interface的形式,但是在其方法上使用了注解,編碼人員便可以不用手動去實現(xiàn)其接口方法。
--最后一個方法是手動寫的,非mybatis-generator實現(xiàn)的。注意該方法的參數(shù)傳遞形式,我在此便犯了錯,我寫的是:
User findByUsernameAndPassword( String name, String passwd) 報錯了。
--使用注解@Repository

@Repository
public interface UserMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    int insert(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    int insertSelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    User selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbg.generated Mon May 28 13:07:09 CST 2018
     */
    int updateByPrimaryKey(User record);

    @Select("select * from user where name=#{name}")
    User findByUsernameAndPassword(@Param("name") String name, @Param("passwd") String passwd);
}

啟動類的編寫
--我當時寫的時候并未使用注解@MapperScan,報錯找不到mapper文件;
通過使用@MapperScan可以指定要掃描的Mapper類的包的路徑

@SpringBootApplication
@ComponentScan(basePackages ={"com.example.demo"})
@MapperScan("com.example.demo.mapper")
public class DemoApplication {

   public static void main(String[] args) {
       SpringApplication.run(DemoApplication.class, args);
   }
}

實體類文件,記得使用注解,否則也報錯

@Component
public class User {
  XXXXXXXX
}

通過本次實踐,我深深的認識到自己對Spring的常用注解幾乎一無所知,或者說只知皮毛,悲催。提供以下簡潔的說明;

參考:https://www.cnblogs.com/xiaoxi/p/5935009.html
@Service用于標注業(yè)務(wù)層組件
@Controller用于標注控制層組件(如struts中的action)
@Repository用于標注數(shù)據(jù)訪問組件,即DAO組件。
@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。

啟動類上的注解
@ComponentScan告訴Spring 哪個packages 的用注解標識的類 會被spring自動掃描并且裝入bean容器。例如,如果你有個類用@Controller注解標識了,那么,如果不加上@ComponentScan,自動掃描該controller,那么該Controller就不會被spring掃描到,更不會裝入spring容器中,因此你配置的這個Controller也沒有意義。
@MapperScan可以指定要掃描的Mapper類的包的路徑
@Configuration 是最新的用注解配置spring,也就是說這是個配置文件,和原來xml配置是等效的,只不過現(xiàn)在用java代碼進行配置了 加上一個@Configuration注解就行了,是不是很方便,不需要那么繁瑣的xml配置了,這樣基于注解的配置,可讀性也大大增高了。

@Autowired 默認按類型裝配,如果我們想使用按名稱裝配,可以結(jié)合@Qualifier注解一起使用。如下:
@Autowired @Qualifier("personDaoBean") 存在多個實例配合使用
@Resource默認按名稱裝配,當找不到與名稱匹配的bean才會按類型裝配。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 1.1 spring IoC容器和beans的簡介 Spring 框架的最核心基礎(chǔ)的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,846評論 2 22
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,254評論 6 342
  • 前言:由于在第一次面試中吃了暗虧,考到了SpringMVC的@RequestMapping和@ResponseBo...
    天譴殘魂閱讀 4,611評論 3 17
  • Python和很多其他語言一樣,支持異常處理。我們可以使用try-catch類似的形式捕獲異常,處理異常,或者拋出...
    樂百川閱讀 626評論 0 1

友情鏈接更多精彩內(nèi)容