1. 程式人生 > >IDEA 2018搭建SSM框架實現登入、註冊、刪除使用者、修改個人資訊、退出登入等功能

IDEA 2018搭建SSM框架實現登入、註冊、刪除使用者、修改個人資訊、退出登入等功能

1.先來看一下完成的效果圖:

註冊賬號:


登入賬號:


首頁展示:


修改賬號:


顯示所有賬號資訊(點選按鈕可刪除該條資訊):


2.使用idea新建一個Maven webapp專案

記得打鉤:


取名字:


設定版本號:


OK!

3.搭建目錄結構



4.設定,讓IDEA識別目錄的作用


5.相關程式碼的編寫

chatrobot.sql新建資料庫

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '使用者ID',
  `email` varchar(255) NOT NULL COMMENT '使用者郵箱',
  `password` varchar(255) NOT NULL COMMENT '使用者密碼',
  `username` varchar(255) NOT NULL COMMENT '使用者暱稱',
  `role` varchar(255) NOT NULL COMMENT '使用者身份',
  `status` int(1) NOT NULL COMMENT '使用者狀態',
  `regTime` datetime NOT NULL COMMENT '註冊時間',
  `regIp` varchar(255) NOT NULL COMMENT '註冊IP',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1');
SET FOREIGN_KEY_CHECKS=1;

User.java

package com.chatRobot.model;

import java.util.Date;

public class User {

    private long id;
    private String email;
    private String password;
    private String username;
    private String role;
    private int status;
    private Date regTime;
    private String regIp;

    public long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Date getRegTime() {
        return regTime;
    }

    public void setRegTime(Date regTime) {
        this.regTime = regTime;
    }

    public String getRegIp() {
        return regIp;
    }

    public void setRegIp(String regIp) {
        this.regIp = regIp;
    }

}

IUserDao.java

package com.chatRobot.dao;

import com.chatRobot.model.User;

import java.util.List;

public interface IUserDao {

    User selectUser(long id);

    List<User> selectAllUser();

    User selectUserByEmail(String email);

    User addUser(User user);

    User removeUser(long id);

    User modifyUser(User user);

}

IUserService.java

package com.chatRobot.service;

import com.chatRobot.model.User;

import java.util.List;

public interface IUserService {

    public User selectUser(long userId);

    public List<User> selectAllUser();

    public User selectUserByEmail(String email);

    public User addUser(User user);

    public User removeUser(long userId);

    public User modifyUser(User user);

}

UserServiceImpl.java

package com.chatRobot.service.impl;

import com.chatRobot.dao.IUserDao;
import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import org.springframework.stereotype.Service;

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

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    public User selectUser(long userId) {
        return this.userDao.selectUser(userId);
    }

    public List<User> selectAllUser() {
        return this.userDao.selectAllUser();
    }

    public User selectUserByEmail(String email) {
        return this.userDao.selectUserByEmail(email);
    }

    public User addUser(User user) {
        return this.userDao.addUser(user);
    }

    public User removeUser(long userId) {
        return this.userDao.removeUser(userId);
    }

    public User modifyUser(User user) {
        return this.userDao.modifyUser(user);
    }

}

UserController.java

package com.chatRobot.controller;

import javax.servlet.http.HttpServletRequest;

