《数据采集技术(初级)》实验手册项目9:创建SpringBoot项目.docx
项目九:创建SpringBoot项目浪潮:2020年7月作者版本时间审核备注王健2.02020-7-13主要内容:1、创建SPringBOot项目.(1)通过多种不同的形式创建SPringBOot项目。2、配置SPringBOOt的日志。(1)配置IogbaCk日志系统。3、将SpringBoot项目发布到LinUX服务器上去。(1)安装JDK。(2)配置JDK,并发布SpringBoot项目到LinUX上去。通过nohug启动SPringbOOt项目。一、创建SPringBoot项目的方法创建SPringBoOt项目的方法有很多种,目前比较流行的为两大种:1、在线创建 在线通过start.spring.io创建SpringBoot项目,在创建完成以后,再导入lDE中开发。2、使用IDE创建 在IDE中直接使用SpringInit直接创建SPringBOot项目。IDE可以是STS也可以是IDEA03、集成开发工具介绍 开发SpringBoot项目,建议使用STS或IDEA. 在使用之前,请给STS或IDEA安装Lombok插件。 安装maven,并配置环境变量。(.m2/SeHingS.xml配置细节)Maven/gradle如果要开发任可java项目,Java项目依赖很多的其他的第三方的库。第三方的库,你可以手工的放到项目中。不要。Maven-在STS、IDEA里面,都自带了。问题:如果使用自带的,将会所有依赖下载到Suser.m2repository->30G+建议大家还要是自己安装一个maven:1:下载Maven.apache.org2:解压Mavenisdistributedinseveralformatsforyourconvenience.Simplypickaready-madebinarydistributionarchiveandfollowinstallationinstructions.UseasourcearchiveifyouintendtobuildMavenyourself.Inordertoguardagainstrrupteddownloads/installations,itishighlyremmendedtoverifythesignatureofthereleasebundlesagainstthepublicKEYSusedbytheApacheMavendevelopers.LinkChecksumsSignatureBinarytar.gzarchiveapache-maven-3.6.3-bin.tar.gzapache-maven-3.6.3-bin.tar.gz.sha512apache-maven-3.6.3-bin.tar.gz.ascBinaryziparchiveapache-maven-3.6.3-bin.zipapache-maven-3.6.3-bin.zip.sha512apache-maven-3.6.3-bin.zip.三Sourcetar.gzarchiveapache-maven-3.6.3-src.tar.gzapache-maven-3.6.3-src.tar.g乙sha512apache-maven-3.6.3-src.tar.gz.ascSourceziparchiveapache-maven-3.6.3-src.zipapache-maven-3.6.3-src.zip.sha512apache-maven-3.6.3-src.zlp.sRaIaaAaNtA<3:配本地仓库到其他的目录贞共享查看修改日期2020/6/14 13:21 2020/6/1413:21 2020/6/1413:21 2020/6/1413:21 2019/11/712:322019/11/7 12:32 2019/11/712:32个>此电脑>Data(D:)>program>apache-maven-3.6.3名称可binbootconflibLICENSEIIOadSNOTICEr_allHREADMEtxt配置:M2HoME=安装目录PATH=%M2-H0ME%binC:Userswangjian>mvn-versionApacheMaven3.6.3(cecedd343002696d0abb50b32b541b8a6ba2883f)Mavenhome:D:programapache-maven_3.6.3bin.Javaversion:11.0.7,vendor:OracleCorporation,runtime:D:programjdk-ll.0.7Defaultlocale:zh_CN,platformencoding:GBKOSname:"windows10",version:"10.0”,arch:"amd64",family:"windows”配置仓库:个Data(D:)>program>apache-maven-3.6.3>confI/b.名称logging修改日期2020/6/14"settings.xml2019/11/72019/11/7-toolchains.xml主页共享查看快速访问I桌面此电脑>Windows(C:)>用户>wangjian>.m2vQQ搜索.m2名称修汉日期类型大小:图片downf C :Userswangjian.m2settings.xml - Notepad+ +话单文件(E)编指搜索视图W 编码(N)语言CL)设置(D IM(Q)宏(M)运行(B)插件(E) fi 1耳©胃心硼*酶胤nell 7I国剧士 X廉国园N囹回圉圃eH settings. Xmldj H virus. Iogt3 H id rsa. pubt3 日 settings, xnl此电脑I 3DI蜩名片0台L下载'音乐I施Windc,-Data (新加卷464743495051525354555657585960616263<settings XInlnS=I,http: / /maven.apauhe.og/SETT工NGS/1.0.01,xmlns:xsi=,http: www.w3.ora2001XMLSChemaTnstance"xsi:SChemaLoCatiOn="http:/maven.apauhe.orqSETTINGS/1.0.0 http:/maven.aaau】 <!- IocalRepositoryI The path to the local repository maven will use to store artifacts.II Default: $user.home/.m2/repository<localRepository>pathtolocalrepo<localRepository>><localRepository>E:/cache/.m2repository<localRepository> <!- InteractiveModeI This will determine whether maven prompts you when it needs input. If set to fals( I maven will use a sensible default value, perhaps based on some other setting, for I the parameter in question.II Default: true<interactiveMode>true<interactiveMode>settings.×ml2020/6/1413:29XMLg11KB二、创建SPringbOOt项目1、在线创建步1、打开start.spring.io输入项目名称,选择版本:(对每一项目做细节说明)springinitializrProjectLanguageMavenProjectOGradleProjectJavaOKotlinOGroovyVzVSpringBootO2.4.0(SNAPSHOT)O2.4.0(M1)O2.3.2(SNAPSHOT)2.3JO2.2.9(SNAPSHOT)O2.2.8Q2.1.16(SNAPSHOT)O2.1.15ProjectMetadataGroupcn.inspurzArtifactbt-demoZNameboot-demoDescription第一zTsSpringBOotgl页目Packagenamecn.inspurYZZZPackagingjOWarJavaO14O11”1 :maven为所使用的依赖工具。2 :Java为开发语言.3 :2.3.1为目前Release版本。4 :GrOUP为项目的包名。5 :Artifact为项目的名称。击忝加依赖:Dependenciesadddependencies.ctrl+B1.ombokJavaannotationlibrarywhichhelpstoreduceboilerplatecode.SpringBootDevTooIsDEVELOPERTOOLSDEVELOPERTOOLSProvidesfastapplicationrestarts,LiveReIoad,andconfigurationsforenhanceddevelopmentexperience.SpringConfigurationProcessorDEVELOPERTLSGeneratemetadatafordeveloperstooffercontextualhelpand"codecompletion"whenworkingwithcustomconfigurationkeys(ex.application.properties.ymlfiles).SpringWebWEBBuildweb,includingRESTfuI,applicationsusingSpringMVC.UsesApacheTomcatasthedefaultembeddedcontainer.ThymeleafTEMPLATEENGINESAmodernSQrVQFSidQJavatemplateengineforbothwebandstandaloneenvironments.AllowsHTMLtobecorrectlydisplayedinbrowsersandasstaticprototypes.SpringBootActuatorOPSSupportsbuiltin©rcustom)endpointsthatletyoumonitorandmanageyourapplication-suchasapplicationhealth,metrics,sessions,etc.ValidationI/OJSR-3O3validationwithHibernatevalidator.对每一N三做说明:1:LOmbok用于简化开发。2 :bootdev为开发选项.3 :Config用于读取配置时的选项。4 :Web网络开发组件。5 :ThymeIeaf模板。6 :Actuator健康检杳。7 :JSR303期正。步2、下载并导入GENERATECTRL+¢0iboot-demo.zip导入到IDE中去,如STS/Eclipse中去:选择导入的项目类型:ImportSelectImportexistingMavenprojectsSelectanimportwizard:typefiltertext> &Install> aJavaEEVaMavenCheCkOUtMaVenPrOieCtSfroynSCMITEXiStingMaVenProjeCtS,InstallordeployanartifacttoaMavenrepository¾MaterializeMavenBinaryProject同MaterializeMavenProjectsfromSCM>&PlUg-inDevelopment选择已经解压好的项目:ImportMavenProjectsMavenProjectsSelectMavenprojectsRootDirectory:E:downloadsboot-demo、Browse.Projects:Qpom.xmlCn.inspw:boot-demo:0.0.1-SNAPSHOT:jarSelectAllDeselectAllSelectTreeDeselectTreeRefresh0Addproject(s)toworkingsetboot-demo>Adyanced等待更新完成:HProblems<«JavadocDeclarationConsole=yProgressXImportingMavenprojects231KB849KB(27%)https:/repo.maven.apache.Org/maven2/org/thymeleaf/thymeleaf/3.0.11.RELEASEthymeleaf-3.0.11.RELEASEjar可选的添加aliyunmaven仓库:<build><repositories><repository><id>central<id><url><repository><repository><id>public<id>< url><repository><repositories><pluginRepositories><pluginRepository><id>central<id>< url><pluginRepository><pluginRepository><id>public<id>< url><plugiRepository><pluginRepositories><project>步3、配置V器boot-demobootdevtoolsOsrc/main/javaQsrc/main/resourcesstaticetemplatesapplication.properties配置的内容如下:server.port=8888spring.application.name=boot-demoserver.servlet.encoding.charset=UTF-8spring.messages.encoding=UTF-8spring.thymeleaf.cache=falsespring.thymeleaf.encoding=UTF-8springjackson.time-zone=GMT+8spring.jackson.date-format=yyyy-MM-ddHH:mm:ssIoggingJeveI.root=infologging.file.name=logsSspring.application.name.log具体含义说明.略。步4、开发1、开发index.htmlP(3src/main/resources&staticVCtemPlateSindex.html<!DOCTYPEhtml><htmlXmlnslh="http:/www.thymeleaf.org><head><metacharset="UTF-8"><title>Inserttitlehere<title><head><body><p>Hello这是主页<p><body><html>2、配置index.html配置index.html如下:packagecn.inspur.config;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.ViewControllerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;©ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer(三)OverridepublicvoidaddViewControllers(ViewControllerRegistryregistry)registry.addViewControllerCindex").setViewName("index");registry.addViewControlIer(V-).SetViewNamefindex');registry.addViewController(-").setViewName("index");)启动:审boot-demobootdevtoolsv(3src/main/javav由cn.inspur1.LBootDemoAppIicationjava/W/一'(_)()一I_I,-lI_/JIW_)lL)lIIIIIl(_lI)'I_I._l_lLLIL一I/=I_I=I/=/_/_/_/:SpringBoot:(v2.3.!.RELEASE)访问测试:÷÷C©IocaIhost:8888/indexHello这是主页停止项目。3、开发HelloControIIerpackagecn.inspur.api.hello.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importlombok.extern.slf4j.Slf4j;ReqUeStMaPPing("hello')ControllerSlMjpublicclassHelloControIIerGetMapping('hi")publicStringhi()Xo.info(ehello.Hi.");return"hello/hi"添加超连接:<!DOCTYPEhtml><htmlxmlnslh=uhttp:/www.thymeleaf.org"><head><metacharset="UTF-8h><title>Inserttitlehere<title><head><body><p>Hello这是主页<p><ahref=l,hellohi">Hello/hi<a><body><html>添加hi.html页面:/atemplatesV&hellohi.html<!DOCTYPEhtml><htmlxmlnslh=uhttp:/www.thymeleaf.org"><head><metacharset="UTF-8h><title>Inserttitlehere<title><head><body><p>这是把页面<p><body><html>启动项目,并测试访问:,Clocalhost:8888/hello/hi这是hi页面4、显示数据Y耕boot-demobootdevtoolsv(3src/main/javaY田cn.inspurv田api.hellovtcontroller> 团HelloControIIerjavaV田service> 团HelloServiceJava由VO> 团Helldiavapackagecn.inspur.api.hello.vo;importlombok.Getter;importlombok.Setter;©Getter©SetterpublicclassHelloprivateStringname;privateintage;privateStringaddress;publicHello()publicHello(Stringname,intage,Stringaddress)this.name=name;this.age=age;this.address=address;)packagecn.inspur.api.hello.service;importjava.util.ArrayList;importjava.util.List;importjava.util.Random;importorg.springframework.stereotype.Service;importcn.inspur.api.hello.vo.Hello;©ServicepublicclassHeIIoServicepublicList<Hello>query()Randomr=newRandom();1.ist<Hello>list=newArrayList<>();inta=r.nextlnt(2);for(inti=O;i<a;i+)list.add(newHelIo("Jack"+i,i*4,"北京"+i);)returnlist;)packagecn.inspur.api.hello.controller;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importcn.inspur.api.hello.service.HelloService;importcn.inspur.api.hello.vo.Hello;importlombok.extern.slf4j.Slf4j;ReqUeStMaPPing("hellcf)ControllerSlf4jpublicclassHelIoCOntrolIerAutowiredprivateHeIIoServicehelloService;GetMaPPing("hi")publicStringhi(Modelmodel)Zinfo("hello.Hi.");1.ist<Hello>list=helloService.queryO;model.addAttribute("datas"Jist);return"hello/hi")运彳裙果:÷÷C©localhost:8888/hello/hi这是hi页面Name;ageaddressjackof1111辰丁厂I北京IJaCk2I仃漏"Jack312!北京3IJaCk416北京4步5、添加bootstr叩样式1、下载样式文件,>Door-aemodooijaevoosjnspurmaserj>图src/main/javav蝎>srcmainresourcesv£?>staticv£>bootstrap>2>css>>js意jquery.min.js,ViiPminic2、添加静态文件配置packagecn.inspurconfig;importorg.springframework.Contextannotation.Configuration;importorg.springframework.web.servlet.config.annotation.ResourceHandIerRegistry;importorg.springframework.web.servlet.config.annotation.ViewControllerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;©ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer©OverridepublicvoidaddViewControllers(ViewControllerRegistryregistry)registry.addViewController('index").setViewName("index");registry.addViewController(7").setViewName("index");registry.addViewController(",).setViewName("index");)©OverridePUbIiCVOidaddResourceHandlers(ResourceHandlerRegistryregistry)registry.addResourceHandlerC7static*l*).addResourceLocations(dasspath:/StatiC/");3、在页面上引用<(DOCTYPEhtml><htmlXmlnslh="http:WWW.thymeleaf.org”><head><metacharset="UTF-8h><title>Inserttitlehere<title><linkrel="StyZesheeftIype="text/css"th:href="/static/bootstrap/css/bootstrap.min.css*><scripttype="text/javascript"Xsrc="/static/jquery.min.js*><script><head><body><divclass="container<divclass="row"><divclass=col-12>< p>Hello-这页<p>< ahref=Hhello/hiH>Hello/hi<a><div><div><div><body><html>4、查看结果0Inserttitlehere×+÷÷C©IocaIhost:8888/1ndexHeII。-这是主页Hello/hihere×+ IoCalhOSt:8888/hell0/hi列表显示结果NameageaddressJackO0北京OJaCkl4北京1步6、使用vuef11后分离技术展示数据<!D0CTYPEhtml><htmlXmlnslh="http:WWW.thymeleaf.org<head><metacharset="UTF-8><title>Inserttitlehere<title><linkrel="StyZesheeftIype="text/css"th:href="/static/bootstrap/css/bootstrap.min.css*><scripttype="text/javascript"Xsrc=K/static/jquery.min.jsr><script><scripttype="text/javascript"Xsrc="/static/layer/layer.js*><script><scripttype="text/javascript"Xsrc="/static/vue.minjs*><script><head><body><divclass="container"d=napp><h2>message<h2><divclass="row、<divclass=co!-12,>>< buttonclick="add"class=btnbtc-primarybm-sm">增力口</buttOn><buttontype="buttonnclass="btnbtn-infohtn-sm"dick="refresh($event)">刷新<button><div><divclass=Yo-12*><tableclass=ntabletab!e-borded"><thead><tr><th>序号<th><th>Name<th><th>age<th><th>address<th><tr><thead><tbodyv-if=ltIisLlength>0"><trv-for="(h,index)inIisC<td>index+1<td><td>h.name<td><td>h.age<td><td>h.address<td><tr><tbody><tbodyv-else><trstyle="text-aIign:center"><tdcolspan=Z">无数据<td><tr><tbody><table><div><div><divid="acb77V"style="display:none,width:400px'><divclass=containera>Name:<inputtype=*te,f"name="name*v-model=hello.name,><br>Age:<inputtype=Yexfname=¾(7e"v-m0del=nhello.agen><br>Address:<inputtype=TeAf尸name="addressv-model=nhello.address''><bx><inputtype="butto""value=©click=nsavea><div><div><div><body><scripttype=textjavascriptw>S(function()varlayerindex=-1;varapp=newVue(el:"#app",data:message:'使用VUE显示数据',list:,hello:name:'",age:O,address:""),methods:refresh:function(e)oad();,add:function()layerindex=layer.open(type:1,title:"增加,content:$('#addDiv');,save:function()varparam=S.param(app.hello);S.post(7hellosaven,param,function(resp)app.list.push(Object.assign(,resp.data);alert(layerlndex);IayencIose(IayerIndex);););functionload()$.post("/hello/hi2",function(data)app.list=data.data;1.'json");oad(););<script><html>2、使用STS创建SpringBoot项目选择创建SpringStarterProject:NewSpringStarterProjectContactingwebserviceandbuildinguimodel.ServiceURLhttps:/start.spring.ioNocontentavailable.输入项目的GAV:NewSpringStarte