溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼

發(fā)布時(shí)間:2020-09-06 14:16:54 來(lái)源:腳本之家 閱讀:333 作者:濤聲依舊~ 欄目:編程語(yǔ)言

一、環(huán)境配置工程目錄

基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼

在pom.xml添加依賴

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.imooc</groupId>
  <artifactId>userLogin</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <!-- 使用junit4 用注解方式 -->
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- 補(bǔ)全項(xiàng)目依賴 -->
    <!-- 1:日志 java日志:slf4j,log4j,logback,common-logging slf4j 是規(guī)范/接口 日志實(shí)現(xiàn):log4j,logback,common-logging 
      使用:slf4j + logback -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.12</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.1</version>
    </dependency>
    <!-- 實(shí)現(xiàn)slf4j接口并整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.1</version>
    </dependency>

    <!-- 2:數(shù)據(jù)庫(kù)相關(guān)依賴 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>
    <!-- DAO框架:MyBatis依賴 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <!-- mybatis自身實(shí)現(xiàn)的spring整合依賴 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!--:3:servlet web相關(guān)依賴 -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.4</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!-- 4:spring依賴 -->
    <!-- 1)spring核心依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <!-- 2)spring dao層依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <!-- 3)spring web相關(guān)依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
    <!-- 4)spring test相關(guān)依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.2.0.RELEASE</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>userLogin</finalName>
    <plugins>
      <!-- define the project compile level -->
      <!-- maven編譯用的版本控制,控制jdk的版本不會(huì)回跳 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

數(shù)據(jù)庫(kù)驅(qū)動(dòng)配置

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysystem?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=kongtao

spring-web.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
     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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    ">
  <!-- 配置springMVC -->
  <!-- 1:開(kāi)啟springMVC注解模式 -->
  <!-- 簡(jiǎn)化配置:
     (1)自動(dòng)注冊(cè)DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
     (2)提供一系列:數(shù)據(jù)綁定,數(shù)字和日期的format @NumberFormat,@DataTimeFormat
    xml,json默認(rèn)讀寫(xiě)支持
   -->
  <mvc:annotation-driven/>
  
  <!-- 2:配置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/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
  <!-- 3:掃描web相關(guān)的bean -->
  <context:component-scan base-package="com.sy.controller" />
</beans>

二、具體邏輯實(shí)現(xiàn)數(shù)據(jù)訪問(wèn)對(duì)象(DAO接口)

UserDao.java

package com.sy.dao;

import org.apache.ibatis.annotations.Param;

import com.sy.entity.User;

