SSM專案搭建及實現簡單的登入

道雖邇,不行不至發表於2020-11-08

使用工具idea;
Java版本1.8.0_251;
關係型資料庫MySQL;

專案整體目錄:
在這裡插入圖片描述

專案建立:
點選file – new – project — 選擇maven 選擇如下:

在這裡插入圖片描述
點選next,輸入專案名稱等
在這裡插入圖片描述

填好後,選擇自己的maven配置檔案
在這裡插入圖片描述
建立好後,在main下沒有Java、resources資料夾,需要自己建立,右鍵main資料夾,new建立java資料夾、resources資料夾,然後右鍵java資料夾,選擇如下:
在這裡插入圖片描述
右鍵resources資料夾,同樣做如下操作:
在這裡插入圖片描述
pom新增依賴:

<!--SpringMVC的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.2.RELEASE</version>
    </dependency>
    <!--mysql連線的jar包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.18</version>
    </dependency>
    <!-- SpringJDBC -->
    <!-- 注意:與當前專案使用的其它spring依賴保持相同的版本號 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.2.RELEASE</version>
    </dependency>
    <!--資料庫連線池dbcp的jar包-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!--MyBatis的jar包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.3</version>
    </dependency>
    <!--Spring整合MyBatis的jar包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.3</version>
    </dependency>
    <!--測試包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

web.xml配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
  <display-name>Archetype Created Web Application</display-name>

  <!--配置過濾器,解決中文亂碼 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--配置spring監聽器,預設只載入WEB-INF檔案下面的applicationContext.xml配置檔案 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--改變預設配置檔案路徑 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--前端控制器 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!--servlet載入springmvc配置檔案  -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

jdbc.properties配置檔案:

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver=com.mysql.cj.jdbc.Driver
username=root
password=123456
initialSize=2
maxActive=10

applicationContext.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:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 自動掃描 -->
    <context:component-scan base-package="com.ssm01.dao"></context:component-scan>
    <context:component-scan base-package="com.ssm01.service"></context:component-scan>
    <context:component-scan base-package="com.ssm01.serviceImpl"></context:component-scan>

    <util:properties id="properties" location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url" value="#{properties.url}"/>
        <property name="driverClassName" value="#{properties.driver}" />
        <property name="username" value="#{properties.username}" />
        <property name="password" value="#{properties.password}" />
        <property name="initialSize" value="#{properties.initialSize}" />
        <property name="maxActive" value="#{properties.maxActive}" />
    </bean>

    <!-- 配置MapperScannerConfigurer -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置介面檔案在哪裡 -->
        <property name="basePackage" value="mapper" />
    </bean>

    <!-- 配置SqlSessionFactoryBean -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置XML檔案在哪裡 -->
        <property name="mapperLocations" value="classpath:mappers/*.xml" />
        <!-- 配置使用哪個資料來源連線資料庫 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- spring自動查詢其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm01.dao"></property>
    </bean>
</beans>

springmvc.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"
       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">
    <!--配置包掃描,掃描到加註解的類自動建立bean元件-->
    <context:component-scan base-package="com.ssm01.controller"/>

    <!-- 2.配置對映處理和介面卡-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!-- 3.檢視的解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

配置檔案建好後,在Java包下建立需要的Java包,及類。

建立user實體類

package com.ssm01.entity;

import java.io.Serializable;

public class User implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public int id;
    public String userNo;
    public String userName;
    public String userCode;
    public String pwd;
    public String sex;
    public int age;
    public String job;
    public String phone;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserNo() {
        return userNo;
    }
    public void setUserNo(String userNo) {
        this.userNo = userNo;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", userNo=" + userNo + ", userName="
                + userName + ", userCode=" + userCode + ", pwd=" + pwd
                + ", sex=" + sex + ", age=" + age + ", job=" + job + ", phone="
                + phone + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((job == null) ? 0 : job.hashCode());
        result = prime * result + ((phone == null) ? 0 : phone.hashCode());
        result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
        result = prime * result + ((sex == null) ? 0 : sex.hashCode());
        result = prime * result
                + ((userCode == null) ? 0 : userCode.hashCode());
        result = prime * result
                + ((userName == null) ? 0 : userName.hashCode());
        result = prime * result + ((userNo == null) ? 0 : userNo.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (job == null) {
            if (other.job != null)
                return false;
        } else if (!job.equals(other.job))
            return false;
        if (phone == null) {
            if (other.phone != null)
                return false;
        } else if (!phone.equals(other.phone))
            return false;
        if (pwd == null) {
            if (other.pwd != null)
                return false;
        } else if (!pwd.equals(other.pwd))
            return false;
        if (sex == null) {
            if (other.sex != null)
                return false;
        } else if (!sex.equals(other.sex))
            return false;
        if (userCode == null) {
            if (other.userCode != null)
                return false;
        } else if (!userCode.equals(other.userCode))
            return false;
        if (userName == null) {
            if (other.userName != null)
                return false;
        } else if (!userName.equals(other.userName))
            return false;
        if (userNo == null) {
            if (other.userNo != null)
                return false;
        } else if (!userNo.equals(other.userNo))
            return false;
        return true;
    }

}

