Click a thumbs-up if you like! GitHub project SSM-Learning-CRM show me the code and take to me

1.1 the cloning

git clone https://github.com/buerbl/ssm-learn-crm.git
Copy the code

Results 1. 2

2 Analyzing Requirements

We need to make a customer system, users can save, edit, delete, customer information in the system.

3 Technology selection

This time, we choose SSM three frameworks to build the back end of the system. JSP and JQuery EasyUI are used for the front end page. Database using MySQL; The project concept uses Maven tools.

technology role
Spring Manage objects, manage transactions, etc
SpringMVC Path jump, request access, etc
Mybatis Data acquisition, etc.
JQuery EasyUI Page display, etc.
MySQL Access data, etc.
IDEA Write code quickly, etc
Navicat Database visualization software

4 the database

We need to save the customer’s name, gender, contact information, and address, so our database script is as follows

CREATE table t_customer(
	id int PRIMARY KEY auto_increment,
	name VARCHAR(20),
	gender char(1),
	telephone VARCHAR(20),
	address VARCHAR(50));Copy the code

5 Maven management

5.1 the jar package

Import the JAR we need once, depending on the following

 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.3. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.12</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>server</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>server</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>server</version>
        </dependency>
    </dependencies>
Copy the code

5.2 Compilation Problems

Maybe when we compile, we find that the webApp file is not compiled. We need to add the following to pom.xml to tell Mavne that we need to compile the specific file.

<build>
   <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
Copy the code

6 Hierarchy

When we get here, we need to set up a folder and get ready to start writing code. Generally speaking, I like the following rules

folder role
controller Control layer code
domain Entity class code
dao Mapper code
service Service layer code

7 Entity class code

We coded the entity class based on the database fields as follows. I used the Lombok framework, which required IDEA to install a Lombok plug-in.

package com.buer.domain;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/ * * *@Description:
 * @Author: boolean
 * @Date: 2019/12/22 11:51 * /

@Getter
@Setter
@ToString

@AllArgsConstructor
public class Customer {
    private  Integer id;
    private String name;
    private String gender;
    private String telephone;
    private String address;
}
Copy the code

Question: How do these fields correspond to database fields one by one? Here we go.

8 Mapper code

Here we need Mybatis to play, first we need the following Mapper code

package com.buer.dao;

import com.buer.domain.Customer;

import java.util.List;

public interface CustomerMapper {
    /** * Add client */
    void saveCustomer(Customer customer);

    /** * query all customers *@return* /
    List<Customer> list(a);

    /*** * Find a customer *@param id
     * @return* /
    Customer findById(Integer id);
}
Copy the code

9 XML file of Mapper

With the Mapper code, we need to match the Mapper with the appropriate XML file. The following

<?xml version="1.0" encoding="UTF-8" ? >

      
<! Mybatis = mapper; mybatis = mapper; mybatis = mapper; mybatis = mapper
<mapper namespace="com.buer.dao.CustomerMapper">

    <! -- Add client -->
    <insert id="saveCustomer" parameterType="com.buer.domain.Customer">
		INSERT INTO ssm.t_customer
			(
			NAME,
			gender,
			telephone,
			address
			)
			VALUES
			(
			#{name},
			#{gender},
			#{telephone},
			#{address}
			)
	</insert>

	<select id="list" resultType="com.buer.domain.Customer">
		select * from t_customer
	</select>

	<select id="findById" resultType="com.buer.domain.Customer">
		select * from t_customer where id = #{id}
	</select>
</mapper>
Copy the code

To answer the above question, how does the entity class field correspond to the database field one by one, using the resultType to automatically map.

10 Service layer code

Let’s start with the interface layer code. The following code

package com.buer.service;

import com.buer.domain.Customer;

import java.util.List;

public interface IcustomerService {
    /** * Add client */
    void saveCustomer(Customer customer);