public interface UserDao {
  
  
  /**
   * 查找用戶名和密碼
   * @param username 登錄用戶名 
   * @return
   */
  User findByUsername(String username);
  /**
   * 注冊(cè)用戶和密碼
   */
  void registerByUsernameAndPassword(@Param("username")String username,
                    @Param("password")String password);
}

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">
<mapper namespace="com.sy.dao.UserDao">
  <!-- 目的:為DAO接口方法提供sql語(yǔ)句配置 -->
  <!-- 查詢用戶和密碼進(jìn)行登錄 -->
  <select id="findByUsername" resultType="User" parameterType="String">
  
    select * from user where username = #{username}
      
  </select>

  <!--增加用戶名和密碼進(jìn)行注冊(cè) -->
  <insert id="registerByUsernameAndPassword">
     insert into user (username,password)
    values (#{username},#{password})
  </insert>
  
</mapper>

控制器

UserController.java

package com.sy.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sy.entity.User;
import com.sy.service.UserService;

@Controller
@RequestMapping("/user")

//這里用了@SessionAttributes,可以直接把model中的user(也就key)放入其中
//這樣保證了session中存在user這個(gè)對(duì)象
@SessionAttributes("user")
public class UserController {
  
  @Autowired
  private UserService userServivce;
  
  //正常訪問(wèn)login頁(yè)面
  @RequestMapping("/login")
  public String login(){
    return "login";
  }
  
  //表單提交過(guò)來(lái)的路徑
  @RequestMapping("/checkLogin")
  public String checkLogin(User user,Model model){
    //調(diào)用service方法
    user = userServivce.checkLogin(user.getUsername(), user.getPassword());
    //若有user則添加到model里并且跳轉(zhuǎn)到成功頁(yè)面
    if(user != null){
      model.addAttribute("user",user);
      return "success";
    }
    return "fail";
  }
  
  //測(cè)試超鏈接跳轉(zhuǎn)到另一個(gè)頁(yè)面是否可以取到session值
  @RequestMapping("/anotherpage")
  public String hrefpage(){
    
    return "anotherpage";
  }
  
  //注銷方法
  @RequestMapping("/outLogin")
  public String outLogin(HttpSession session){
    //通過(guò)session.invalidata()方法來(lái)注銷當(dāng)前的session
    session.invalidate();
    return "login";
  }

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

  @RequestMapping("/doRegist")
  public String doRegist(User user,Model model){
    System.out.println(user.getUsername());
    userServivce.Regist(user);
    return "success";
  }
}

實(shí)體類

package com.sy.entity;

public class User {
  
  
  private String id;
  
  private String username;
  
  private String password;

  public String getId() {
    return id;
  }

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

  public String getUsername() {
    return username;
  }

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

  public String getPassword() {
    return password;
  }

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

相關(guān)服務(wù)

UserService.java (接口)

package com.sy.service;
import com.sy.entity.User;

//Service層接口
public interface UserService {
  
  //檢驗(yàn)用戶登錄
  User checkLogin(String username,String password);
  void Regist(User user);
}

UserServiceImpl.java

package com.sy.service.Impl;

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

import com.sy.dao.UserDao;
import com.sy.entity.User;
import com.sy.service.UserService;

@Service
public class UserServiceImpl implements UserService{

  @Autowired
  private UserDao userDao;
  
  /* 
   * 檢驗(yàn)用戶登錄業(yè)務(wù)
   * 
   */

  public User checkLogin(String username, String password) {
    
    User user = userDao.findByUsername(username);
    if(user != null && user.getPassword().equals(password)){
    
      return user;
    }
    return null;
  }

  @Override
  public void Regist(User user) {

    userDao.registerByUsernameAndPassword(user.getUsername(),user.getPassword());

  }
}

其他配置文件

持久層相關(guān)配置文件 sprintg-dao.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:aop="http://www.springframework.org/schema/aop"
    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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!-- 配置整合mybatis過(guò)程 -->
  <!-- 1:配置數(shù)據(jù)庫(kù)相關(guān)參數(shù) properties的屬性:${url}-->
  <context:property-placeholder location="classpath:jdbc.properties"/>
  <!-- 2:數(shù)據(jù)庫(kù)連接池 -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 配置連接池屬性 -->
    <property name="driverClass" value="${jdbc.driverClass}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
  
    <!-- c3p0連接池的私有屬性 -->
    <property name="maxPoolSize" value="30"/>
    <property name="minPoolSize" value="10"/>
    <!-- 關(guān)閉連接后不自動(dòng)commit -->
    <property name="autoCommitOnClose" value="false"/>
    <!-- 獲取連接超時(shí)時(shí)間 -->
    <property name="checkoutTimeout" value="1000"/>
    <!-- 當(dāng)獲取連接失敗重試次數(shù) -->
    <property name="acquireRetryAttempts" value="2"/>
  </bean>
  
  <!-- 約定大于配置 -->
  <!-- 3:配置sqlsessionfactory對(duì)象 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 注入數(shù)據(jù)庫(kù)連接池 -->
    <property name="dataSource" ref="dataSource"/>
    <!-- 配置mybatis全局配置文件:mybatis-config.xml -->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!-- 掃描entity包 使用別名 com.sy.entity.User ->User -->
    <property name="typeAliasesPackage" value="com.sy.entity"/>
    <!-- 掃描sql配置文件:mapping需要的xml文件 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
  </bean>
  
  <!-- 4:配置掃描Dao接口的包,動(dòng)態(tài)實(shí)現(xiàn)Dao接口,注入到Spring容器中 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 注入sqlsessionfactory -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!-- 給出需要掃描的Dao接口包 -->
    <property name="basePackage" value="com.sy.dao"/>
  </bean>

</beans>

spring-service.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:aop="http://www.springframework.org/schema/aop"
    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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!-- 掃描service包下所有使用注解的類型 -->
  <context:component-scan base-package="com.sy.service"/>

  <!-- 配置事務(wù)管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入數(shù)據(jù)庫(kù)的連接池 -->
    <property name="dataSource" ref="dataSource"/>
  </bean>
  
  <!-- 配置基于注解的聲明式事務(wù)
    默認(rèn)使用注解來(lái)管理事務(wù)行為
   -->
  <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <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>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!-- 配置全局屬性 -->
  <settings>
    <!--使用jdbc的getGeneratedKeys獲取數(shù)據(jù)庫(kù)自增主鍵值 -->
    <setting name="useGeneratedKeys" value="true"/>
    <!-- 使用列別名替換列名  默認(rèn):true
      select name as title from table
     -->
    <setting name="useColumnLabel" value="true"/>
    <!-- 開(kāi)啟駝峰命名轉(zhuǎn)換:Table(create_time) -> Entity(createTime) -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings> 
 
</configuration>

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>Insert title here</title>
</head>
<body background="images/bg1.jpg">

  <form action="${pageContext.request.contextPath}/user/checkLogin" method="post">
    <table>
      <tr>
        <td>用戶名:</td>
        <td><input id="username" name="username" type="text"></td>
      </tr>
      <tr>
        <td>密碼:</td>
        <td><input id="password" name="password" type="password"></td>
      </tr>
      <tr >
        <td><input type="submit" value="登錄" ></td>
        <td><input type="button" value="注冊(cè)" onclick="window.location.href='/user/regist'"> </td>
      </tr>

    </table>
  </form>
</body>
</html>

regist.jsp

<%--
 Created by IntelliJ IDEA.
 User: 86265
 Date: 2018/1/30
 Time: 10:32
 To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>用戶注冊(cè)頁(yè)面</title>
</head>
<body>
  <h4>注冊(cè)頁(yè)面</h4>
  <hr/>
  <form action="${pageContext.request.contextPath}/user/doRegist" method="post">
    <table border="1px">
      <tr height="35px">
        <td width="150px">用戶名</td>
        <td width="300px">
          <input type="text" name="username" id="username">
        </td>
      </tr>
      <tr height="35px">
        <td>密碼</td>
        <td>
          <input type="text" name="password" id="password">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="submit" id="regist" value="注冊(cè)"/>
        </td>
      </tr>
    </table>
  </form>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>

  <div>
    <strong> welcome,${sessionScope.user.username}! </strong>
  </div>
  this is success page!

  <a href="${pageContext.request.contextPath}/user/anotherpage" rel="external nofollow" >點(diǎn)我跳到另一個(gè)頁(yè)面</a>

  <form action="${pageContext.request.contextPath}/user/login">
    <table>
      <tr>
        <td><input type="submit" value="退出登錄"></td>
      </tr>
    </table>
  </form>
</body>
</html>

fail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    u are loser,this is a fail page!
</body>
</html>

anotherpage.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>Insert title here</title>
</head>
<body>

  <div>
    <strong> ${sessionScope.user.username}!!!!! </strong>
  </div>
  <form action="user/outLogin">
    <table>
      <tr>
        <td><input type="submit" value="退出登錄" ></td>
      </tr>
    </table>
  </form>
</body>
</html>

三、運(yùn)行結(jié)果

基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼

基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼

基于SSM框架實(shí)現(xiàn)簡(jiǎn)單的登錄注冊(cè)的示例代碼

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI