The three simple and easy-to-learn SSM frameworks (Spring + spring MVC + mybatis) require Ajax asynchronous technology integration. Have you failed?

I. Introduction to SSM framework

  • SSM framework is the acronym of Spring + Spring MVC + MyBatis. It is the mainstream Java EE enterprise framework after inheriting SSH. It is suitable for building various large-scale enterprise application systems. As shown in the figure:

1, What is Spring

  • Spring is an open source framework. It is a lightweight container framework for * * inversion of control (IOC) and aspect oriented (AOP) *.

1. What is inversion of control (IOC)?

  • IOC: inversion of control is also called dependency injection. Using the factory mode to hand over the object to the container for management, you only need to configure the corresponding bean in spring and let the spring container generate the instance object and management object of the class.

2. What is AOP?

  • AOP is just an idea of Spring. It is a programming idea similar to OOP, not a technology, but a supplement and improvement to OOP.

2, What is spring MVC

  • Spring MVC is a part of the Spring Framework. It is a lightweight Web framework based on Java to implement MVC. It can make development very simple and standardized.

1. What is MVC?

  • MVC is the abbreviation of model, view and controller. It is a software design specification.

3, Role of MyBatis

  • Mybatis is a persistence layer framework used to help you quickly manage data addition, deletion, modification and query. Mybatis is an excellent framework for jdbc encapsulation, stored procedures and high-level mapping. Configure and original mapping using simple XML or annotation.

II. Database

(employee table, no primary / foreign key Association)
(identity table, no primary / foreign key Association)

III. code measurement

1, Measuring tool

IDEA 2020.3.3
MySQL
maven 3.3.9
Tomcat 9.0.46

2, Project measurement is the source code

Note: this project is only for the purpose of learning, not the real project requirements, and there are often some bugs.
Source code download address: https://pan.baidu.com/s/1eD3Q1Z7p5N6IC4eiQRZ3iQ
Extraction code: 1024

1. Create Maven project

2. Click maven, check the "Create from archetype" option, select the structure of "...: Maven archetype webapp", and then click "Next" to Next.
3. Enter the project name (ssmDemo) and select the project storage path. Step 3 is optional.

4. Click to select the path of Maven download.
5. Check "Override", then click the folder icon on the left and select "settings.xml" of maven.
6. Check "Override" and click the folder icon on the left to select the folder where maven depends on the warehouse for storage. (Note: maven dependent warehouse can be customized).

7. The whole is shown in the figure.

8. If this happens in the lower left corner of the IDEA, you need to wait for a while. It depends partly on downloading.

9. After downloading, the file directory structure is shown in the figure below. (Note: you can also add a web project to the original java project, which will not be demonstrated here)

10. The overall directory structure of the ssm framework is shown in the figure below. (Note: you need to create your own folder)
11. Then click "pom.xml" to replace the code in the yellow box with the following dependent jar packages

Replace the following dependencies

<properties>
    <spring.version>4.2.6.RELEASE</spring.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis-spring.version>1.2.2</mybatis-spring.version>
    <servlet.version>3.0.1</servlet.version>
    <druid.version>1.0.13</druid.version>
    <jsp-api.version>2.1</jsp-api.version>
    <jstl.version>1.2</jstl.version>
    <mysql.connector.version>5.1.38</mysql.connector.version>
    <aspectj.version>1.8.6</aspectj.version>
    <commons.fileupload.version>1.3.1</commons.fileupload.version>
    <jackson.version>2.5.4</jackson.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.7.7</slf4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
      <type>jar</type>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis-spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons.fileupload.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp-api.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.connector.version}</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
  </dependencies>

12. Add Tomcat
IDEA configuration Tomcat [click]

xml file configuration

