1. 程式人生 > >Spring Boot簡單入門(二)

Spring Boot簡單入門(二)

上篇演示了Spring Boot最簡單的一個例項,這篇將整合mysql和mybatis實現簡單的登入功能。

以前我們寫java程式碼,都要自己手動一個一個去建實體類,寫方法,這種瑣碎的事情不但無聊且浪費時間,這裡介紹一個好用的工具,Mybatis-Generator。它可以自動生成Dao、Modle、Mapping相關檔案,具體使用方法請參考:http://www.cnblogs.com/lichenwei/p/4145696.html

將自動生成的檔案拖到建好的Spring Boot專案中

接著引入mysql、mybatis相關依賴

        <dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>	
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

然後新建application.yml檔案,將原來的application.properties檔案刪除,在application.yml中寫入:

server:
  port: 8080

spring:
    datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
        password: root
## 該配置節點為獨立的節點,有很多同學容易將這個配置放在spring的節點下,導致配置無法被識別
mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要對應mapper對映xml檔案的所在路徑
  type-aliases-package: com.example.model  # 注意:對應實體類的路徑

要根據自己的實際情況修改相應配置,避免直接複製貼上造成專案報錯。

接著在templates下新建login.html:

<!DOCTYPE html>
<html>
  <head>
    <title>登入</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3"/>
    <meta name="description" content="this is my page"/>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    
    <script type="text/javascript" src="../js/jquery.min.js"></script>

  </head>
  
  <body>
    <form id="myForm">
    	使用者名稱:<input type="text" id="username" name="username" /><br/>
    	密碼:<input type="password" id="password" name="password" /><br/>
    	<button type="button" id="submit">登入</button>
    </form>
  </body>
  <script type="text/javascript">
  	$("#submit").click(function(){
  		$.ajax({
  			url:"getUser",
  			data:$("#myForm").serialize(),
  			type:"POST",
  			dataType:"json",
  			success:function(data){
  				if(data.msg == "1"){
  					alert("登入成功!");
  					window.location.href="index";
  				}else{
  					alert("登入失敗!");
  				}
  			},
  			erro:function(){
  				alert("fail");
  			}
  		})
  	})
  </script>
</html>

其中jquery檔案放在static檔案下,引用時要注意。另外這裡扯一句,避免其他人和我踩一樣的坑,在這裡用ajax提交整個表單時,如果採用button標籤,必須在標籤里加上type="button",不然這裡還會預設為input標籤的submit型別,也就是說在ajax提交一次後,表單的submit還會再提交一次,所以這裡必須加上type="button",切記切記。

查詢語句和Dao層、Service層程式碼不做贅述,直接貼程式碼:

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.UserDao">
  <resultMap id="BaseResultMap" type="com.example.model.User">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="photo" jdbcType="VARCHAR" property="photo" />
  </resultMap>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    id, username, email, password, sex, photo
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from t_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <!-- 根據使用者名稱和密碼查詢使用者 -->
  <select id="getUserByNameAndPwd" resultMap="BaseResultMap">
	select id,username,email,sex from t_user
	<where>
		<if test="username != null and username != ''">
			and username = #{username}
		</if>
		<if test="password != null and password != ''">
			and password = #{password}
		</if>
	</where>  
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from t_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.model.User">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into t_user (id, username, email, 
      password, sex, photo
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, 
      #{password,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{photo,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.model.User">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="email != null">
        email,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="photo != null">
        photo,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="photo != null">
        #{photo,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.model.User">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="photo != null">
        photo = #{photo,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.model.User">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    set username = #{username,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      photo = #{photo,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

UserDao.java

package com.example.dao;

import java.util.Map;

import com.example.model.User;

public interface UserDao {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    int deleteByPrimaryKey(Integer id);
    
    /**
     * 根據使用者名稱和密碼查詢使用者
     * @param params
     * @return
     */
    User getUserByNameAndPwd(Map<String,Object> params);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    int insert(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    int insertSelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    User selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated
     */
    int updateByPrimaryKey(User record);
}

UserService.java

package com.example.service;

import java.util.Map;

import com.example.model.User;

public interface UserService {
	/**
     * 根據使用者名稱和密碼查詢使用者
     * @param params
     * @return
     */
    User getUserByNameAndPwd(Map<String,Object> params);
}

UserServiceImpl.java

package com.example.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.UserDao;
import com.example.model.User;
import com.example.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;

	@Override
	public User getUserByNameAndPwd(Map<String, Object> params) {
		return userDao.getUserByNameAndPwd(params);
	}

}

UserController.java

package com.example.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.model.User;
import com.example.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/index")
	public String index(){
		return "index";
	}
	
	@RequestMapping("/login")
	public String login(){
		return "login";
	}
	
	@RequestMapping("/getUser")
	@ResponseBody
	public Map<String,Object> getUser(@RequestParam Map<String,Object> params){
		Map<String,Object> map = new HashMap<String, Object>();
		User user = userService.getUserByNameAndPwd(params);
		if(user != null){
			map.put("msg", "1");
		}else{
			map.put("msg", "0");
		}
		return map;
	}
}

最後,在Application中新增MapperScan,動態掃描

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.dao")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
		System.out.println("(*^▽^*)啟動成功!(〃'▽'〃)");
	}
}

啟動服務後,在瀏覽器中輸入   http://localhost:8080/user/login