Set up the ssm framework to realize login, data display, addition, deletion, modification and query

Keywords: Java xml Mybatis Spring

Requirements:

Use ssm (spring spring MVC mybatis) for integration in the background

Using bootstrap framework in the foreground

Using Ajax to send between front and back

Table structure:

 

After login, all user information will be displayed, and each can be added, deleted, modified and checked

The user name and user PWD of this table are also used for verification when logging in

Project directory structure

 

Step 1: build the framework and test

applicationContext.xml: spring configuration file, including spring and mybatis integration

mybatis.xml: mybatis configuration file

springmvcServlet-servlet.xml: springMVC configuration file

1. Create a new context package in the src directory to store configuration files

2. Configure web.xml

3. Import the required jar package

Because junit test, pageHelper and other components will also be used in this project, some jar packages are not necessary when building the framework. You can ask Du nianha about the necessary jar packages

   

Write web.xml

The comments in the code are complete. Here you can post the code directly. If there is something you can't understand, you can leave a message or private letter

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssm-dynamic</display-name>
  <!-- start-up spring container -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <!-- Exists at root springContext.xml file -->
      <param-value>classpath*:contexts/applicationContext.xml</param-value>  
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  </listener>
  
  <!-- To configure log4j -->
  <context-param>  
      <param-name>log4jConfigLocation</param-name>   
      <param-value>WEB-INF/classes/contexts/log4j.properties</param-value>   
  </context-param>  
  <context-param>   
      <param-name>log4jRefreshInterval</param-name>   
      <param-value>60000</param-value>   
  </context-param>   
  <!-- Need to add spring-web.jar package -->  
  <listener>   
      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
  </listener> 
  
  <!-- To configure springmvc Front end controller -->
  <servlet>
      <!-- Lie in web.xml Exists in the same level directory springmvcServlet-servlet.xml file -->
    <servlet-name>springmvcServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:contexts/springmvcServlet-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvcServlet</servlet-name>
      <!-- Block all requests -->
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- Character encoding filter,Be sure to put it before all filters -->
  <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>
      <init-param>
          <param-name>forceRequestEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
      <init-param>
          <param-name>forceResponseEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- Use Rest Style URI,Make the page normal post Request to specified delete perhaps put request -->
  <filter>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p" 
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.1.xsd
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"
       default-lazy-init="true">
    <!-- spring Configuration files, which are related to business logic -->
    <context:component-scan base-package="com.huaxin">
        <!-- Do not scan controller -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- Import external profile -->
    <context:property-placeholder location="classpath:contexts/jdbc.properties"/>
    <!-- ======Data source configuration start====== -->
    <bean id = "dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">  
        <property name="driverClassName" value="${jdbc.driver}" />  
        <property name="jdbcUrl" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
        <property name="maximumPoolSize" value="${jdbc.maximumPoolSize}" />  
        <property name="minimumIdle" value="${jdbc.minimumIdle}" />  
        <property name="connectionTestQuery" value="${jdbc.connectionTestQuery}" />  
        <property name="dataSourceProperties">  
            <props>  
                <prop key="cachePrepStmts">${jdbc.cachePrepStmts}</prop>  
                <prop key="prepStmtCacheSize">${jdbc.prepStmtCacheSize}</prop>  
                <prop key="prepStmtCacheSqlLimit">${jdbc.prepStmtCacheSqlLimit}</prop>  
                <prop key="useServerPrepStmts">${jdbc.useServerPrepStmts}</prop>  
            </props>  
        </property>  
    </bean>
    <!-- ======End of data source configuration====== -->

    <!-- ======integration mybatis start====== -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Appoint mybatis Global profile location -->
        <property name="configLocation" value="classpath:contexts/mybatis.xml"></property>
        <!-- specify data source -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- Appoint mybatis Of mapper Location of files -->
        <property name="mapperLocations" value="classpath:com/huaxin/mapping/*.xml"></property>
    </bean>
    <!-- Configure the scanner to mybatis Interface implementation added to ioc In container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- Scan all dao Interface implementation, adding to ioc In container -->
        <property name="basePackage" value="com.huaxin.dao"></property>
    </bean>
    <!-- ======integration mybatis End====== -->
    
    <!-- ======Configure executable batch sqlSession start====== -->
    <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate.class">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
        <constructor-arg name="executorType" value="BATCH"></constructor-arg>
    </bean> -->
    <!-- ======Configure executable batch sqlSession End====== -->
    
    <!-- ======The configuration of things control begins====== -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Control data source -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- Open annotation based things, using xml Things in configuration form (mainly using configuration form) -->
    </bean>
    <aop:config>
        <!-- Pointcut expression
        *[return type]+Blank space+Need to control things+
        ..[Two points indicate that its subpackages can also be]+*[Method]+(..)[Two points represent any number of parameters] -->
        <aop:pointcut expression="execution(* com.huaxin.service..*(..))" id="txPoint"/>
        <!-- Configuration enhancements -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
    <!-- How to cut things in -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- *Means that all methods are methods of things -->
            <tx:method name="*"/>
            <!-- with get All ways to start,Think it's all query methods, and tune them -->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- ======End of configuration of object control====== -->
    <!-- Spring The core point of the profile (data source, and mybatis Integration and control of things) -->
</beans>

springmvcServlet-servlet.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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p" 
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.1.xsd
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"
       default-lazy-init="true">
    <!-- springmvc Configuration file, including control of website jump logic, configuration -->
    <context:component-scan base-package="com.huaxin" use-default-filters="false">
        <!-- Scan controller only -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- Configure view parser to facilitate page return -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- Two standard configurations -->
    <!-- take springmvc Unprocessable requests to tomcat -->
    <mvc:default-servlet-handler/>
    <!-- Able to support springmvc More advanced features, JSR303 Verification, fast Ajax Wait, map dynamic requests -->
    <mvc:annotation-driven/>
</beans>

mybatis.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>
    <!-- Configure hump naming rules -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
    <!-- Configuration type alias -->
    <typeAliases>
        <package name="com.huaxin.bean"/>
    </typeAliases>
    
    <!-- Configure paging queries -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 3.3.0 Version available - Rationalization of paging parameters, default false Prohibit -->
            <!-- When rationalization is enabled, if pageNum<1 The first page will be queried if pageNum>pages The last page will be queried -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

Using mybatis reverse engineering to generate bean s, dao and mapping

Configure mbg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
  <context id="DB2Tables" targetRuntime="MyBatis3">
      <!-- Configure whether to generate comments -->
      <commentGenerator>
          <property name="suppressAllComments" value="true" />
    </commentGenerator>
      <!-- Configure database connection information -->
    <jdbcConnection 
        driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://127.0.0.1:3306/test"
        userId="root"
        password="1234">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- Appoint JavaBean Build location -->
    <javaModelGenerator 
        targetPackage="com.huaxin.bean" 
        targetProject=".\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    
    <!-- Appoint sql Location of map file generation -->
    <sqlMapGenerator 
        targetPackage="com.huaxin.mapping"  
        targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- Appoint dao Where the interface is generated, mapper Location of interface generation -->
    <javaClientGenerator 
        type="XMLMAPPER" 
        targetPackage="com.huaxin.dao"  
        targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- Specify the build policy for each table, enable***Indicates no build example surface -->
    <table tableName="user" domainObjectName="User" enableCountByExample="false"
        enableUpdateByExample="false" enableDeleteByExample="false" 
        enableSelectByExample="false" selectByExampleQueryId="false"></table>
  </context>
</generatorConfiguration>

Write build class

package com.huaxin.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MBGTest {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("Code generated successfully");
    }
}

Refresh the project after execution to see the generated code

Test whether the dao layer and basic configuration of the project are successful

Write test class MapperTest.java

package com.huaxin.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.huaxin.bean.User;
import com.huaxin.dao.UserMapper;

/**
 * Test dao layer
 * @author ws
 * Spring The project can use spring's unit test to automatically inject the components we need
 * 1.Import spring test module spring-test-4.1.7.RELEASE.jar
 * 2.@ContextConfiguration Specify profile location
 *   @RunWith(SpringJUnit4ClassRunner.class)Specify unit tests using spring
 * 3.Directly use the components of autowired
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:contexts/applicationContext.xml"})
public class MapperTest {
    @Autowired
    UserMapper userMapper;
    
    /*@Autowired
    SqlSession sqlSession;*/

    public static void main(String[] args) {
        /*// 1.Create SpringIOC container
        ApplicationContext ioc = new ClassPathXmlApplicationContext("springContext.xml");
        // 2.Get mapper from container
        UserMapper bean = ioc.getBean(UserMapper.class);*/
    }
    
    
    @Test
    public void testC(){
        System.out.println(">>>>>>>>>>>>>>>>>>>>" + userMapper);
        User user = new User();
        user.setUserId("testCRUD3");
        user.setUserName("Bruce Lee");
        user.setUserPwd("qwer123");
        user.setAge(231);
        userMapper.insertSelective(user);
        /*for(int i = 0;i < 500;i++){
            String uid = UUID.randomUUID().toString().substring(0, 5);
            userMapper.insertSelective(new User(uid, uid, uid, i));
            System.out.println("Insert successfully! "";
        }*/
        System.out.println("Insert complete");
    }
    
    @Test
    public void testCs(){
        /*UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        for(int i = 0;i < 1000;i++){
            String uid = UUID.randomUUID().toString().substring(0, 5);
            String id = UUID.randomUUID().toString().substring(5,10);
            userMapper.insertSelective(new User(id, uid, uid, i));
        }*/
    }
}

Write login.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>Login page</title>
<!-- Get project name -->
<%
    pageContext.setAttribute("PATH", request.getContextPath());
%>

<!-- 
web Route
 Not to/Relative path at the beginning, find resources based on the current path (easy to cause problems)
with/Relative path to start, find resource to server path( http://localhost:8080)As standard,Need to add project name
 -->
<script type="text/javascript" src="${PATH}/static/jquery/jquery-1.12.4.min.js"></script>
<link href="${PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="${PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<%-- <link href="${PATH }/static/css/login.css" rel="stylesheet"> --%>

<style type="text/css">
.container{
   display:table;
   height:100%; 
}

.row{
   display: table-cell;
   vertical-align: middle;
}
</style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-2">
                <form action="login" method="post">
                      <div class="form-group">
                        <label>user name</label>
                        <input type="text" class="form-control input-sm" name="username">
                    </div>
                      <div class="form-group">
                        <label>Password</label>
                        <input type="password" class="form-control input-sm" name="password">
                    </div>
                      <div class="checkbox">
                        <label>
                          <input type="checkbox">Remember user name and password
                        </label>
                    </div>
                      <button type="submit" class="btn btn-default">Submission</button>
                    <div>${msg}</div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

LoginController.java

package com.huaxin.controller;

import javax.servlet.http.HttpServletRequest;
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 com.huaxin.bean.User;
import com.huaxin.dao.UserMapper;

@Controller
public class LoginController {
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * Jump to login page when visiting
     * @param model
     * @return
     */
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("msg", "");
        return "login";
    }
    
    @RequestMapping(value="/login")
    public String login(Model model, // Put the value passed to the front page model in
            HttpServletRequest request // Value from foreground page
            ){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean flag = LoginCheck(username, password);
        if(flag){
            return "uerList";
        }else{
            model.addAttribute("msg", "Incorrect user name or password, please login again");
            return "login";
        }
    }
    
    /**
     * Check whether the user name and password are correct
     * @param username
     * @param password
     * @return
     */
    private boolean LoginCheck(String username,String password){
        User user = userMapper.selectByUserName(username);
        if(user == null || "".equals(user)){
            return false;
        }
        if(user.getUserPwd().equals(password)){
            return true;
        }else{
            return false;
        }
    }
}

Here, the user mapper adds the information to query the record according to the username

sql is written in UserMapper.xml

<select id="selectByUserName" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from user
    where user_name = #{username,jdbcType=VARCHAR}
  </select>

Start the project, which uses Tomcat 7.0 and jdk1.8

Page rendering (ps: Currently, the page style has not been adjusted, but it is ugly. You can adjust it yourself, and remember the user name and password function has not been implemented)

 

Login succeeded, display user list information

uerList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- Import label Library -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>json Display page</title>
<!-- Get project name path -->
<%
    pageContext.setAttribute("PATH", request.getContextPath());
%>

<!-- 
web Route
 Not to/Relative path at the beginning, find resources based on the current path (easy to cause problems)
with/Relative path to start, find resource to server path( http://localhost:8080)As standard,Need to add project name
 -->
<script type="text/javascript" src="${PATH}/static/jquery/jquery-1.12.4.min.js"></script>
<link href="${PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="${PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="${PATH }/static/css/list.css" rel="stylesheet">
<script type="text/javascript" src="${PATH }/static/js/list.js"></script>

</head>
<body>
<%-- ${pageInfo } --%>
    <!-- Use bootstrap Grid system building display page -->
    <div class="container">
        <!-- Title -->
        <div class="row">
            <div class="col-sm-12">
                <h1>USER INFO</h1>
            </div>
        </div>
        <!-- Add delete button -->
        <div class="row">
            <!-- Use column offset -->
            <div class="col-sm-4 col-sm-offset-10">
                <!-- Use button style -->
                <button type="button" class="btn btn-primary btn-sm" id="userAddBtn">increase</button>
                <button type="button" class="btn btn-primary btn-sm" id="userDelBtn">delete</button>
            </div>
        </div>
        <!-- List information -->
        <div class="row">
            <div class="col-sm-12">
                <table class="table table-hover" id="user_table">
                    <thead>
                        <tr>
                            <th width="20%">id</th>
                            <th width="20%">user name</th>
                            <th width="20%">Password</th>
                            <th width="20%">Age</th>
                            <th width="20%">operation</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        <!-- paging -->
        <div class="row">
            <!-- Paging text messages -->
            <div class="col-sm-3" id="pageInfo_area"></div>
            <!-- Paging bar information -->
            <div class="col-sm-5 col-sm-offset-4" id="pageNav_area"></div>
        </div>
    </div>
    <!-- New mode box -->
    <div class="modal fade" id="userAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document" style="width: 35%">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h5 class="modal-title" id="myModalLabel">Newly added</h5>
          </div>
          <div class="modal-body">
            <form class="form-horizontal" id="userAddModalForm">
              <div class="form-group">
                <label class="col-sm-2 control-label">id</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" name="userId">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">user name</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" name="userName" placeholder="Email or mobile number">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">Password</label>
                <div class="col-sm-8">
                  <input type="password" class="form-control" name="userPwd" placeholder="Please input a password">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">Age</label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" name="age" placeholder="Please enter age">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btn-sm" id="userAddModalSaveBtn">Preservation</button>
          </div>
        </div>
      </div>
    </div>
</body>
</html>

Page style needs to be fine tuned

 list.css

td,th{
    text-align: center;
}
body{
    overflow:-Scroll;
    overflow-x:hidden;
}

Write UserController.java

package com.huaxin.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaxin.bean.Msg;
import com.huaxin.bean.User;
import com.huaxin.logic.UserLogic;

@Controller
public class UserController {
    
    @Autowired
    private UserLogic userLogic;
    
    /**
     * Get user information by paging
     * @ResponseBody jackson package needs to be imported
     * @param pn
     * @return
     */
    @RequestMapping(value="/user",method=RequestMethod.GET)
    @ResponseBody
    public Msg getUser(
            @RequestParam(value="pn",defaultValue="1")Integer pn){// Paging parameters
        
        /* Configure paging queries
        ** Introduce PageHelper paging plug-in, namely pagehelper-5.1.2.jar and jsqlparser-0.9.1.jar
        ** mybatis.xml Configure paging in
        ** Call PageHelper.startPage(pageNum, pageSize);
        **/
        PageHelper.startPage(pn, 7);
        // startPage The next query is paging query
        List<User> list = userLogic.getUserList();
        // Use pageInfo Result set after wrapping query,Encapsulate detailed paging information,5 5 consecutive pages
        PageInfo pageInfo = new PageInfo(list,5);
        return Msg.success().add("pageInfo",pageInfo);
    }
    
    @RequestMapping(value="/user",method=RequestMethod.POST)
    @ResponseBody
    public Msg addUser(User user){
        userLogic.addUser(user);
        return Msg.success();
    }
}

Add the selectAll method in usermapper to query all user information

The sql is as follows

<select id="selectAll" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from user
  </select>

The logic package is actually the service layer

The UserLogic.java code is as follows

package com.huaxin.logic;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.huaxin.bean.User;
import com.huaxin.dao.UserMapper;

@Service
public class UserLogic {
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * Query user list (pagination query)
     * @return
     */
    public List<User> getUserList(){
        return userMapper.selectAll();
    }

    /**
     * New user
     * @param user
     */
    public void addUser(User user) {
        // id For auto generated uuid
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        user.setUserId(uid);
        userMapper.insertSelective(user);
    }
}

Because the front and back stage use ajax for submission

Write list.js

var basePath = getRootPath();
$(function () {
    // After the page is loaded, send it directly ajax Request, to paging data
    doQuery(1);
    // Bind button to event
    bindEvent();
});
// Query method
function doQuery(pn) {
    $.ajax({
        url:basePath + "/user",
        data:"pn=" + pn,
        type:"GET",
        success:function(result){
            //console.log(result);
            // Analyze and display employee data
            build_user_table(result);
            // Parse and display paging information
            build_page_info(result);
            // Parse and display the paging bar
            build_page_nav(result);
        }
    });
}
//New method
function doAdd(formData){
    alert(formData);
    $.ajax({
        url:basePath + "/user",
        data:formData,
        type:"POST",
        success:function(result){
            console.log(result);
        }
    });
}


// Analyze and display employee data
function build_user_table(result) {
    // Empty table
    $("#user_table tbody").empty();
    var users = result.data.pageInfo.list;
    $.each(users,function(index,item){
        var userIdTd = $("<td></td>").append(item.userId);
        var userNameTd = $("<td></td>").append(item.userName);
        var passwordTd = $("<td></td>").append(item.userPwd);
        var ageTd = $("<td></td>").append(item.age);
        var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm")
                                .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
                                .append("edit");
        var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm")
                                .append($("<span></span>").addClass("glyphicon glyphicon-remove"))
                                .append("delete");
        var operate = $("<td></td>").append(editBtn).append("&nbsp;").append(delBtn);
        $("<tr></tr>").append(userIdTd)
                    .append(userNameTd)
                    .append(passwordTd)
                    .append(ageTd)
                    .append(operate)
                    .appendTo("#user_table tbody");
    });
}

// Parse and display paging information
function build_page_info(result){
    // empty
    $("#pageInfo_area").empty();
    $("#pageInfo_area").append("Current"+ result.data.pageInfo.pageNum 
            +"page,common"+ result.data.pageInfo.pages +"page,"
            + result.data.pageInfo.total +"Records");
}


// Parse and display the paging bar
function build_page_nav(result) {
    // empty
    $("#pageNav_area").empty();
    // nav
    var pageNav = $("<nav></nav>").attr("aria-label","Page navigation");
    // ul
    var pageUl = $("<ul></ul>").addClass("pagination");
    // home page
    var firstPageLi = $("<li></li>").append($("<a></a>").append("home page").attr("href","#"));
    // next page before
    var previousPageLi = $("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#"));
    
    // If there is no previous page, the first page and the previous page are set as non clickable
    if(!result.data.pageInfo.hasPreviousPage){
        firstPageLi.addClass("disabled");
        previousPageLi.addClass("disabled");
    }else{
        // Send when clicked ajax Request, get current page data
        firstPageLi.click(function(){
            doQuery(1);
        });
        previousPageLi.click(function(){
            doQuery(result.data.pageInfo.pageNum - 1);
        });
    }
    
    // Add home and previous page to ul In label
    pageUl.append(firstPageLi).append(previousPageLi);
    // Traverse to get the middle page number
    $.each(result.data.pageInfo.navigatepageNums,function(index,item){
        var numsLi = $("<li></li>").append($("<a></a>").append(item).attr("href","#"));
        // Set the page to highlight
        if(result.data.pageInfo.pageNum == item){
            numsLi.addClass("active");
        }
        // Send when clicked ajax Request, get current page data
        numsLi.click(function(){
            doQuery(item);
        });
        // Put each li Page add to ul In label
        pageUl.append(numsLi);
    })
    // Next page
    var NextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#"));
    // Last
    var lastPageLi = $("<li></li>").append($("<a></a>").append("Last").attr("href","#"));
    // If there is no next page, the last page and the next page are set as non clickable
    if(!result.data.pageInfo.hasNextPage){
        NextPageLi.addClass("disabled");
        lastPageLi.addClass("disabled");
    }else{
        // Send when clicked ajax Request, get current page data
        NextPageLi.click(function(){
            doQuery(result.data.pageInfo.pageNum + 1);
        });
        lastPageLi.click(function(){
            doQuery(result.data.pageInfo.pages);
        });
    }
    
    // Add next and last page to ul In label
    pageUl.append(NextPageLi).append(lastPageLi);
    // take ul Tag to nav In label
    pageNav.append(pageUl);
    // take nav Label added to specified div in
    $("#pageNav_area").append(pageNav);
}

//Get the project root path, such as: http://localhost:8083/ssm-dynamic
function getRootPath(){
    //Get the current web address, such as: http://localhost:8083/ssm-dynamic/jsp/jsonList.jsp
    var curWwwPath=window.document.location.href;
    //Obtain the directory after the host address, such as: ssm-dynamic/jsp/jsonList.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //Obtain the host address, such as: http://localhost:8080
    var localhostPaht=curWwwPath.substring(0,pos);
    //Acquisition band"/"Project name of, such as:/ssm-dynamic
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}

//Bind button to event
function bindEvent(){
    //Bind new button click Event
    $("#userAddBtn").click(function(){
        $("#userAddModal").modal({
            // Click the background mode box not to close
            backdrop:"static"
        });
    })
    //Button binding will be removed click Event
    $("#userDelBtn").click(function(){
        $("#userDelModal").modal({
            
        });
    });
    //Save button binding click Event
    $("#userAddModalSaveBtn").click(function(){
        // Get data entered on the page
        var formData = $("#userAddModalForm").serialize();
        // Execute new method
        //doAdd(formData);
        alert(formData);
        $.ajax({
            url:basePath + "/user",
            data:$("#userAddModalForm").serialize(),
            type:"POST",
            success:function(result){
                alert(0);
            }
        });
    });
}

Start the project, now the list and new users can be displayed

The effect is as follows

Click the new button rendering

 

Current project progress (January 4, 2018):

Sign in:

Function not implemented: save user name and password, page style

Display page (pagination query): completed

Add: only click Save to insert into the database, and the details are not processed (Click Save to close the pop-up window, id is set to hide, page length and content check, etc.)

Edit and delete incomplete

Posted by esmarts on Thu, 30 Apr 2020 11:55:03 -0700