applicationContext.xml (Spring core configuration 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

">

    <!--    Scan annotation package-->
    <context:component-scan base-package="com.ChenZhiHui.Mapper"></context:component-scan>
    <context:component-scan base-package="com.ChenZhiHui.Service"></context:component-scan>

    <!-- Read database configuration file -->
    <context:property-placeholder location="classpath:db.MySQL.properties"/>

    <!-- JNDI Get data source(use dbcp Connection pool) -->
    <bean id="dataSource"
          class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" scope="singleton">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />

        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--Mapper Scanner-->
    <!--He can give it automatically Mapper The interface under generates a lowercase object-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ChenZhiHui.Mapper"/>
    </bean>

    <!-- to configure mybitas SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>


</beans>

db.MySQL.properties (database configuration file)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/company?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root

mybatis-config.xml (MyBatis core configuration 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>
    <!--Log output-->
    <settings>
        <setting name="logImpl" value="stdout_logging" />
    </settings>
    <!--alias-->
    <typeAliases>
        <package name="com.ChenZhiHui"/>
    </typeAliases>

</configuration>

springmvc-servlet.xml (spring MVC core configuration 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:mvc="http://www.springframework.org/schema/mvc"
       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <!--	Support annotation-->
        <mvc:annotation-driven></mvc:annotation-driven>

        <!--	
        Scan annotation package, point to Controller package
		Example: base-package="com.XXX.Controller
		-->
        <context:component-scan base-package="com.ChenZhiHui.Controller"></context:component-scan>

        <!--    Load static resources-->
        <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <filter>
    <filter-name>encoding</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>

<!--Load filter-->
  <filter>
    <filter-name>my</filter-name>
    <filter-class>com.ChenZhiHui.Filter.FirstFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>my</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

<!--Default load page-->
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

</web-app>

companyMapper.xml (Mapper core configuration 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">
<!--namespace point Mapper Layer interface-->
<mapper namespace="com.ChenZhiHui.Mapper.companyMapper">

        <!--Create a Map aggregate-->
        <resultMap id="dologinMap" type="companyPage">
            <id column="cid" property="cid"></id>
            <result column="cnumber" property="cnumber"></result>
            <result column="cpwd" property="cpwd"></result>
            <result column="cname" property="cname"></result>
            <result column="iid" property="iid"></result>
            <association property="identityPage" javaType="com.ChenZhiHui.Page.identityPage">
                <id column="iid" property="iid"></id>
                <result column="iidentity" property="iidentity"></result>
            </association>
        </resultMap>

<!--Sign in SQL-->
    <select id="dologin" resultMap="dologinMap" parameterType="companyPage">
        SELECT * FROM company WHERE cnumber=#{cnumber} AND cpwd=#{cpwd}
    </select>
<!--Home page query SQL-->
    <select id="pageSelect" resultMap="dologinMap">
        SELECT * FROM company AS c,identity AS i WHERE c.iid=i.iid AND c.cname LIKE CONCAT('%',#{text},'%') AND c.iid=i.iid
        <if test="uid!=-1">
            AND c.iid=#{uid}
        </if>
        LIMIT #{index},#{sum}
    </select>
<!--Home page deletion SQL-->
    <delete id="pageDelete" parameterType="int">
        DELETE FROM company WHERE cid=#{cid}
    </delete>
<!--Total query pages SQL-->
    <select id="pageNumber" resultType="int">
        SELECT COUNT(0) FROM company
    </select>
<!--Home page modification SQL-->
    <update id="pageUpdate" parameterType="companyPage">
        UPDATE company SET cpwd=#{cpwd},cname=#{cname},iid=#{iid} WHERE cid=#{cid}
    </update>
<!--Registered user SQL-->
    <insert id="logon" parameterType="companyPage">
        INSERT INTO company(cnumber,cpwd,cname,iid) VALUES (#{cnumber},#{cpwd},#{cname},0)
    </insert>
</mapper>

3, Codes of various classes

companyController (Controller class)

package com.ChenZhiHui.Controller;

import com.ChenZhiHui.Page.companyPage;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.ChenZhiHui.Service.companyService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class companyController {

    @Autowired
    companyService companyService;

    /**
     * Sign in
     * @param companyPage
     * @param request
     * @return
     */
    @RequestMapping(value="/dologin")
    public String doLogin(companyPage companyPage, HttpServletRequest request){
        companyPage companyPage1=companyService.dologin(companyPage);
        if(companyPage1!=null){
            request.getSession().setAttribute("cid",companyPage1.getCid());
            request.getSession().setAttribute("cnumber",companyPage1.getCnumber());
            request.getSession().setAttribute("cpwd",companyPage1.getCpwd());
            request.getSession().setAttribute("cname",companyPage1.getCname());
            request.getSession().setAttribute("iid",companyPage1.getIdentityPage().getIid());
            if(companyPage1.getIdentityPage().getIid()==1){
                return "redirect:page.jsp?cidentity=1";
            }else{
                return "redirect:page.jsp?cidentity=0";
            }
        }else {
            return "redirect:login.jsp?cidentity=-1";
        }
    }

    /**
     * Total query pages
     * @param sum
     * @return
     */
    @RequestMapping("/pageNumber")
    @ResponseBody
    public String pageNumber(int sum){
        String str=null;
        System.out.println("sum="+sum);
            int count=companyService.pageNumber();
            count=count%sum==0?count/sum:count/sum+1;
            str= JSON.toJSONString(count);
            return str;
    }

    /**
     * Home page query
     * produces = "text/plain;charset=utf-8": Set code
     * @param index
     * @param sum
     * @param text
     * @param uid
     * @return
     */
    @RequestMapping(value = "/pageSelect",produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String pageSelect(int index,int sum,String text,int uid){
        List<companyPage> companyList=companyService.pageSelect(index,sum,text,uid);
        String str=JSON.toJSONString(companyList);
        return str;
    }

    /**
     * Home page deletion
     * @param cid
     * @return
     */
    @RequestMapping("/pageDelete")
    @ResponseBody
    public String pageDelete(int cid){
        System.out.println(cid);
        int count=companyService.pageDelete(cid);
        String str=JSON.toJSONString(count);
        System.out.println("str="+str);
        return str;
    }

    /**
     * Home page modification
     * produces = "text/plain;charset=utf-8": Set code
     * @param companyPage
     * @return
     */
    @RequestMapping(value = "/pageUpdate",produces = "text/plain;charset=utf-8")
    public String pageUpdate(companyPage companyPage){
        int count=companyService.pageUpdate(companyPage);
        return "page.jsp";
    }

    /**
     * register
     * produces = "text/plain;charset=utf-8": Set code
     * @param companyPage
     * @param request
     * @return
     */
    @RequestMapping( value = "/logon",produces = "text/plain;charset=utf-8")
    public String logon(companyPage companyPage,HttpServletRequest request){
        request.getSession().setAttribute("cnumber",companyPage.getCnumber());
        int count=companyService.logon(companyPage);
        return "redirect:page.jsp";
    }
}

FirstFilter

package com.ChenZhiHui.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FirstFilter implements Filter {
    //Initialization of filter
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String url=request.getRequestURI();
        //It is allowed to load pages with login and logon, and * js static resource loading
        if(request.getSession().getAttribute("cnumber")!=null || url.contains("login") || url.contains("logon") || url.contains("*.js")) {
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //Return to login
            response.sendRedirect("login.jsp");
        }
    }

    //Filter destruction
    public void destroy() {

    }
}

companyMapper (Mapper interface)

package com.ChenZhiHui.Mapper;

import com.ChenZhiHui.Page.companyPage;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface companyMapper {
    companyPage dologin(companyPage companyPage);       //Sign in
    int pageNumber();           //Total number of queries
    //index current number of pages, sum displays several pieces of information, text query name, uid query all / employees / administrators (- 1 = query all, 0 = query employees, 1 = query administrators)
    List<companyPage> pageSelect(@Param("index") int index, @Param("sum") int sum, @Param("text") String text,@Param("uid") int uid);         //Query all employees
    int pageDelete(@Param("cid") int cid);        //delete
    int pageUpdate(companyPage companyPage);    //modify
    int logon(companyPage companyPage);    //register
}

companyPage (employee Page entity class)

package com.ChenZhiHui.Page;

public class companyPage {
    private Integer cid;        //Serial number
    private String cnumber;     //account number
    private String cpwd;        //password
    private String cname;       //full name
    private Integer iid;  //identity
    private identityPage identityPage;      //Identity class object

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCnumber() {
        return cnumber;
    }

    public void setCnumber(String cnumber) {
        this.cnumber = cnumber;
    }

    public String getCpwd() {
        return cpwd;
    }

    public void setCpwd(String cpwd) {
        this.cpwd = cpwd;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public Integer getIid() {
        return iid;
    }

    public void setIid(Integer iid) {
        this.iid = iid;
    }

    public com.ChenZhiHui.Page.identityPage getIdentityPage() {
        return identityPage;
    }

    public void setIdentityPage(com.ChenZhiHui.Page.identityPage identityPage) {
        this.identityPage = identityPage;
    }
}

identityPage (person identity Page entity class)

package com.ChenZhiHui.Page;

import java.util.List;

public class identityPage {
    private Integer iid;        //Serial number
    private String iidentity;  //identity
    private List<companyPage> companyPageList;      //Employee class collection

    public Integer getIid() {
        return iid;
    }

    public void setIid(Integer iid) {
        this.iid = iid;
    }

    public String getIidentity() {
        return iidentity;
    }

    public void setIidentity(String iidentity) {
        this.iidentity = iidentity;
    }

    public List<companyPage> getCompanyPageList() {
        return companyPageList;
    }

    public void setCompanyPageList(List<companyPage> companyPageList) {
        this.companyPageList = companyPageList;
    }
}

companyServiceImpl (Service interface implementation class)

package com.ChenZhiHui.Service.Impl;

import com.ChenZhiHui.Page.companyPage;
import com.ChenZhiHui.Service.companyService;
import org.springframework.beans.factory.annotation.Autowired;
import com.ChenZhiHui.Mapper.companyMapper;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class companyServiceImpl implements companyService {

    @Autowired
    companyMapper companyMapper;

    //Sign in
    public companyPage dologin(companyPage companyPage) {
        return companyMapper.dologin(companyPage);
    }

    //Total number of queries
    public int pageNumber() {

        return companyMapper.pageNumber();
    }

    //Query all employees
    public List<companyPage> pageSelect(int index, int sum, String text,int uid) {

        return companyMapper.pageSelect(index,sum,text,uid);
    }

    //delete
    public int pageDelete(int cid) {

        return companyMapper.pageDelete(cid);
    }

    //modify
    public int pageUpdate(companyPage companyPage) {

        return companyMapper.pageUpdate(companyPage);
    }

    //register
    public int logon(companyPage companyPage) {
        return companyMapper.logon(companyPage);
    }
}

companyService (Service interface)

package com.ChenZhiHui.Service;

import com.ChenZhiHui.Page.companyPage;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.List;


public interface companyService {
    companyPage dologin(companyPage companyPage);       //Sign in
    int pageNumber();           //Total number of queries
    List<companyPage> pageSelect(int index,int sum,String text,int uid);     //Query all employees
    int pageDelete(int cid);        //delete
    int pageUpdate(companyPage companyPage);    //modify
    int logon(companyPage companyPage);    //register
}

login.jsp (login page)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<h2>Hello World!</h2>
<form action="dologin" method="post">
    account number:<input type="text" name="cnumber">
    password:<input type="text" name="cpwd">
    <input type="submit" value="Sign in">
    <input type="button" onclick="logon();" value="register">
</form>
</body>
</html>
<script type="text/javascript">
    var iidentity=0;        //Login results
    $(function (){
        //Get the first value after the "=" sign,
        iidentity=window.location.href.split("=")[1];
        login();
    });
    //Go to the registration page
    function logon(){
        window.location.href="logon.jsp";
    }
    //Return login results
    function login(){
        if(iidentity==-1){
            alert("Wrong account or password!");
        }
    }
</script>

logon.jsp (registration page)

<%@ page pageEncoding="utf-8" %>
<html>
<head>
    <title>register</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<h2>User registration</h2>
<form action="logon" method="post">
    account number:<input type="text" name="cnumber" placeholder="cell-phone number/mailbox"/></br>
    password:<input type="text" name="cpwd"/></br>
    full name:<input type="text" name="cname"/>
    </br>
    <input type="submit" value="register"><input type="button" id="goBack" value="Return to login">
</form>
</body>
</html>
<script type="text/javascript">
    $(function (){
        $("input[name='cnumber']").focus();        //Get focus automatically
    });
</script>

page.jsp (home page)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home page</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<input type="text" id="text" name="select" placeholder="Please enter the name you want to find">&nbsp;&nbsp;<input type="radio" name="identity" value="-1" checked="true">whole&nbsp;&nbsp;<input type="radio" name="identity" value="0">staff&nbsp;&nbsp;<input type="radio" name="identity" value="1">administrators<input type="button" onclick="pageSelect()" value="query"/>
<table border="1" id="showSelect">
    <tr><td>Serial number</td><td>account number</td><td>password</td><td>full name</td><td>identity</td><td colspan="2">operation</td></tr>
</table>
<div id="counter">
    <button id="shouye" type="button" onclick="shouye()">home page</button>
    <button id="shangyiye" type="button" onclick="shangyiye()">previous page</button>
    <button id="xiayiye" type="button" onclick="xiayiye()">next page</button>
    <button id="weiye" type="button" onclick="weiye()">Last page</button>
    <b id="number">the number of pages: x/y</b>
</div>
<form id="modification" action="pageUpdate" method="post">
    Serial number:<input type="text" name="cid" readonly="readonly"/>
    account number:<input type="text" name="cnumber" readonly="readonly"/>
    password:<input type="text" name="cpwd">
    full name:<input type="text" name="cname">
    Identity:<input type="radio" name="iid" value="0">staff&nbsp;&nbsp;<input type="radio" name="iid" value="1">administrators
    <input type="submit" onsubmit="pageSubmit()" value="preservation">
</form>
</body>
</html>
<script type="text/javascript">
    var iidentity=0;    //identity
    var index=1;        //Current number of pages
    var sum=4;          //Display rows
    var count=0;        //Total number of rows
    var uid=-1;         //Query by identity- 1 = all, 0 = employees, 1 = administrators

    $(function (){
        //Get identity
        iidentity=window.location.href.split("=")[1];
        //Page load hide modify box
        $("#modification").hide();
        //Query total pages and update page numbers
        pageNumber();
        //Query all personnel
        pageSelect();
    });
    //Save changes auto hide changes box
    function pageSubmit(){
        $("#modification").hide();
    }

    //Home page query
    function pageSelect(){
        //Get identity
        var a=document.getElementsByName("identity");
        for(var i=0;i<a.length;i++){
            if(a[i].checked){
               uid=a[i].value;
            }
        }
        //Update pages
        pageNumber();
        var text=$("#text").val();
        $("table tr:gt(0)").remove();
        // alert((index-1)*sum+":"+text+":"+uid);
        $.post("pageSelect",{"index":(index-1)*sum,"sum":sum,"text":text,"uid":uid},function (data){
            if(data!=""){
            var str="<tr>";
                for (var i=0;i<data.length;i++) {
                    str += "<td>"+data[i].cid+"</td><td>"+data[i].cnumber+"</td><td>"+data[i].cpwd+"</td><td>"+data[i].cname+"</td><td>"+data[i].identityPage.iidentity+"<td>";
                    if (iidentity==0) {
                        str += "<input type='button' disabled='disabled' value='delete'/><input type='button' disabled='disabled' value='modify'/>";
                    } else {
                        str += "<input type='button' οnclick='pageDelete(" + data[i].cid + ");' value='delete'/>" +
                            "<input type='button' οnclick='pageUpdate("+data[i].cid+",\""+data[i].cnumber+"\","+data[i].cpwd+",\""+data[i].cname+"\","+data[i].iid+");' value='modify'/>";
                    }
                    str+="</td></tr>";
                }
                $("#showSelect").append($(str));
            }else{
                index--;
                if(index<1){
                    index=1;
                }
                //Continued investigation
                pageSelect();
            }
        },"JSON");
    }
    //Modification method
    function pageUpdate(cid,cnumber,cpwd,cname,iid){
        $("#modification").show();
        alert(cid+":"+cnumber+":"+cpwd+":"+cname+":"+iid);
        $("input[name='cid']").val(cid);
        $("input[name='cnumber']").val(cnumber);
        $("input[name='cpwd']").val(cpwd);
        $("input[name='cname']").val(cname);
        $("#modification input[type='radio']").eq(iid).prop("checked",true);
    }
    //Delete method
    function pageDelete(cid){
        $.post("pageDelete",{"cid":cid},function (data){
            console.log(data);
            if(data>0){
                console.log("Delete succeeded!");
                pageSelect();
            }else{
                console.log("Deletion failed!");
            }
        },"JSON");
    }
    //home page
    function shouye(){
        index=1;
        pageSelect();
    }
    //previous page
    function shangyiye(){
        index--;
        if(index<1){
            index=1;
        }
        pageSelect();
    }
    //next page
    function xiayiye(){
        index++;
        if(index>count){
            index=count;
        }
        pageSelect();
    }
    //Last page
    function weiye(){
        index=count;
        pageSelect();
    }
    //Update pages
    function pageNumber(){
        $.post("pageNumber",{"sum":sum},function(data){
            count=data;
            $("#number").empty();
            var str="the number of pages:"+index+"/"+count;
            $("#number").append(str);
        },"JSON");
    }
</script>

Keywords: Java Javascript JQuery Spring Back-end

Added by hammerslane on Sat, 29 Jan 2022 20:33:39 +0200