之前一直在做的一個GIS系統項目,採用了jsp+servlet框架,數據傳輸框架採用了apache的thrift框架,短時多傳的風格還不錯,但是較其他的java web項目顯得有點太臃腫了,現在要跟大家介紹一下最近剛研究的輕量級java web框架。
1.首先是建立maven專案
本人開發用的IDE用的是IDEA 2017,Google上這樣評價IDEA:最適合開發java程式的IDE,看到這裡大家就應該知道了。首先新建一個maven程序,如圖
#選擇從archeType創建,在src-》main資料夾下建立java(resource)資料夾,這樣才能在該資料夾下建立java class,同時在java目錄下建立如下四個資料夾,分別代表控制器、資料儲存處理、物件模型、處理服務。
#2.新增maven專案依賴。
pom.xml,各個相依性所對應的模組名稱已註明。
<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.在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.在service資料夾下建立實作介面方法的類別
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.在mapper資料夾下建立資料取得介面類別
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.建立控制器實作類別
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; } }
7.resources檔案下建立資料夾,並設定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.建立application.properties文件,設定jdbc
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/chuyin jdbc.username=root jdbc.password=root
9.設定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>
好了,至此後台已全部配置完畢,看一下效果吧,可以看到資料已經取得成功。
##
以上是maven Spring+Spring MVC+Mybatis+mysql輕量級Java web開發環境搭建的詳細內容。更多資訊請關注PHP中文網其他相關文章!