建立UserDao

package com.ssm01.dao;

import com.ssm01.entity.User;

import java.util.List;

public interface UserDao {

    public User login(User user);

    public User add(User user);

    public User update(User user);

    public boolean delete(int id);

    public List<User> selectList();

}

建立UserService

package com.ssm01.service;

import com.ssm01.entity.User;

import java.util.List;
import java.util.Map;

public interface UserService {

    public Map<String, Object> login(User user);

    public Map<String, Object> add(User user);

    public Map<String, Object> update(User user);

    public boolean delete(int id);

    public List<User> selectList();

}

建立UserServiceImpl

package com.ssm01.serviceImpl;

import com.ssm01.dao.UserDao;
import com.ssm01.entity.User;
import com.ssm01.service.UserService;
import org.springframework.stereotype.Service;

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

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;

    @Override
    public Map<String, Object> login(User user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", userDao.login(user));
        return map;
    }

    @Override
    public Map<String, Object> add(User user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", userDao.add(user));
        return map;
    }

    @Override
    public Map<String, Object> update(User user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", userDao.update(user));
        return map;
    }

    @Override
    public boolean delete(int id) {
        return userDao.delete(id);
    }

    @Override
    public List<User> selectList() {
        return userDao.selectList();
    }

}

建立UserController

package com.ssm01.controller;

import com.ssm01.entity.User;
import com.ssm01.service.UserService;
import com.ssm01.util.ResultMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

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


    @Resource
    UserService userService;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResultMessage login(User user){

        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        try {
            Map<String, Object> map = userService.login(user);
            list.add(map);
            return ResultMessage.newInstance(0, "登入成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.newInstance(1, "登入失敗", list);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/selectList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResultMessage selectList(){
        List<User> list = new ArrayList<User>();
        try {
            list = userService.selectList();
            return ResultMessage.newInstance(0, "查詢成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.newInstance(1, "查詢失敗", list);
        }
    }

}

建立請求返回實體類ResultMessage

package com.ssm01.util;

import java.io.Serializable;
import java.util.List;

public class ResultMessage implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private int code = 0;
    private String message;
    private List<?> date;

    public ResultMessage(){
    }

    public ResultMessage(int code, String message, List<?> date){
        this.code = code;
        this.message = message;
        this.date = date;
    }

    public static ResultMessage newInstance(int code, String message, List<?> date){
        ResultMessage obj = new ResultMessage();
        obj.code = code;
        obj.message = message;
        obj.date = date;
        return obj;
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<?> getDate() {
        return date;
    }

    public void setDate(List<?> date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "ResultMessage [code=" + code + ", message=" + message
                + ", date=" + date + "]";
    }

}

建立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.ssm01.dao.UserDao">

    <resultMap type="com.ssm01.entity.User" id="UserResult">
        <id property="id" column="id"></id>
        <result property="userName" column="user_ame"></result>
        <result property="pwd" column="password"></result>
    </resultMap>

    <select id="login" parameterType="com.ssm01.entity.User" resultMap="UserResult">
 		select * from user where user_name=#{userName} and password=#{pwd}
 	</select>

    <select id="add" parameterType="com.ssm01.entity.User" resultMap="UserResult">
 		insert into user (user_name,password) values(#{userName},#{pwd})
 	</select>

</mapper>

修改index.jsp作為登入頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>使用者登入頁面</title>
</head>
<body>
<a href="add.jsp">註冊</a>&nbsp;<br/>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    userName:<input type="text" name="userName" value="${userName}"/><br/>
    passWord:<input type="password" name="pwd" value="${pwd}"/><br/>
    <input type="submit" value="登入"/><br/>
    <font color="red">${errorMsg}</font>
</form>
</body>
</html>

新增完成後,需要配置Tomcat
在這裡插入圖片描述
點選左上角的加號圖示
在這裡插入圖片描述
找到tomcat server,點選下面的local
在這裡插入圖片描述
做如下選擇處理,最後點選fix;這裡需要修改Tomcat的配置檔案,這裡是已經修改後的結果,如需修改請自行百度
在這裡插入圖片描述
做如下選擇後點選OK
在這裡插入圖片描述
這裡可以把library新增進來
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
都配置好後,即可啟動工程,啟動工程後回自動跳轉瀏覽器,開啟localhost:8081/SSM01

目前只做了請求到後端,沒有做後端返回前端的處理,後續會繼續補充。
在這裡插入圖片描述

相關文章