Based on Spring+Mybatis+jsp+servlet's user login and registration function (database search and user insertion), JSP writes the front end (css+javascript), using IDEA

Based on Spring+Mybatis+jsp+servlet's user login and registration function (database search and user insertion), JSP writes the front end (css+javascript), using IDEA

!!! Code at the end
The design of the front end of the web page: jsp writing, using css to beautify (the font uses Google font, the icon uses font awesome, the color uses palettes|flat ui colors, Google can find it, I think it's good to use it)
Simple js is used to verify the user name length, password and confirm password of the form
Project structure

(1) establish a database named spring, a table of user information, field id, username, password

(2) front end jsp and css code writing
(3) Mybatis general configuration file of sqlMapConfig.xml
(4) general Spring configuration file of ApplicationContext.xml
(5) write User class bean
(6) the UserMapper interface and the UserMapper.xml definition implement the findById, findByName, findByUser, insertUser methods of SQL statements
(7) UserService interface and UserServiceImpl implementation class (implement addAccount and hasAccount methods)
(8) servlet classes under util Toolkit (LoginServlet and RegisterServlet)
Profile:
(1)sqlMapConfig.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>
    <typeAliases>
        <package name="com.dingxiang.bean"/>
    </typeAliases>
    <mappers>
        <mapper class="com.dingxiang.mapper.UserMapper"/>
    </mappers>
</configuration>

(2) UserMapper.xml (configure the implementation of UserMapper interface)

<?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.dingxiang.mapper.UserMapper">
    <select id="findById" resultType="User" parameterType="Integer">
        select * from spring.user_information where id=#{id}
    </select>
    <select id="findByName" parameterType="String" resultType="User">
        select * from spring.user_information where username=#{username}
    </select>
    <select id="findByUser" parameterType="User" resultType="User">
        select * from spring.user_information where username=#{username} and password=#{password}
    </select>
    <insert id="insertUser" parameterType="User">
        insert  into spring.user_information (username,password) values(#{username},#{password})
    </insert>
</mapper>

(3) ApplicationContext.xml (configure DataSource, sqlsessionFactory, Mapper implementation to give the User to Spring management, and the database implementation of Mybatis is completed by Spring for us)

<?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">
    <bean class="com.dingxiang.service.UserServiceImpl" name="userService"/>
    <!--To configure datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value="*****"/>
    </bean>
        <!--To configure SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="sqlMapConfig.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" name="configurer">
        <property name="basePackage" value="com.dingxiang.mapper"/>
    </bean>
</beans>

Front end web page code (use js to replace display page, login, register and simple form validation)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta charset="utf-8">
  <title>login-register</title>
  <link rel="stylesheet" type="text/css" href="css/style.css"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body>
<div class="bt">
  <i class="fas fa-long-arrow-alt-right"></i>Login  my own account<br/>
</div>
<div class="register">
  <i class="fas fa-registered"></i>Register new account
</div>
<div class="login-box">
  <div class="hide-bt1">
    <i class="fas fa-times"></i>
  </div>
  <form action="<%=request.getContextPath()%>/login.do" method="post" class="login-form">
    <h1>Welcome</h1>
    <input type="text" name="username" id="" class="text"  placeholder="USERNAME" />
    <input type="password" name="password" id="" class="text" placeholder="PASSWORD" />
    <input type="submit" name="" class="login-bt" id="" value="Login" />
  </form>
</div>
<div class="register-box">
  <div class="hide-bt2">
    <i class="fas fa-times"></i>
  </div>
  <form action="<%=request.getContextPath()%>/register.do" method="post" class="register-form">
    <h1>Welcome</h1>
    <input type="text" name="username" id="username" class="text"  placeholder="USERNAME" onblur="checkregister_username(this)"/>
    <input type="password" name="password" id="password" class="text" placeholder="PASSWORD" onblur="checkregister_pass(this)"/>
    <input type="password" name="repassword" id="repassword" class="text" placeholder="REPASSWORD" onblur="checkregister_repass(this)"/>
    <input type="submit" name="" class="register-bt" id="" value="Register" />
  </form>
</div>
</body>
</html>
<script type="text/javascript">
  $(".bt").on("click",function(){
    $(".login-box").toggleClass("showed_login");
  })
  $(".register").on("click",function(){
    $(".register-box").toggleClass("showed_register");
  })
  $(".hide-bt1").on("click",function(){
    $(".login-box").toggleClass("showed_login");
  })
  $(".hide-bt2").on("click",function(){
    $(".register-box").toggleClass("showed_register");
  })
  function checkregister_username(username) {
    if (username.value.length < 3 || username.value.length > 10) {
      alert("User name must be 3-10 position");
    }
  }
  function checkregister_pass(pass){
    var repass=document.getElementById("repassword").value;
    var username=document.getElementById("username").value;
    if(username==null||username==""){
      alert("enter one user name");
    }
    if(pass.value.length<3||pass.value.length>10){
      alert("Password must be 3-10 position");
    }
  }
  function checkregister_repass (repass) {
    var pass=document.getElementById("password").value;
    if(repass.value!=pass){
      alert("Please enter the same password as the confirm password");
    }
  }
</script>

css

*{
    font-family: "montserrat",sans-serif;
}
body{
    margin: 0;
    padding: 0;
    background: #333;
}
.login-box{
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100vh;
    background-image: linear-gradient(45deg,#9fbaa8,#31354c);
}
.login-form{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    color: white;
    text-align: center;
}
.login-form h1{
    font-family: 'Pacifico', cursive;
    font-weight: 400;
    font-size: 40px;
    margin-top: 0;
}
.text{
    display: block;
    box-sizing: border-box;
    width: 240px;
    background: #ffffff28;
    border: 1px solid white;
    padding: 10px 20px;
    color: white;
    outline: none;
    margin: 10px 0;
    border-radius: 6px;
    text-align: center;
}
.login-bt{
    font-family: 'Pacifico', cursive;
    width: 240px;
    background: #c0392b;
    border: 0;
    color: white;
    padding: 10px;
    border-radius: 6px;
    cursor: pointer;
}
.login-bt:hover{
    background: #e74c3c;
}
.hide-bt1{
    color: #000;
    position: absolute;
    top: 40px;
    right: 40px;
    cursor: pointer;
    font-size: 24px;

}
.bt{
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate(-50%,-50%);
    color: white;
    border: 2px solid;
    padding: 10px;
    cursor: pointer;
}
.register{
    left: 50%;
    position: absolute;
    top: 60%;
    transform: translate(-50%,-50%);
    color: white;
    border: 2px solid;
    padding: 10px;
    cursor: pointer;
}
.showed_login{
    left: 0%;
}

.register-box{
    position: absolute;
    top: 0;
    left: -200%;
    width: 100%;
    height: 100vh;
    background-image: linear-gradient(45deg,#9fbaa8,#31354c);
}
.register-form{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    color: white;
    text-align: center;
}
.register-form h1{
    font-family: 'Pacifico', cursive;
    font-weight: 400;
    font-size: 40px;
    margin-top: 0;
}
.register-bt{
    font-family: 'Pacifico', cursive;
    width: 240px;
    background: #c0392b;
    border: 0;
    color: white;
    padding: 10px;
    border-radius: 6px;
    cursor: pointer;
}
.register-bt:hover{
    background: #e74c3c;
}
.showed_register{
    left: 0%;
}
.hide-bt2{
    color: #000;
    position: absolute;
    top: 40px;
    right: 40px;
    cursor: pointer;
    font-size: 24px;

}

Front page display:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login has failed</title>
</head>
<body>
<h1>
    This user already exists. Please register again.
    <p><a href="index.jsp">Click here to return to registration</a> </p>
</h1>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login successfully</title>
</head>
<body>
<h1>
    Login succeeded, welcome<%=request.getParameter("username")%>. <P><a href="index.jsp">Click here to return.</a></P>
</h1>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login was successful</title>
</head>
<body>
<h1>
    Successfully registered,<%=request.getParameter("username")%>. <P><a href="index.jsp">Click here to return to login</a></P>
</h1>
</body>
</html>

UserMapper interface

package com.dingxiang.mapper;

import com.dingxiang.bean.User;

public interface UserMapper {
    User findById(Integer id)throws Exception;
    User findByName(String username)throws Exception;
    User findByUser(User user)throws Exception;
    void insertUser(User user)throws Exception;

}

UserService interface

package com.dingxiang.service;

import com.dingxiang.bean.User;

public interface UserService {
    Boolean hasAccount(String username,String password)throws Exception;
    void addAccount(String username,String password)throws Exception;
}

UserServiceImpl implementation class

package com.dingxiang.service;

import com.dingxiang.bean.User;
import com.dingxiang.mapper.UserMapper;

import javax.annotation.Resource;

public class UserServiceImpl implements UserService{
    @Resource(type = UserMapper.class)
    private UserMapper userMapper;

    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Boolean hasAccount(String username, String password) throws Exception {
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        if(userMapper.findByUser(user)!=null){
            return false;
        }
        return false;
    }

    @Override
    public void addAccount(String username, String password) throws Exception {
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insertUser(user);
    }
}

LoginServlet

package com.dingxiang.utils;

import com.dingxiang.bean.User;
import com.dingxiang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(
        name = "loginServlet",
        urlPatterns = {"/login.do"}
)
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID =1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        ApplicationContext ac=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        UserService userService= (UserService) ac.getBean("userService");
        try {
            if(userService.hasAccount(username,password)){
                response.sendRedirect("sccuess.jsp");
            }else{
                response.sendRedirect("index.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

RegisterServlet

package com.dingxiang.utils;

import com.dingxiang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(
        name = "registerServlet",
        urlPatterns = {"/register.do"}
)
public class RegisterServlet extends HttpServlet {
    private ApplicationContext ac=null;
    private static final long serialVersionUID =1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    public void init() throws ServletException {
        ac=new ClassPathXmlApplicationContext("ApplicationContext.xml");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        UserService userService= (UserService) ac.getBean("userService");
        try {
            if(userService.hasAccount(username,password)){
                request.getRequestDispatcher("chongfu.jsp").forward(request,response);
            }else{
                userService.addAccount(username,password);
                response.sendRedirect("success_register.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Class User

package com.dingxiang.bean;

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    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;
    }

    public String getPassword() {
        return password;
    }

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

Tags: Spring xml Mybatis JSP

Posted on Fri, 08 Nov 2019 07:45:15 -0800 by tinyashcities