Ultra-detailed IDEA configuration SSM environment

1. Database table creation

create database idcard;

create table usertable
(
id int(11) primary key not null auto_increment,
uname varchar(50) not null,
upwd varchar(32) not null
);

2. Create a new maven project

New Project, only select Maven on the left and the SDK above, and do not select all others, next:

insert image description here
Enter GroupId and ArtifactId:
insert image description here

Finish:
insert image description here

Enter the main interface as shown below:
insert image description here

(You can choose Enable Auto-Import automatically prompted in the lower right corner, and you can automatically import maven coordinates later)

3. Configure pom.xml

Open pom.xml and fill in the following dependencies. I have personally tested that these coordinates are compatible with each other, including spring, spring mvc, mybatis, mysql, servlet, junit, log4j, etc.:

<dependencies>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
        <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.2</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.45</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.8.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>2.9.0</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.2</version>
    </dependency>
    
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.2.1</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

Finally, External Libraries can see the imported package:
insert image description here

If it cannot be imported automatically, click Maven on the right, and then click the reimport button on the left that looks like a refresh style:
insert image description here

4. Add web support to the project

Right-click the ssm project and select Add Framework Support:

insert image description here

Select Web Application and OK:

insert image description here

This adds the web folder and web.xml to the project directory as follows:
insert image description here

5. Create entity class

Right-click the java folder and write java code in this directory.

Create a new MyUser class. The previous model. is for building packages, so you can build packages and classes in one step:

insert image description here

Fill in the following code:

package model;

public class MyUser {
    
    
    private int id;
    private String uname;
    private String upwd;

    public int getId() {
    
    
        return id;
    }

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

    public String getUname() {
    
    
        return uname;
    }

    public void setUname(String uname) {
    
    
        this.uname = uname;
    }

    public String getUpwd() {
    
    
        return upwd;
    }

    public void setUpwd(String upwd) {
    
    
        this.upwd = upwd;
    }
}
  • Tip: After filling in the three attributes, right-click the blank area and select generate to automatically generate Getters and Setter:

insert image description here

insert image description here
insert image description here

6. Create PO

The entity class just created is for code logic. Then create a new MyUserTable under the po package, which corresponds to the database form:

package po;

public class MyUserTable {
    
    
    private int id;
    private String uname;
    private String upwd;

    public int getId() {
    
    
        return id;
    }

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

    public String getUname() {
    
    
        return uname;
    }

    public void setUname(String uname) {
    
    
        this.uname = uname;
    }

    public String getUpwd() {
    
    
        return upwd;
    }

    public void setUpwd(String upwd) {
    
    
        this.upwd = upwd;
    }
}

7. Create dao

Create a new dao package and create a new interface UserMapper for MyBatis agent development:

package dao;

import model.MyUser;

public interface UserMapper {
    
    
    
    void register(MyUser myUser);
    
}

Create a new mapper directory in the resource directory and a new UserMapper.xml file in the mapper directory:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.UserMapper">
    <select id="register" parameterType="myUser">
        insert into usertable (id, uname, upwd) values (null, #{uname}, ${upwd})
    </select>
</mapper>

The namespace fills in the path of UserMapper, and the id corresponds to the method name in UserMapper.

At this time, the UserMapper class is associated with the UseMapper.xml configuration file.

Note: myUser here is an alias, and the alias of the entity class will be configured later.

8. Create new jdbs.properties

Create a new jdbs.properties under the resources directory and fill in the following content:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/idcard?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

Note: useSSL=false is to solve the "Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure" error. If not encountered, it can be ignored.

9. Configure sqlMapConfig.xml

Create a new sqlMapConfig.xml in the resources directory and fill in the following content:

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

    <properties resource="jdbc.properties"></properties>


    <typeAliases>
        <package name="model"/>
        <package name="po"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>


</configuration>

typeAliases is the alias mentioned above. The package attribute creates aliases for all classes under the package, which can be accessed without a package path.

This file mainly configures the mapper mapping file to associate the previously configured mapper mapping with the database.

10. Create service

Create a new service package and create a new interface UserService:

package service;

import model.MyUser;

public interface UserService {
    
    
    
    void register(MyUser myUser);
    
}

Implementation of the new interface UserService:

package service;

import dao.UserMapper;
import model.MyUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
public class UserServiceImpl implements UserService {
    
    
    @Override
    public void register(MyUser myUser) {
    
    
        try {
    
    
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.register(myUser);

            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }
}

Here, sqlMapConfig.xml is introduced to realize the association between the database and UserMapper.xml, and UserMapper.class is also introduced to realize the association between dao and database.

Therefore, the service can already operate the database.

Tips: Implements became popular after they were implemented. Press alt+enter to select implement methods to automatically generate @Override:

insert image description here

11. Deploy applicationContext.xml

Create a new applicationContext.xml in the resources directory and fill in the following content:

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

    <context:component-scan base-package="service"/>
    <context:component-scan base-package="dao"/>

</beans>

Spring in ssm is only responsible for service and dao, and the controller is controlled by spring mvc.

12. Create controller

Create a new controller package and create a UserController class:

package controller;

import model.MyUser;
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.ResponseBody;
import service.UserService;

@Controller
public class UserController {
    
    

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    @ResponseBody
    public String test() {
    
    
        System.out.println("get a request: register");

        MyUser myUser = new MyUser();
        myUser.setId(1);
        myUser.setUname("tom");
        myUser.setUpwd("123");

        userService.register(myUser);
        return "register success";
    }
}

After the simulation receives an empty register request, let the service control the dao.

13. Configure springmvc.xml

Create a new springmvc.xml in the resources directory and fill in the following content:

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="controller"/>

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


    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

14. Configure web.xml

Configure web.xml in the web/WEB-INF directory and fill in the following content:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

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

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

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

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

</web-app>

web.xml integrates applicationContext.xml and springmvc.xml, unifying all configuration contents.

Currently, the project directory structure is as follows:

insert image description here

15. Configure tomcat

Click Add Configuration in the upper right corner:

insert image description here

Click the plus sign + in the upper left corner and select Tomcat Server, Local:

insert image description here

First configure the Application server under Server:

insert image description here

Select the locally downloaded tomcat root directory:

insert image description here

Enter Deployment, as shown below:

Click the plus button, select Artifact, click the modify button, select all Available Elements and right-click Put into Default Locations:

insert image description here

insert image description here

In this way, you can see the maven coordinates imported at the beginning in WEB-INF/lib:

insert image description here

16. Start the project

Click the green triangle Start button:

insert image description here

The browser jumps to localhost:8080/ssm_war_exploded by default, and web/index.jsp is displayed.

Just add /register after the link to access the RequestMapping in the controller:

insert image description here

Check the database content. A new item has been added, which is an attribute of the myUser class simulated by the controller:

insert image description here

17. Summary

Tomcat starts the configuration of web.xml, and then uses web.xml to start the configuration of applicationContext.xml and springmvc.xml.

Among them, applicationContext.xml controls service and dao, and service can use dao and mybatis mapping to operate the database; springmvc.xml controls controller to realize user external access.

Therefore, ssm connects the entire process from user to service to database.

18. ssm configuration mind map

insert image description here

Guess you like

Origin blog.csdn.net/yilongyoung/article/details/125102707