    /** * returns all data *@return* /
    List<Customer> list(a);

    /** * Modify data *@return* /
    Customer findById(Integer id);
}

Copy the code

Then implement the interface as follows

package com.buer.service.Impl;

import com.buer.dao.CustomerMapper;
import com.buer.domain.Customer;
import com.buer.service.IcustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/ * * *@Description:
 * @Author: boolean
 * @Date: 2019/12/22 and * /
@Service("customerService")
public class IcustomerServiceImpl implements IcustomerService {
    @Resource
    private CustomerMapper customerMapper;
    @Override
    @Transactional
    public void saveCustomer(Customer customer) {
        customerMapper.saveCustomer(customer);
    }

    @Override
    public List<Customer> list(a) {
        return customerMapper.list();
    }

    @Override
    public Customer findById(Integer id) {
        returncustomerMapper.findById(id); }}Copy the code

Transactional annotations @service (“customerService”),@Resource, @Transactional annotations what do they do? Please see the following

annotations role
@Service(“customerService”) Tell Spring that this is something called customerService and that you need to take care of it and create an object for it when it initializes.
@Resource Annotations in Java, injected objects
@Transactional Tell Spring that you need to start the transaction

11 Control layer code

This is the stage for SpringMVC. The following code

package com.buer.controller;

import com.buer.domain.Customer;
import com.buer.service.IcustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/ * * *@Description:
 * @Author: boolean
 * @Date: 2019/12/22 18:50 * /

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Resource
    private IcustomerService service;
    @RequestMapping("/index")
    public String test(a){
        System.out.println("ssss");
        return "index";
    }


    @RequestMapping("/save")
    public String save(Customer customer){
        System.out.println("save");
        service.saveCustomer(customer);
        return "success";
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Customer> list(a){
        System.out.println("list");
        return service.list();
    }

    @RequestMapping("/findById")
    @ResponseBody
    public Customer findById(Integer id){
        System.out.println("findById");
        returnservice.findById(id); }}Copy the code
annotations role
@Controller Tell SpringMVC, this is your code
@RequestMapping(“/save”) Tell SpringMVC to access with the “/save” path
@ResponseBody Tell SpringMVC to return JSON

That’s the code, but we’re not done yet. We need some configuration files.

12 jdbc.properties

We want to connect to the database as follows

jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
Copy the code

13 applicationContext.xml

We need to tell Spring to connect to the database and where our code is and how to manipulate it. The following code

<?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">

    <! Jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <! Create DataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="10"/>
        <property name="maxIdle" value="5"/>
    </bean>

    <! Create SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <! -- Associate connection pool -->
        <property name="dataSource" ref="dataSource"/>
        <! Mapper.xml -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <! Scan all interfaces of Mapper -->
    <! -- Note: If the Mapper interface package is used for scanning, then the id name of each Mapper interface in the Spring container is the class name: for example, CustomerMapper -> CustomerMapper ->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! Mapper interface package path -->
        <property name="basePackage" value="com.buer.dao"></property>
    </bean>

    <! -- Start Spring's IOC annotation scan -->
    <context:component-scan base-package="com.buer"/>

    <! -- Start Spring transactions -->
    <! -- Transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <! -- Enable Spring transaction annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
Copy the code

14 spring-mvc.xml

We need to tell SpringMVC, where is the code he needs and how to manipulate our code

15 web.xml

We need to start the project and some font specifications. The following code

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>01.mybatis</display-name>
  <! -- Configure SpringMVC encoding filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>
  <! -- Start SpringMVC -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <! -- Parameter: read spring-mvC.xml -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>


  <! -- Start Spring -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <! -- Change path -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
</web-app>
Copy the code

In this case, the back end is up.

16 Page Writing

16.1 the index. The JSP

We need to write the home page, the code is as follows

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < HTML > <head> <title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="easyui/jquery.min.js"></script> <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script> <link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">  <link id="themeLink" rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css"> <style type="text/css"> ul{ line-height: 30px; } </style> </head> <body class="easyui-layout"> <! <div data-options="region:'north',split:true" style="height:80px; > <! -- logo --> <div id="logo"> <img src="images/20191223003101.png"/> </div> <! <div id="loginDiv" style="position: absolute; right: 20px; top: 20px;" > Welcome, [super administrator], you login using [192.156.21.22]IP! </div> <div id="themesDiv" style="position: absolute; right: 20px; top:40px;" > <a href="javascript:void(0)" id="mb" class="easyui-menubutton" Data-options ="menu:'#Themesmeus',iconCls:'icon-edit'"> </a> <div id="Themesmeus" style="width:150px; > <div>default</div> <div>gray</div> <div>black</div> <div>bootstrap</div> <div>material</div> <div>metro</div> </div> </div> </div> <! <div data-options="region:'south',split:true" style="height:30px; > <div id="copyrightDiv" style="text-align: center;" > < p style = "max-width: 100%; Copyright 2018 </div> </div> <! <div data-options="region:'west',title:' system menu ',split:true" style="width:200px;" > <div id="aa" class="easyui-accordion" style="width:193px;" <div title=" system management "data-options="iconCls:'icon-reload',selected:true" style="padding:10px;" > < ul > < li > < a href = "javascript: void (0)" pageUrl = "customer_manage. JSP" > customer management < / a > < / li > < / ul > < / div > < / div > < / div > <! <div data-options="region:'center'" style="padding:5px; background:#eee;" > <div id="tt" class="easyui-tabs" style="width:500px; height:250px;" Data-options ="fit:true"> <div title=" start page "style="padding:20px; display:none;" </div> </div> <script type="text/javascript"> $(function(){// attach time to a tag $("a[pageUrl]").click(function(){ //1. Var pageUrl = $(this).attr("pageUrl"); Var title = $(this).text(); / / 2. Determine whether there is any option to specify a title card if ($(" # "tt) tabs (" exists", the title)) {/ / 3. If so, select the TAB $("#tt").tabs("select",title); }else{//4. $("#tt").tabs("add",{title:title, content:"<iframe src='"+pageUrl+"' width='100%' height='100%' frameborder='0'><iframe>", closable:true }); }}); $("#Themesmeus"). Menu ({onClick:function(item){//1. Var themeName = item.text; Var href= $("#themeLink").attr("href"); / / 3. Change the href attribute value / / easyui/themes/default/easyui. CSS href = href.substring(0,href.indexOf("themes"))+"themes/"+themeName+"/easyui.css"; 4 / / update the link's href attribute $(" # themeLink "). Attr (" href "href); }}); }); </script> </body> </html>Copy the code

16.2 customer_manage. JSP

We need the detail page. The code is as follows

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < HTML > <head> <title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <! <script type="text/javascript" SRC ="easyui/jquery.min.js"></script> <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script> <link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">  <link id="themeLink" rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css"> </head> <body> <table id="list"></table> <! <div id=" TB "> <a id="addBtn" href="#" class="easyui-linkbutton" Data-options ="iconCls:'icon-add',plain:true"> Add </a> <a id="editBtn" href="#" class="easyui-linkbutton" </a> <a id="deleteBtn" href="#" class="easyui-linkbutton" href="#" class="easyui-linkbutton" Data-options ="iconCls:'icon-remove',plain:true"> Delete </a> </div> <! <div id="win" class="easyui-window" style="width:500px; Height :300px" data-options="iconCls:'icon-save',modal:true,closed:true"> <form ID ="editForm" method="post"> <%-- provides id to hide field --%> <input type="hidden" name="id"> <input type="text" name="name" class=" easyui-validateBox "data-options=" Required :true"/><br/> <input type="radio" name="gender" value=" male "/> male <input type="radio" name="gender" value=" female "/> female <br/> <input type="text" name="telephone" class=" easyui-validateBox "data-options="required:true"/><br/> <input type="text" name="address" class="easyui-validatebox" data-options="required:true"/><br/> <a id="saveBtn" Href ="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'"> Save </a> </form> </div> <script Type ="text/javascript"> $(function(){$("#list").datagrid({//url: "customer/list.action", //columns: Tille: Columns :[[{field:" ID ", title:" customer number ", width:100, checkbox:true}, {field:"name", Title :" customer name ", width:200}, {field:"gender", title:" customer gender", width:200}, {field:"telephone", title:" customer phone", width:200}, {field:"address", title:" client ", width:200}], // display pagination:true, // Toolbar :"# TB "}); / / open the edit window $(" # addBtn "). Click (function () {/ / clear form data $(" # editForm "). The form (" the clear "); $("#win").window("open"); }); / / save data $(" # saveBtn "). Click (function () {$(" # editForm "). The form (" submit ", {/ / url: // submit: OnSubmit :function(){return $("#editForm").form("validate"); }, //success: function(data){//data: The data returned by the server, type string class // requires the data returned by Controller in the following format: // Success: Data = eval("("+data+")"); If (data. Success) {/ / $(" # win "). Close the window the window (" close "); // Refresh datagrid $("#list"). Datagrid ("reload"); $.messager.alert(" info"," save successfully "); } else {$. Messenger. Alert (" prompt ", "save failed:" + data. MSG, "error"); }}}); }); $("#editBtn").click(function(){var Rows = $("#list").datAGrid ("getSelections"); if(rows.length! = 1) {$. Messenger. Alert (" prompt ", "modification operations can only choose one line", "warning"); return; $("#editForm").form("load","customer/ findByid.action? id="+rows[0].id); $("#win").window("open"); }); // Delete $("#deleteBtn").click(function(){var rows =$("#list").datagrid("getSelections"); If (rows.length==0){$.messager.alert(" alert "," delete at least one row ","warning"); return; } / / format: id = 1 & id = 2 & 3 $id =. Messenger. Confirm (" prompt ", "confirm delete data?" ,function(value){ if(value){ var idStr = ""; / / traverse data $(rows). Each (function (I) {idStr + = (" id = "+ rows [I] id +" & "); }); idStr = idStr.substring(0,idStr.length-1); $.post("customer/delete.action",idStr,function(data){if(data.success){// Refresh the datagrid $("#list").datagrid("reload"); $. Messager. alert(" info"," delete succeeded "); } else {$. Messenger. Alert (" prompt ", "delete failed:" + data. MSG, "error"); } },"json"); }}); }); }); </script> </body> </html>Copy the code

complete

Q&A

java-lang-illegalargumentexception-no-converter-found-for-return-value-of-type

The reason is that no json returns are converted

  1. Add it on CustomerController@ResponseBody
  2. Jackson dependencies need to be added