import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;
    private long userId;
    private ObjectMapper mapper;

    //Ok!!!
    @RequestMapping(value = "/showUser/{id}", method = RequestMethod.GET)
    public void getUser(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        long userId = Long.parseLong(id);
        User user = this.userService.selectUser(userId);
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(user));
        response.getWriter().close();
    }

    //Ok!!!!
    @RequestMapping(value = "/loginUser", method = RequestMethod.GET)
    public void loginUser(User loginUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        User user = this.userService.selectUserByEmail(loginUser.getEmail());
        ObjectMapper mapper = new ObjectMapper();
        if (user == null) {
            response.getWriter().write("賬號不存在!");
        } else if (!loginUser.getPassword().equals(user.getPassword())) {
            response.getWriter().write("密碼輸入錯誤!");
        } else {
            response.getWriter().write(mapper.writeValueAsString(user));
        }
        response.getWriter().close();
    }

    //Ok!!!!
    @RequestMapping(value = "/allUser", method = RequestMethod.GET)
    public void allUser(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        List<User> userList = userService.selectAllUser();
        String userMsg = "";
        for (User user : userList) {
            userMsg = userMsg + "<tr>";
            userMsg = userMsg + "<td>" + user.getId() + "</td>";
            userMsg = userMsg + "<td>" + user.getUsername() + "</td>";
            userMsg = userMsg + "<td>" + user.getPassword() + "</td>";
            userMsg = userMsg + "<td>" + user.getEmail() + "</td>";
            userMsg = userMsg + "<td>" + user.getRole() + "</td>";
            userMsg = userMsg + "<td>" + user.getStatus() + "</td>";
            userMsg = userMsg + "<td>" + user.getRegTime() + "</td>";
            userMsg = userMsg + "<td>" + user.getRegIp() + "</td>";
            userMsg = userMsg + "<td><input type='button' value='刪 除' onclick='removeUser(" + user.getId() + ")'/></td>";
            userMsg = userMsg + "</tr>";
        }
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(userMsg));
    }

    //Ok!!!!
    @RequestMapping(value = "/showUser", method = RequestMethod.POST)
    public void postUser(User registUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        User user = this.userService.selectUserByEmail(registUser.getEmail());
        if (user != null) {
            response.getWriter().write("該賬號已經註冊過!");
        } else {
            registUser.setStatus(1);
            registUser.setRegTime(new Date());
            registUser.setRegIp("127.0.0.6");
            this.userService.addUser(registUser);
            response.getWriter().write(mapper.writeValueAsString(user));
        }
        response.getWriter().close();
    }

    //Ok!!!
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public void putUser(User updateUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        System.out.println(updateUser.getUsername());
        System.out.println(updateUser.getPassword());
        ObjectMapper mapper = new ObjectMapper();
        User user = this.userService.modifyUser(updateUser);
        response.getWriter().write(mapper.writeValueAsString(user));
        response.getWriter().close();
    }

    //Ok!!!!
    @RequestMapping(value = "/removeUser/{id}", method = RequestMethod.DELETE)
    public void deleteUser(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        long userId = Long.parseLong(id);
        this.userService.removeUser(userId);
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write("remove success!");
        response.getWriter().close();
    }

}

UserDao.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">

<!-- 設定為IUserDao介面方法提供sql語句配置 -->
<mapper namespace="com.chatRobot.dao.IUserDao">

    <select id="selectUser" resultType="User" parameterType="long">
        select * from user where id = #{id}
    </select>

    <select id="selectAllUser" resultType="User">
        select * from user
    </select>

    <select id="selectUserByEmail" resultType="User" parameterType="string">
        select * from user where email = #{email}
    </select>

    <select id="addUser" resultType="User" parameterType="User">
        insert into user (email,password,username,role,status,regTime,regIp) values (#{email},#{password},#{username},#{role},#{status},#{regTime},#{regIp})
    </select>

    <select id="removeUser" resultType="User" parameterType="long">
        delete from user where id = #{id}
    </select>

    <select id="modifyUser" resultType="User" parameterType="User">
        update user set
                 email = #{email},
                 password = #{password},
                 username = #{username},
                 role = #{role},
                 status = #{status},
                 regIp = #{regIp}
                 where id = #{id}
    </select>

</mapper>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
#資料庫地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/chatrobot?useUnicode=true&characterEncoding=utf8
#使用者名稱
jdbc.username=root
#密碼
jdbc.password=root
#最大連線數
c3p0.maxPoolSize=30
#最小連線數
c3p0.minPoolSize=10
#關閉連線後不自動commit
c3p0.autoCommitOnClose=false
#獲取連線超時時間
c3p0.checkoutTimeout=10000
#當獲取連線失敗重試次數
c3p0.acquireRetryAttempts=2

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 掃描web相關的bean -->
    <context:component-scan base-package="com.chatRobot.controller"/>

    <!-- 開啟SpringMVC註解模式 -->
    <mvc:annotation-driven/>

    <!-- 靜態資源預設servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 配置jsp 顯示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 掃描service包下所有使用註解的型別 -->
    <context:component-scan base-package="com.chatRobot.service"/>

    <!-- 配置資料庫相關引數properties的屬性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 資料庫連線池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>

    <!-- 配置SqlSessionFactory物件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入資料庫連線池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 掃描model包 使用別名 -->
        <property name="typeAliasesPackage" value="com.chatRobot.model"/>
        <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描Dao介面包 -->
        <property name="basePackage" value="com.chatRobot.dao"/>
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入資料庫連線池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基於註解的宣告式事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

func.js

//Ok!!
function addUser() {
    var username = $("#username").val();
    var password = $("#password").val();
    var email = $("#email").val();
    var role = $("#role").val();
    var user = {
        "username": username,
        "password": password,
        "email": email,
        "role": role
    };
    var _url = "http://localhost:8080/ChatRobot/user/showUser";
    $.ajax({
        url: _url,
        type: "POST",
        data: user,
        contentType: "application/x-www-form-urlencoded",
    }).done(function (data) {
        if (data == "該賬號已經註冊過!") {
            alert("該賬號已經註冊過!");
            return false;
        } else {
            window.sessionStorage.setItem("user", data);
            window.location.replace("http://localhost:8080/ChatRobot/user_index.html");
        }
    }).fail(function (res) {
        alert("註冊失敗!");
    });
}

//Ok!!
function loginUser() {
    var password = $("#password").val();
    var email = $("#email").val();
    var role = $("#role").val();
    var user = {
        "password": password,
        "email": email,
        "role": role
    };
    var _url = "http://localhost:8080/ChatRobot/user/loginUser";
    $.ajax({
        url: _url,
        type: "GET",
        data: user,
        contentType: "application/x-www-form-urlencoded",
    }).done(function (data) {
        if (data == "密碼輸入錯誤!") {
            alert("密碼錯誤!");
            return false;
        } else if (data == "賬號不存在!") {
            alert("賬號不存在!");
            return false;
        } else {
            window.sessionStorage.setItem("user", data);
            window.location.replace("http://localhost:8080/ChatRobot/user_index.html");
        }
    }).fail(function (res) {
        alert("登入失敗!");
    });
}

//Ok!!!
function updateUser() {
    var user = {
        "id": $("#id").val(),
        "username": $("#username").val(),
        "password": $("#password").val(),
        "email": $("#email").val(),
        "role": $("#role").val(),
        "status": $("#status").val(),
        "regTime": new Date(),
        "regIp": $("#regIp").val()
    };
    console.log(user);
    var _url = "http://localhost:8080/ChatRobot/user/updateUser";
    $.ajax({
        url: _url,
        type: "POST",
        data: user,
        contentType: "application/x-www-form-urlencoded",
    }).done(function (data) {
        window.location.replace("http://localhost:8080/ChatRobot/user_info.html");
    }).fail(function (res) {
        window.location.replace("http://localhost:8080/ChatRobot/user_info.html");
    });
}

//Ok!!!
function removeUser(id) {
    var _url = "http://localhost:8080/ChatRobot/user/removeUser";
    alert("第" + id + "條資料已被刪除!");
    $.ajax({
        type: "DELETE",
        url: _url + "/" + id,
        dataType: "json",
        success: function (data) {
            window.location.reload();
        },
        error: function (res) {
            window.location.reload();
        }
    });
}

//Ok!!!
function removeSession() {
    window.sessionStorage.removeItem("user");
}

html檔案裡面的js

<script>
        $(document).ready(function () {
            var data = window.sessionStorage.getItem("user");
            if (data != null) {
                var user = $.parseJSON(data);
                $("#showName").html(user.username);
            } else {
                $("#showName").append("歡迎");
            }
        });
    </script>
<script>
        $(document).ready(function () {
            var data = window.sessionStorage.getItem("user");
            if (data != null) {
                var user = $.parseJSON(data);
                $("#showName").html(user.username);
            } else {
                $("#showName").append("歡迎");
            }
            if (data != null) {
                var user = $.parseJSON(data);
                $("#id").val(user.id);
                $("#email").val(user.email);
                $("#username").val(user.username);
                $("#password").val(user.password);
                $("#role").val(user.role);
                $("#status").val(user.status);
                $("#regTime").val(user.regTime);
                $("#regIp").val(user.regIp);
            }
        });
    </script>
<script>
        $(document).ready(function () {
            var data = window.sessionStorage.getItem("user");
            if (data != null) {
                var user = $.parseJSON(data);
                $("#showName").html(user.username);
            } else {
                $("#showName").append("歡迎");
            }

            var _url = "http://localhost:8080/ChatRobot/user/allUser";
            $.ajax({
                url: _url,
                type: "GET",
                cache: false,
                processData: false,
                contentType: "application/x-www-form-urlencoded"
            }).done(function (data) {
                console.log("success!" + data);
                $("table").append(data);
            }).fail(function (res) {
                console.log("sorry,failed!" + res);
            });
        });
    </script>
OK!前端頁面的程式碼沒有貼出來,因為程式碼量實在是太龐大,不過可以前往我的資源https://download.csdn.net/download/qq_29656961/10498799裡面去下載,這是我第一次寫SSM框架,不足之處還會在後續的學習之中慢慢改進。