IDEA Springboot创建多模块项目,整合Mybatis实现后台登录(二)

接上篇,搭建多模块项目后就开始写代码了。

首先在springboot-web添加jar包依赖,

pom.xml源码如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>springboot</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-web</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- 添加 springboot-service 的依赖 -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>springboot-service</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>

        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- Redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- RabbitMQ -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 配置devtool-->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

修改application.properties文件

#spring����Mybatis����
mybatis.type-aliases-package=com.example.entity
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*/*.xml

server.port=8082
#server.servlet.context-path=/demo
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/permission?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
icode=true&characterEncoding=utf-8
#默认路径

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#页面热加载
spring.thymeleaf.cache = false

1)首先在springboot-dao里面创建实体类entity及mapper

结构如下:

实体类代码及mapper代码:

package com.example.entity;

import java.util.Date;

public class User {
    private Integer id;

    private String username;

    private String password;

    private Date createdate;

    private Integer logincount;

    private Date lastlogintime;

    private Integer staffid;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Date getCreatedate() {
        return createdate;
    }

    public void setCreatedate(Date createdate) {
        this.createdate = createdate;
    }

    public Integer getLogincount() {
        return logincount;
    }

    public void setLogincount(Integer logincount) {
        this.logincount = logincount;
    }

    public Date getLastlogintime() {
        return lastlogintime;
    }

    public void setLastlogintime(Date lastlogintime) {
        this.lastlogintime = lastlogintime;
    }

    public Integer getStaffid() {
        return staffid;
    }

    public void setStaffid(Integer staffid) {
        this.staffid = staffid;
    }
}
package com.example.mapper;

import com.example.entity.User;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserMapper {
	List<User> getAll();
	User findUserByName(@Param("username") String username, @Param("password") String password);
	int addUser(User user);
}

在springboot-service新建service接口

代码如下:

package com.example.service;



import com.example.entity.User;

import java.util.List;


public interface UserService {
	
	/**根据接口查询所用的用户*/
	public List<User> findAllUser();
	User findUserByName(String username, String password);
	/**添加用户*/
	int addUser(User user);
}

实现类

package com.example.service.impl;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
	@Resource
	private UserMapper userMapper;

	@Override
	@Transactional
	public int addUser(User user){
		boolean flag = true;
		int result = userMapper.addUser(user);
		return result;
	}


	@Override
	public User findUserByName(String username, String password) {
		return userMapper.findUserByName(username,password);
	}

	public List<User> findAllUser() {
		List<User> list = userMapper.getAll();
		return list;
	}


	//@Override
	//public Map<String, Object> redisMap() {
		//jedisCluster.set("user", "张三丰");
		//设置完毕,获取之
		//String value = jedisCluster.get("user");
		//Map<String, Object> maps = new HashMap<String, Object>();
		//maps.put("redis", value);
		//return maps;
	//}

}

在springboot-web新建LoginController接口

package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.User;
import com.example.service.UserService;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    @ResponseBody
    public JSONObject login(HttpServletRequest request, String username, String password){
        JSONObject jsonObject = new JSONObject();
        if(username!=null && password !=null){
            User user = userService.findUserByName(username, password);
            if(user!=null){
                jsonObject.put("status","0");
                jsonObject.put("msg","登录成功!");
                return jsonObject;
            }else {
                jsonObject.put("status","1");
                jsonObject.put("msg","账号或密码不正确,请重新登录!");
                return jsonObject;
            }
        }else{
            jsonObject.put("status","1");
            jsonObject.put("msg","请填写正确信息!");
            return jsonObject;
        }
    }
    /**
     * 退出系统
     * @param session
     *   Session
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/logout")
    public String logout(HttpSession session) throws Exception{
        //清除Session
        session.invalidate();
        return "login";
    }
    @RequestMapping("404")
    public String page404() {
        return "404";
    }

    @RequestMapping("500")
    public String page500() {
        return "500";
    }
}

在springboot-web里新建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.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.example.entity.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="createDate" property="createdate" jdbcType="TIMESTAMP" />
    <result column="loginCount" property="logincount" jdbcType="INTEGER" />
    <result column="lastLoginTime" property="lastlogintime" jdbcType="TIMESTAMP" />
    <result column="staffId" property="staffid" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, username, password, createDate, loginCount, lastLoginTime, staffId
  </sql>
  <sql id="Base_Where_List">
    <if test="username != null  and username != ''">
      and username = #{username}
    </if>
    <if test="password != null and password != ''">
      and password = #{password}
    </if>
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from "u_user_info"
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from "u_user_info"
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.entity.User" >
    insert into "u_user_info" (id, username, password,
    createDate, loginCount, lastLoginTime,
    staffId)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
    #{createdate,jdbcType=TIMESTAMP}, #{logincount,jdbcType=INTEGER}, #{lastlogintime,jdbcType=TIMESTAMP},
    #{staffid,jdbcType=INTEGER})
  </insert>
  <insert id="addUser" parameterType="com.example.entity.User">
    insert into u_user_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="createdate != null" >
        createDate,
      </if>
      <if test="logincount != null" >
        loginCount,
      </if>
      <if test="lastlogintime != null" >
        lastLoginTime,
      </if>
      <if test="staffid != null" >
        staffId,
      </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="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null" >
        #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="logincount != null" >
        #{logincount,jdbcType=INTEGER},
      </if>
      <if test="lastlogintime != null" >
        #{lastlogintime,jdbcType=TIMESTAMP},
      </if>
      <if test="staffid != null" >
        #{staffid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.entity.User" >
    update "u_user_info"
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null" >
        createDate = #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="logincount != null" >
        loginCount = #{logincount,jdbcType=INTEGER},
      </if>
      <if test="lastlogintime != null" >
        lastLoginTime = #{lastlogintime,jdbcType=TIMESTAMP},
      </if>
      <if test="staffid != null" >
        staffId = #{staffid,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.entity.User" >
    update "u_user_info"
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      createDate = #{createdate,jdbcType=TIMESTAMP},
      loginCount = #{logincount,jdbcType=INTEGER},
      lastLoginTime = #{lastlogintime,jdbcType=TIMESTAMP},
      staffId = #{staffid,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="findUserByName" resultMap="BaseResultMap" parameterType="java.lang.String">
    select
    <include refid="Base_Column_List" />
    from u_user_info
    where username=#{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
  </select>
</mapper>

至此,项目配置完成。启动项目,

注意,springboot启动类要加这个注解@EnableTransactionManagement

,扫描mapper包,否则会报如下错误:

启动成功,访问地址http://localhost:8082/toLogin,输入账号密码,提示登录成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值