About this article

Spring content has learned three content, today is the last article, this section is basically familiar with the process, this article to achieve the functions: through the Web page to access the database, to achieve data insertion and query in the data table; In addition to creating a Web project instead of a Java project, I’ll briefly review the JSP content and learn something new: how to make Spring container objects globally unique.

Implementation steps

Step 1: Create a table

For this step, we will continue to use the newly created programmer from the previous section, which has three fields: ID, name, and age.

Step 2: Create a Web project and add dependencies

The difference between creating a Web project and creating a Java project is that we choose a different template. Of course, it is based on Maven. The template is xxx-Maven-archetype-webapp.

After creation, the directory structure will have one more WebApp directory than the Java project, and the corresponding Java and Resources directories will be missing. We can create them manually.

Add dependencies to the POM.xml file. Unlike the previous section, here you need to add two more dependencies (JSP and servlet). The complete code is as follows:


      

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.javafirst</groupId>
    <artifactId>spring-webapp</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <packaging>war</packaging>

    <! -- <name>spring-webapp Maven Webapp</name>-->
    <! -- &lt; ! &ndash; FIXME change it to the project's website &ndash; &gt; -->
    <! -- <url>http://www.example.com</url>-->

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <! - MyBatis dependence - >
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <! -- Spring dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.14</version>
        </dependency>

        <! -- MyBatis with Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.3</version>
        </dependency>

        <! -- Spring transaction -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.14</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.14</version>
        </dependency>

        <! AspectJ AOP implementation annotations -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.14</version>
        </dependency>

        <! Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <! -- servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        
        <! -- jsp -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>
Copy the code

This article will add a dependency later, remember this file.

Step 3: Create a New Java entity class

The name of the field in the new entity class is not the same as the name of the field in the table.

public class Programmer {

    private Integer pId;
    private Integer pAge;
    private String pName;

    public Integer getpId(a) {
        return pId;
    }

    public void setpId(Integer pId) {
        this.pId = pId;
    }

    public Integer getpAge(a) {
        return pAge;
    }

    public void setpAge(Integer pAge) {
        this.pAge = pAge;
    }

    public String getpName(a) {
        return pName;
    }

    public void setpName(String pName) {
        this.pName = pName;
    }

    @Override
    public String toString(a) {
        return "Programmer information: {" +
                "pId=" + pId +
                ", pAge=" + pAge +
                ", pName='" + pName + '\' ' +
                '} '; }}Copy the code

Step 4: Create dao and Mapper files

We need to implement insert data and query data, so our DAO only needs to provide two interfaces.

public interface ProgrammerDaoNew {

    int insertProgrammer(Programmer programmer);

    Programmer selectProgrammerById(Integer id);
}
Copy the code

The corresponding mapper file is still separate here, in the mapper folder under the resources directory, the specific code is as follows:


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.javafirst.dao.ProgrammerDaoNew">

    <insert id="insertProgrammer">
        insert into programmer(`name`,age) values (#{pName},#{pAge})
    </insert>

    <select id="selectProgrammerById" resultMap="selectMap">
        select * from programmer where id = #{id}
    </select>

    <resultMap id="selectMap" type="com.javafirst.domain.Programmer">
        <id column="id" property="pId"/>
        <id column="name" property="pName"/>
        <id column="age" property="pAge"/>
    </resultMap>

</mapper>
Copy the code

Step 5: Configure the MyBatis core file

This is the same as in the previous section, and much the same is done in this configuration file, which is basically the flow code as mentioned earlier:


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <typeAliases>
        <typeAlias type="com.javafirst.domain.Programmer"/>
    </typeAliases>

    <mappers>
        <mapper resource="mapper/ProgrammerDaoMapper.xml"/>
    </mappers>
</configuration>
Copy the code

Here you should have a feeling point:

The above process is basically linked, that is, the order of existence, you see each file will introduce the content created in the previous step, write more, naturally easy.

Step 6: Create the business layer Service

Our business only add records and query records, of course, you can also expand on this basis, our interface content is as follows:

public interface ProgrammerService {

    int addProgrammer(Programmer programmer);

    Programmer findProgrammer(Integer id);
}
Copy the code

In its implementation class, we need to do the work in real business development, comparing all kinds of verification passed before the real add record work and so on.

public class ProgrammerServiceImpl implements ProgrammerService {

    ProgrammerDaoNew programmerDao;

    public void setProgrammerDao(ProgrammerDaoNew programmerDao) {
        this.programmerDao = programmerDao;
    }

    @Override
    public int addProgrammer(Programmer programmer) {
        return programmerDao.insertProgrammer(programmer);
    }

    @Override
    public Programmer findProgrammer(Integer id) {
        returnprogrammerDao.selectProgrammerById(id); }}Copy the code

One might wonder, when is the setProgrammerDao() method called here? This is handled by the Spring framework. When a custom Service is declared in the Spring configuration file, it is automatically injected. This is what we learned in the first part of Spring.

Step 7: Configure the Spring core file

It’s all boilerplate code, which was already mentioned in the previous article


      
<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 https://www.springframework.org/schema/context/spring-context.xsd">

    <! Use properties file to configure database link information in data source.
    <context:property-placeholder location="jdbc.properties"/>

    <! Declare data source -->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

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

    <! -- Statement MapperScannerConfigurer -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

        <property name="basePackage" value="com.javafirst.dao"/>
    </bean>

    <bean id="programmerService" class="com.javafirst.service.ProgrammerServiceImpl">
        <property name="programmerDao" ref="programmerDaoNew"/>
    </bean>
</beans>
Copy the code

The jdbc.properties file contains the following contents:

jdbc.url=jdbc:mysql://localhost:3306/spring_demo
jdbc.username=root
jdbc.password=root
Copy the code

At this point we’ve actually done the basic configuration, but we’re creating a Web project, not a Java project, so we’ll need web pages and simple logic to test, using our WebApp directory and JSP knowledge.

Step 8: Create the Jsp page

We need two JSP pages, one to input information and provide query function, namely insert operation, page we provide name and age input, and then submit the database insert operation, this file name is called register.jsp, its code is as follows:

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> Enter an engineer </title> </head> <body> <form method="post" action="add"> <%-- the name value is the key value in the servlet --%> name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br>
    <input type="submit" value="Enter"/>
</form>

<br><br>
<form method="get" action="find"> Query engineer information: <input type="text" name="pId">
    <input type="submit" value="Query">
</form>

</body>
</html>
Copy the code

The page should look something like this:

When we successfully input, the page will jump to a success page, which is our second JSP page registersuccess.jsp, we do not associate specific logic, just do a simple demonstration, the complete code is as follows:

<%--
  Created by studyingJava
  Date: 2022/1/24
  Time: 15:46
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> Registered successfully </title> </head> <body> Will jump to the home page for you... </body> </html>Copy the code

The toString() method has been overridden in the previous entity class. The toString() method has been overridden in the previous entity class. Of course, if you are interested, you can display the results on the page.

Step 9: Create the Servlet

We also need to create two servlets, one to handle the input request, i.e. the data raised by post, and the other to handle the query operation, i.e. the data operation of get request.

AddProgrammerServlet. Java code is as follows:

/** * desc: * author: recommend learning Java * 

* weChat: studyingJava */

public class AddProgrammerServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); // Retrieve the registration data submitted from the form String name = req.getParameter("name"); String age = req.getParameter("age"); System.out.println("Data submitted:" + name + age); // Create a Spring container to insert into the database String config = "spring-applicationContext.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(config); ProgrammerService service = (ProgrammerService) context.getBean("programmerService"); Programmer programmer = new Programmer(); programmer.setpName(name); programmer.setpAge(Integer.valueOf(age)); service.addProgrammer(programmer); // Give user feedback req.getRequestDispatcher("/registerSuccess.jsp").forward(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); }}Copy the code

There are basically three steps here, and you can look at the code comments.

FindProgrammerServlet. Java code is as follows:

/** * desc: * author: recommend learning Java * 

* weChat: studyingJava */

public class FindProgrammerServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); // Retrieve the registration data submitted from the form String pId = req.getParameter("pId"); System.out.println("User ID submitted for query:" + pId); // Create a Spring container to insert into the database String config = "spring-applicationContext.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(config); ProgrammerService service = (ProgrammerService) context.getBean("programmerService"); Programmer programmer = service.findProgrammer(Integer.valueOf(pId)); System.out.println(programmer); }}Copy the code

The logic is simple. If you noticed, we created Spring container objects in different servlets. This is the problem that needs to be solved at the beginning of this article.

Step 10: Configure the Servlet

We have created the Servlet, and now we can configure it, that is, when the browser visits, it can find the corresponding function hosting page to process the request. The configuration is also relatively simple, in the webApp directory web-INF WEB.

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

    <servlet>
        <servlet-name>AddProgrammerServlet</servlet-name>
        <servlet-class>com.javafirst.controller.AddProgrammerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddProgrammerServlet</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>FindProgrammerServlet</servlet-name>
        <servlet-class>com.javafirst.controller.FindProgrammerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FindProgrammerServlet</servlet-name>
        <url-pattern>/find</url-pattern>
    </servlet-mapping>
</web-app>
Copy the code

This is the equivalent of a portal, our Servlet is the equivalent of a page, and each page needs to be registered here to be used.

Step 11: Release and test

At this point, all of our work is in place, but unlike Java projects, Web projects need to be deployed and published before they can be accessed in a browser. I won’t go into more details about IDEA deployment for Web projects, but note that you must install and configure the JDK and Tomcat environment.

Port 8080 is occupied, which PID (process ID) is occupied by a port?

netstat -aon | findstr 8080
Copy the code

Find the ID of the process and kill it with the command:

netstat -aon | findstr 14321
Copy the code

Then try to restart the project. The two commands here are executed from the command line window.

Use the ContextLoaderListener

This is where we need to solve the previously mentioned problem using the ContextLoaderListener listener, which is provided by the Spring framework and has two core steps:

  • inpom.xmlAdd a dependency tospring-web
  • Configure it in web.xmlcontext-paramThe label

Spring – web dependency

<! -- spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>1.2.6</version>
</dependency>
Copy the code

The configuration in web.xml is as follows:

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

With these two steps configured, we can then use the spring-provided utility classes to modify our initialization Spring container code as follows:

//String config = "spring-applicationContext.xml";
//ApplicationContext context = new ClassPathXmlApplicationContext(config);

// This sentence is used instead of the previous one
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Copy the code

Fetching the ApplicationContext object in multiple places so that the system does not recreate it ensures that it is globally unique.

conclusion

  • Using Spring with MyBatis is actually very convenient, a lot of work can be configured to focus on business development, which may be the benefits brought by the framework
  • The process of creating Maven-based Java and Web projects must be able to complete common configurations

Learn programming, recommend the preferred Java language, xiaobian created a focus on Java original public number to recommend learning Java, you can search javaFirst attention in wechat, together to open the Java journey!