Home  >  Article  >  Java  >  maven Spring+Spring MVC+Mybatis+mysql lightweight Java web development environment construction

maven Spring+Spring MVC+Mybatis+mysql lightweight Java web development environment construction

PHP中文网
PHP中文网Original
2017-07-09 18:13:011138browse

A GIS system project I have been working on before uses the jsp+servlet framework. The data transmission framework uses the thrift framework of apache. The short-term multi-transmission style is not bad, but it is a bit too bloated compared to other java web projects. Now, let me introduce to you the lightweight java web framework that I have just studied recently.

1. First create a maven project

The IDE I use for development is IDEA 2017. Google reviews IDEA as follows: The most suitable IDE for developing Java programs. Everyone should know it after reading this. First create a new maven program, as shown in Figure

Choose to create from archeType, create the java (resource) folder under the src-》main folder, so that the java class can be created in this folder, and at the same time create the following four folders in the java directory, representing control respectively. Server, data storage processing, object model, processing service.

2. Add maven project dependencies.

pom.xml, the module name corresponding to each dependency has been noted.

<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 ">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ssm_test</groupId>
  <artifactId>demo1</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>demo1 Maven Webapp</name>
  <url>;/url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.1.4.RELEASE</spring.version>
    <jackson.version>2.5.0</jackson.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- 使用SpringMVC需配置 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.4</version>
    </dependency>

    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.1</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.18</version>
    </dependency>

    <!-- json -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.3</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>

    <!-- aop -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <!-- 上传文件 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>



    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.40</version>
    </dependency>

  </dependencies>
</project>

3. Create a service interface class under service

ITestService.Java

package com.chuyin.service;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by Zhang Feiyue on 2017/7/8.
 */
public interface ITestService {
    public JSONObject getUsers(JSONObject param);
}

4. Create a class that implements the interface method in the service folder

TestService.Java

package com.chuyin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chuyin.mapper.TestMapper;
import com.chuyin.service.ITestService;
import org.springframework.stereotype.Service;

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

/**
 * Created by Zhang Feiyue on 2017/7/8.
 */
@Service
public class TestService implements ITestService {
    @Resource
    private TestMapper testMapper;

    @Override
    public JSONObject getUsers(JSONObject param) {
        List<JSONObject> userList = testMapper.getUsers(param);
        JSONObject result = new JSONObject();
        result.put("userList", userList);
        return result;
    }
}

5. Create a data acquisition interface class in the mapper folder

TestMapper.Java

package com.chuyin.mapper;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by Zhang Feiyue on 2017/7/8.
 */
@Component
public interface TestMapper {
    public List<JSONObject> getUsers(JSONObject param);
}

6. Create a controller implementation class

TestController.Java

package com.chuyin.controller;

import com.alibaba.fastjson.JSONObject;
import com.chuyin.service.impl.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created by Zhang Feiyue on 2017/7/8.
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private TestService testService;

    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    public JSONObject getUser(@RequestBody JSONObject param) {
        JSONObject result = testService.getUsers(param);
        result.put("success", true);
        return result;
    }
}

Create a folder under the 7.resources file and configure TestMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chuyin.mapper.TestMapper">
    <select id="getUsers" parameterType="JSON" resultType="JSON">
        <![CDATA[
        select * from base_user where username=#{username}
        ]]>
    </select>
</mapper>

8. Create application.properties file and configure jdbc

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/chuyin
jdbc.username=root
jdbc.password=root

9. Configure log4j.xml, mybatis-config.xml, spring-common.xml, spring-mvc.xml

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p: %c - %m%n"/>
        </layout>
    </appender>

    <appender name="filelog_daily" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${catalina.home}/logs/catalina.log"/>
        <param name="DatePattern" value="'.'yyyy-MM-dd"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p: %c - %m%n"/>
        </layout>
    </appender>

    <appender name="errorlog_daily" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${catalina.home}/logs/error.log"/>
        <param name="DatePattern" value="'.'yyyy-MM-dd"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p: %c - %m%n"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="ERROR" />
            <param name="LevelMax" value="ERROR" />
        </filter>
    </appender>

    <!-- 3rdparty Loggers -->
    <!--<logger name="org.springframework.core">
        <level value="info"/>
    </logger>-->

    <logger name="java.sql.*">
        <level value="info"/>
    </logger>

    <!--<logger name="org.springframework.context">
        <level value="info"/>
    </logger>-->

    <!--<logger name="org.springframework.web">
        <level value="info"/>
    </logger>-->

    <logger name="org.springframework">
        <level value="info"/>
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>

    <!-- 下面是打印mybatis语句的配置-->
    <logger name="com.ibatis" additivity="true">
        <level value="DEBUG" />
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>

    <logger name="java.sql.Connection" additivity="true">
        <level value="DEBUG" />
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>
    <logger name="java.sql.Statement" additivity="true">
        <level value="DEBUG" />
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>
    <logger name="java.sql.PreparedStatement" additivity="true">
        <level value="info" />
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>
    <logger name="java.sql.ResultSet" additivity="true">
        <level value="info" />
        <!--<appender-ref ref="bizlog_daily" />-->
    </logger>

    <!-- Root Logger -->
    <root>
        <priority value="DEBUG"/>
        <appender-ref ref="console"/>
        <appender-ref ref="filelog_daily"/>
        <appender-ref ref="errorlog_daily"/>
    </root>

