IDEA下创建Springboot,freemarker,mockserver,Gradle项目
来源:互联网 发布:淘宝的昵称怎么改手机 编辑:程序博客网 时间:2024/06/15 07:34
有时候,springboot只是作为一个前置服务,不需要链接数据库,而是去调别人restful接口,然后去展示h5页面。
而且后台接口很多时候是不能在我们前置服务开发之前都开发完的,我们这里就需要一个mock server来模拟后台接口。
这个时候,我们就需要搭建一个Springboot,freemarker,mockserver,Gradle项目了。
话不多说,直接上一套简单框架全部代码。
1、项目结构图
2、build.gradle
plugins { id 'org.springframework.boot' version '1.5.3.RELEASE'}apply plugin: 'java'apply plugin: 'idea'apply plugin: 'eclipse'repositories { jcenter()}jar { baseName = 'preserver'}sourceCompatibility = 1.7targetCompatibility = 1.7compileJava.options.encoding = 'UTF-8'compileTestJava.options.encoding = 'UTF-8'task wrapper(type: Wrapper) { gradleVersion = '4.1'}bootRun { addResources = true}configurations { compile.exclude module: "spring-boot-starter-tomcat"}dependencies { compile 'org.slf4j:slf4j-api:1.7.21' compile 'org.apache.commons:commons-lang3:3.5' compile 'com.google.guava:guava:21.0' compile 'org.springframework.boot:spring-boot-starter' compile 'org.springframework.boot:spring-boot-starter-web' compile 'org.springframework.boot:spring-boot-starter-security' compile 'org.springframework.boot:spring-boot-starter-undertow' compile 'org.springframework.boot:spring-boot-starter-test' compile 'org.springframework.boot:spring-boot-starter-aop' compile 'org.springframework.boot:spring-boot-starter-logging' compile 'org.springframework.boot:spring-boot-starter-freemarker' compile 'org.springframework.boot:spring-boot-devtools' compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3' compile group: 'com.alibaba', name: 'fastjson', version: '1.2.39' testCompile 'junit:junit:4.12'}
3、application.yaml
spring.profiles.active: local---spring: profiles: local devtools.restart.enabled: true output.ansi.enabled: ALWAYS freemarker: suffix: .html settings: datetime_format: yyyy-MM-dd HH:mm:ss date_format: yyyy-MM-dd time_format: HH:mm:ss number_format: 0.###### boolean_format: true,false auto_import: "'spring.ftl' as spring" whitespace_stripping: true default_encoding: UTF-8 tag_syntax: auto_detect url_escaping_charset: UTF-8 template_update_delay: 3 locale: zh_CN cache_storage: strong:20,soft:250 resources.chain.strategy: content.enabled: true fixed.version: 1 mvc: favicon.enabled: false static-path-pattern: /**logging: level.root: info level.com.smknet.hmls.preserver: info path: /home/fuhd/work/workspace/idea/ file: preserverservlet: container: port: 8080 timeout: 30net4j: url: http://192.168.23.208:9001---spring: profiles: test---spring: profiles: pqa---spring: profiles: prod
4、logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?><configuration> <include resource="org/springframework/boot/logging/logback/defaults.xml"/> <include resource="org/springframework/boot/logging/logback/console-appender.xml"/> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${LOG_PATH}${LOG_FILE}.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>UTF-8</charset> </encoder> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>50MB</MaxFileSize> </triggeringPolicy> </appender> <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${LOG_PATH}${LOG_FILE}_error.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>UTF-8</charset> </encoder> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <root> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> <logger name="com.smknet.hmls.preserver" level="ERROR"> <appender-ref ref="ERROR_FILE"/> </logger></configuration>
5、ProductController
package com.smknet.hmls.preserver.controller;import com.smknet.hmls.preserver.service.UserService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;/** * 产品控制类 * Created by dyw on 2017/10/11. */@Controller@RequestMapping("/product")public class ProductController { private static final Logger logger = LoggerFactory.getLogger(ProductController.class); @Autowired private UserService userService; @RequestMapping("/show") public String show(Model model) { try { String user = userService.getUserName(); model.addAttribute("user", user); } catch (Exception e) { //查询抛异常的时候,返回异常页面 return "test"; } return "test"; }}
6、UserServiceImpl
package com.smknet.hmls.preserver.service.impl;import com.smknet.hmls.preserver.service.UserService;import com.smknet.hmls.preserver.util.HttpClientUtil;import org.springframework.stereotype.Service;/** * 用户service实现类 * Created by dyw on 2017/10/12. */@Servicepublic class UserServiceImpl implements UserService { @Override public String getUserName() { String userInfo = HttpClientUtil.httpGetRequest("http://localhost:1111/UUS001?accessToken=123456"); return userInfo; }}
7、HttpClientUtil
package com.smknet.hmls.preserver.util;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.client.utils.URIBuilder;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URISyntaxException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Map;/** * httpclient 工具类 * Created by dyw on 2017/10/11. */public class HttpClientUtil { private static PoolingHttpClientConnectionManager cm; //当请求出现异常的时候返回的字符串 private static String EMPTY_STR = ""; private static String UTF_8 = "UTF-8"; private static void init() { if (cm == null) { cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(50);// 整个连接池最大连接数 cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2 } } /** * 通过连接池获取HttpClient * * @return */ private static CloseableHttpClient getHttpClient() { init(); return HttpClients.custom().setConnectionManager(cm).build(); } /** * http get 方法 * * @param url url链接 * @return 相应内容String类型 */ public static String httpGetRequest(String url) { HttpGet httpGet = new HttpGet(url); return getResult(httpGet); } public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException { URIBuilder ub = new URIBuilder(); ub.setPath(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); ub.setParameters(pairs); HttpGet httpGet = new HttpGet(ub.build()); return getResult(httpGet); } public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) throws URISyntaxException { URIBuilder ub = new URIBuilder(); ub.setPath(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); ub.setParameters(pairs); HttpGet httpGet = new HttpGet(ub.build()); for (Map.Entry<String, Object> param : headers.entrySet()) { httpGet.addHeader(param.getKey(), String.valueOf(param.getValue())); } return getResult(httpGet); } /** * http post * * @param url url * @return 相应内容String格式 */ public static String httpPostRequest(String url) { HttpPost httpPost = new HttpPost(url); return getResult(httpPost); } /** * http post * * @param url url * @param body 消息体 * @return 响应内容 */ public static String httpPostRequest(String url, String body) { HttpPost httpPost = new HttpPost(url); // 构建消息实体 StringEntity entity = new StringEntity(body, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); // 发送Json格式的数据请求 entity.setContentType("application/json"); httpPost.setEntity(entity); return getResult(httpPost); } public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8)); return getResult(httpPost); } public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(url); for (Map.Entry<String, Object> param : headers.entrySet()) { httpPost.addHeader(param.getKey(), String.valueOf(param.getValue())); } ArrayList<NameValuePair> pairs = covertParams2NVPS(params); httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8)); return getResult(httpPost); } private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) { ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, Object> param : params.entrySet()) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()))); } return pairs; } /** * 处理Http请求 * * @param request http请求 * @return 相应结果 */ private static String getResult(HttpRequestBase request) { // CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = getHttpClient(); try { CloseableHttpResponse response = httpClient.execute(request); // response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { // long len = entity.getContentLength();// -1 表示长度未知 String result = EntityUtils.toString(entity); response.close(); // httpClient.close(); return result; } } catch (IOException e) { e.printStackTrace(); } finally { } return EMPTY_STR; }}
8、WebSecurityConfig
package com.smknet.hmls.preserver.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.security.SecurityProperties;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/**") .permitAll() .anyRequest() .authenticated(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user") .password("password") .roles("USER"); }}
9、EmbeddedServletContainerConfig
package com.smknet.hmls.preserver.config;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;/** * Servlet容器配置 */@Componentpublic class EmbeddedServletContainerConfig implements EmbeddedServletContainerCustomizer { @Value("${servlet.container.port}") private Integer port; @Value("${servlet.container.timeout}") private Integer timeout; @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(port); container.setSessionTimeout(timeout, TimeUnit.MINUTES); }}
10、test.html
<!DOCTYPE html><html lang="en"><head> <title>测试</title> <meta charset="utf-8"></head><body><h1>${user}</h1></body></html>
11、foo.json 和 mocoserver
打开cmd,转到我们mocoserver的路径下
这里有2个文件,详细看下图
执行下面一段命令,用来启动mocoserver
java -jar moco-runner-0.11.0-standalone.jar start -p 1111 -c foo.json
[ { "request":{ "uri":"/UUS001", "queries":{ "accessToken":"123456" } }, "response":{ "json":{"name":"dddddddddddd"} } }]
mocoserver下载地址
我上传的时候发现不能设置0积分。。如有需要,可以私信我邮箱地址,看到肯定第一时间发你~
到这里我们已经完成项目的全部了,可以运行查看效果了哈~
ok~
这里打个小广告~
需要看电影的童鞋,可以关注下~
谢谢哈~
阅读全文
1 0
- IDEA下创建Springboot,freemarker,mockserver,Gradle项目
- idea 下gradle创建springboot 项目
- IDEA下gradle创建springboot项目
- idea+springboot+gradle创建项目
- IDEA下创建Springboot,thymeleaf,Mybatis,Postgresql,Gradle项目
- 使用IDEA+GRADLE创建springboot项目
- 使用idea+gradle创建springboot项目
- Gradle创建springboot项目
- idea创建springboot项目
- idea+springboot创建项目
- [SpringBoot学习]-IDEA创建Gradle多Module结构的SpringBoot项目
- 使用gradle 创建springboot项目
- IDEA SpringBoot gradle打项目jar包
- 使用IDEA创建SpringBoot项目
- idea中创建springboot项目
- 使用idea创建SpringBoot项目
- 使用idea创建springboot项目
- springBoot系列-IDEA 创建springBoot项目
- SVN之svnadmin初始化配置-yellowcong
- 第一次安装centos7
- 关于学习javascript的笔记
- Linux(Ubuntu)下编译PJSIP2.7
- [Lincode] #149 买卖股票的最佳时机
- IDEA下创建Springboot,freemarker,mockserver,Gradle项目
- sshkey管理Linux系统的联网登录
- ITIL的服务目录管理流程的关键知识
- 顺序栈的压栈和出栈
- 百度语音REST API -- 简单Demo
- spark 集群启动后,worker 节点worker 进程一段时间后自动结束
- 编程题
- Java设计模式之责任链模式
- 最长递增路径