</log4j:configuration>

mybatis-config.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>
    <settings>
        <setting name="jdbcTypeForNull" value="NULL"/>
        <setting name="safeResultHandlerEnabled" value="false"/>
    </settings>

    <!-- 实体类,简称 -设置别名 -->
    <typeAliases>
        <typeAlias alias="JSON" type="com.alibaba.fastjson.JSONObject"/>
    </typeAliases>
    <!-- 实体接口映射资源 -->
    <plugins>
        <plugin interceptor="com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor">
            <property name="dialectClass" value="com.github.miemiedev.mybatis.paginator.dialect.MySQLDialect"/>
        </plugin>
    </plugins>

    <!--
        说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml
    -->
    <mappers>
        <mapper resource="com/chuyin/mapper/TestMapper.xml"/>
    </mappers>

</configuration>

spring-common.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		
		
		 http://www.springframework.org/schema/aop  http://www.springframework.org/schema/context ">
    <!-- 注解扫描包 -->
    <context:component-scan base-package="com.chuyin"></context:component-scan>

    <bean id="dataSourceMaster"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--<bean id="dataSourceSlave"-->
    <!--class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
    <!--<property name="driverClassName" value="${jdbc.driver}" />-->
    <!--<property name="url" value="${jdbc.url}" />-->
    <!--<property name="username" value="${jdbc.username}" />-->
    <!--<property name="password" value="${jdbc.password}" />-->
    <!--</bean>-->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--<bean id="dataSource" class="com.skytech.datasource.MultiDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="master" value-ref="dataSourceMaster"/>
                <!–<entry key="slave1" value-ref="dataSourceSlave"/>–>
                <!–<entry key="slave2" value-ref="dataSourceSlave2"/>–>
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="dataSourceMaster"/>
    </bean>-->

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

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

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!--<bean id="multiDataSourceAspect" class="com.skytech.datasource.DataSourceAspect">
        <property name="dataSource" ref="dataSource"/>
        <property name="masterKey" value="master"/>
        <property name="slaveKeys">
            <array>
                <value>slave1</value>
                <value>slave2</value>
            </array>
        </property>
    </bean>
    <aop:config>
        <aop:aspect id="c" ref="multiDataSourceAspect">
            <aop:pointcut id="tx" expression="execution(* com.skytech.pkdata.mapper.*.*(..))"/>
            <aop:before pointcut-ref="tx" method="before"/>
        </aop:aspect>
    </aop:config>-->
</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	
	
	
	
	">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:application.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="fileEncoding" value="UTF-8"></property>
    </bean>

    <!-- 注解扫描包 -->
        <context:component-scan base-package="com.chuyin">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>

    <!-- 开启注解 -->
    <mvc:annotation-driven/>
    <!--
        配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd
    -->
    <!--<mvc:resources mapping="/css/**" location="/css/" />-->
    <!--<mvc:resources mapping="/img/**" location="/img/" />-->
    <!--<mvc:resources mapping="/js/**" location="/js/" />-->
    <mvc:resources mapping="/lib/**" location="/lib/"/>
    <!--<mvc:resources mapping="/jsp/**" location="/jsp/" />-->
    <!--<mvc:resources mapping="/images/**" location="/images/" />-->
    <!--<mvc:resources mapping="/html/**" location="/html/" />-->

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/html/"/>
        <property name="suffix" value=".html"/>
    </bean>
</beans>

Okay, now the background has been fully configured. Let’s take a look at the effect. You can see that the data has been successfully obtained.

The above is the detailed content of maven Spring+Spring MVC+Mybatis+mysql lightweight Java web development environment construction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn