Préface
J'ai toujours utilisé SpringMVC + MyBatis pour développer des interfaces arrière. J'ai été inactif récemment. Selon les exigences fonctionnelles existantes, j'utilise Springboot + MyBatis pour déployer un projet Web simple.
Outils utilisés
Problèmes résolus
1. Comment créer un projet Springboot avec Idea
2. Comment configurer le serveur, la base de données, MyBatis, Afficher l'analyseur
3. Comment utiliser le générateur MyBatis pour générer automatiquement du code
4. Comment utiliser la multipaction pour télécharger des fichiers
5. Comment utiliser les transactions Springboot
6. Comment emballer le déploiement de Tomcat
Utilisez l'idée pour créer un projet Springboot
1. Ouvrez l'idée, le fichier -> nouveau -> Projet, sélectionnez Spring Initializr, puis suivant.
2. Modifier Ariifact, le nom et le package ci-dessous seront automatiquement modifiés; L'emballage a deux modes, l'un est en pot et l'autre est la guerre; Parce que Springboot est livré avec Tomcat, le projet peut être en pot et s'exécuter directement; Bien que mon projet existant soit déployé sur Tomcat, je dois être un package de guerre; Et puis ensuite.
3. Définissez la dépendance du projet, puis ensuite, accédez à la page suivante, définissez le nom du projet et cliquez sur Terminer pour terminer.
4. Entrez le projet
pom.xml
<? xml version = "1.0" Encoding = "utf-8"?> <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"> <modersversion> 4.0.0 </démarforbootDemo </pamplid> <artificactid> SpringbootDemo <version> 0.0.1-snapshot </ version> <packaging> war </packaging> <name> SpringbootDemo </name> <description> Projet de démonstration pour Spring Boot </Scription> <parent> <ProupID> org.springframework.boot </proupId> <Artifactid> Spring-Boot-starter-parent </ Artifactid> <Dudition>> 2.0.2.releas <LelativePath /> <! - Lookup Parent du Repository -> </parent> <Properties> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <project.reporting.outputencoding> utf-8 </project.reporting.outputincing> <Java.version> 1.8 <java. </properties> <Dependces> <Dependency> <ProupId> org.springframework.boot </proncId> <Artifactid> printemps-boot-starter-jdbc </ artifactid> </pedency> <dependency> <prouprid> org.springframework.boot </prounid> <artifactisid> <dependency> <proupId> org.mybatis.spring.boot </proupId> <Artifactid> Mybatis-Spring-Boot-starter </ artifactId> <DERVIRAGE> 1.3.2 </ version> </pedency> <petendency> <proupId> org.springframework.boot </roulid> <ArtifActid> Spring-Boot-Devtools </ GroupId> <ccope> runtime </cope> </dependency> <dependency> <proupId> com.microsoft.sqlserver </rom grouped> <ArtifActid> mssql-jdbc </ artifactid> <ccope> runtime </cope> </pedidency> <dependency> <proupId> org.springFramework. <ArtefactId> printemps-boot-starter-tomcat </retifactid> <ccope> fourni </ccope> </dependency> <dependency> <proupId> org.springframework.boot </rom grouped> <ArtifActid> Spring-Boot-starter-Test </ Artifactid> <Scope> Test </cope> </dependency> <GroupId> org.springframework.boot </prôdId> <ArtefactId> Spring-Boot-Maven-Plugin </ ArfactId> </Glugin> </Glugins> </ Build> </ Project>
Springmvc sans fichier de configuration
Deux exemples: 1. Accès à la demande HTTP et rendu la page 2. La demande HTTP renvoie la chaîne JSON
-Configure la source de données et le rendu
-Add View Rendre les dépendances de POM
-Create WelcomeController, Welcome.jsp
Nouvelle structure de projet
application.yml configurer la source de données et le rendu
# Data Source and View Configuration Spring: DataSource: URL: jdbc: sqlserver: // xx: 1433; databasename = xx username: xx mot de passe: xx driver-class-name: com.microsoft.sqlserver.jdbc.
pom.xml ajoute la dépendance de la vision du rendu
<! - Utiliser JSP nécessite des dépendances -> <dependency> <proupId> org.apache.tomcat.embed </proncId> <Artifactid> tomcat-embed-jasper </ ArtiFactId> <Cope> fournies </cope> </Dedidency> <Dedency> <proupId> javax.servlet </propeD> <ArtifActid> JSTLA </varincy>
Créer un WelcomeController
package com.example.springbootdemo.web; import com.example.springbootdemo.entity.welcome; import com.example.springbootdemo.response.response; import com.example.springbootdemo.response.responsecode; import org.springframework. org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.responsewview; import org.springframework.web.servlet.modelandview; import java.util.arraylist; Importer java.util.List; @ contrôleur @ requestmaping (")") WelcomeController {/ ** * Visitez la page Welcome.jsp * @return * / @RequestMapping ("WelcomeIndex") public ModelAndView WelcomeIndex () {ModelAndView mv = new ModelAndView (); mv.setViewName ("bienvenue"); mv.addObject ("name", "xx"); retour MV; } / ** * RETOUR JSON String * @return * / @RequestMapping ("GetWelcomeInfo") @ResponseBody Public Response getWelcomeInfo () {/ ** * Test Data * / list <leende> welcomes = new ArrayList <> (); Bienvenue w1 = new bienvenue (); w1.setid ("1"); w1.setName ("xx1"); w1.setage (11); w1.setgender ("femme"); Bienvenue w2 = new bienvenue (); w2.setid ("2"); w2.setName ("xx2"); W2.Setage (22); w2.setgender ("mâle"); Welcome.Add (W1); Welcome.Add (W2); Réponse réponse = nouvelle réponse (); Response.setData (Welcome); Response.SetRetcode (ResponseCode.Success); Response.setRetdescs ("Success"); réponse de retour; }}Créer Welcome.jsp
<% @ page ContentType = "Text / Html; charSet = UTF-8" Language = "Java"%> <Html> <A-Head> <Title> Voir le rendu </ title> </ head> <body> Hello, $ {name} </ body> </html>Démarrer le projet et accéder
http: // localhost: 8080 / bienvenue / getwelcomeinfo
http: // localhost: 8080 / welcome / wemeldex
Générer automatiquement du code à l'aide du générateur MyBatis
Utilisé pour créer * mapper.xml, modèle, fichiers DAO pour les tables
Ajouter un générateur MyBatis pour générer automatiquement le plugin de code dans pom.xml
<fuild> <Glugins> <Glugin> <ProupId> org.springframework.boot </proupId> <ArtifactId> Spring-Boot-Maven-Plugin </ Artifactid> </Glugin> <! - MyBatis Generator Generator Plug-In -> <Glugin> <proupId> org.mybatis.Generator </proulid> <ArtefactId> Mybatis-Generator-Maven-Plugin </ ArfactId> <DERVIERNE> 1.3.2 </ Version> <Inconguration> <IcongurationFile> $ {basasedir} /src/main/resources/generator/generatorconfig.xml </FIGIGRAGEFILE> </ Configuration> true </vrowrite> </gingin> </granins> </ build>Ajouter un générateurconfig.xml dans le dossier Ressources / générateur configuré dans le pom.xml ci-dessus
<? xml version = "1.0" Encoding = "UTF-8"?> <! Doctype GeneratorConfiguration public "- // Mybatis.org//dtd Mybatis Generator Configuration 1.0 // en" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <GeneratorConcure> <! - Database Driver: Sélectionnez le package de pilotes de base de données sur votre disque dur local -> <classpathentry location = "c: /users/.m2/repository/com/microsoft/sqlserver/mssql-jdbc/6.2.2.jre8/mssql-jdbc-6.2.2.jre8.jar" / TargetRuntime = "mybatis3"> <commentgenerator> <propriété name = "suppressDate" value = "true" /> <! - Que ce soit pour supprimer les commentaires générés automatiquement true: oui: false: non -> <propriété name = "supressallcomments" value = "true" /> </ commentgenerator> <! - Database link url, username, mot de passe -> <jdbconnection DriverClass = "com.microsoft.sqlserver.jdbc.sqlServerDriver" ConnectionUrl = "jdbc: sqlServer: // xx: 1433; databasename = xx" userrid = "xx" mot de passe = "xx"> </ jdbcconnection> <javatyperesolver value = "false" /> </ javatyperesolver> <! - Générer le nom et l'emplacement du package du modèle -> <javamodelgenerator targetpackage = "com.example.springbootdemo.entity" cibleProject = "src / main / java"> <propriété name = "permette </ javamodelGenerator> <! - Générer le nom du package et l'emplacement du fichier de mappage -> <SqlMapGenerator TargetPackage = "MyBatis" TargetProject = "Src / Main / Resources"> <propriété Name = "ActiveBpackages" Value = "True" /> </ sqlmapGenerator> <! - Générat Nom et Location du pack type = "xmlmapper" ciblePackage = "com.example.springbootdemo.mapper" targetproject = "src / main / java"> <propriété name = "activeubpackages" value = "true" /> </ javaclientGenerator> <! - Le tableau à générer est le nom de la table dans la database ou le nom de la vue DomainObjectn, le nom de la Table TableName = "xx" domainObjectName = "StudentBinding" aperçuCountByExample = "false" activerupDateByExample = "false" ENTIVEDELETEBYEXample = "false" ActiveDelectByExample = "false" SelectByExampeReryId = "false"> </ Table> </ftexed> </preeatorConfiguration>
Utilisez MyBatis-Generator: Générer dans Maven pour produire des classes connexes en fonction des tables de la base de données
Modifier les configurations -> add -> maven
Configurer Mybatis
Ajouter la configuration de MyBatis dans Application.yml
# MyBatis Configuration MyBatis: Mappen-Locations: ClassPath *: Mybatis / * mapper.xml type-aliases-package: com.example.springbootdemo.entity
Ajouter @Repository ("StudentBindingMapper") Annotation dans StudentBindingMapper.java pour scanner vers
@Repository ("StudentBindingMapper") Interface publique StudentBindingMapper {}Ajouter @mapperscan dans SpringbootdemoApplication.java
package com.example.springbootdemo; import org.mybatis.spring.annotation.mapperscan; import org.springframework.boot.springApplication; import; org.springframework.boot.autoconfigure.springbootapplication; @ SpringbootApplication @ MAPPERSCAN ("com.example.springbootdemo.mapper") Public Class SpringbootDemoApplication (Public Static Void Main (String [] Args) {SpringApplication.Run (SpringbootDemoApplication.class); }}Ajouter des couches de service et de contrôleur
Niveau du projet
Ajouter StudentBindingService
package com.example.springbootdemo.service; import com.example.springbootdemo.entity.studentbinding; import java.util.list; interface publique StudentBindingService {int deleteByprimaryKey (long id); INT INSERT (StudentBinding Record); int InteserSelective (dossier d'étudiant); StudentBinding SelectByPrimaryKey (Long ID); int updateByPrimaryKeySelective (dossier d'étudiant); int updateByPrimaryKey (StudentBinding Record); vide validtransaction (ID long); Liste <StudentBinding> GetStudentBindByQuery (dossier d'étudiant);}Ajouter StudentBindingServiceImpl
package com.example.springbootdemo.service.impl; import com.example.springbootdemo.entity.studentbinding; import com.example.springbootdemo.mapper.studentbindingmapper; import com.example.springbootdemo.service.studentbindingsservice; import; org.springframework.beans.factory.annotation.autowired; import org.springframework.sterreotype.service; import org.springframework.transaction.annotation.transactional; import java.util.list; @service (value = studentbindingService ") classe publique StudentBinDingSending @Autowired Private StudentBindingMapper StudentBindingMapper; @Override public int DeleteByPrimaryKey (Long ID) {return StudentBindingMapper.DeleteByPrimaryKey (ID); } @Override public int insert (StudentBinding Record) {return StudentBindingMapper.insert (disque); } @Override public int insertSelective (StudentBinding Record) {return StudentBindingMapper.InsertSelective (enregistrement); } @Override public StudentBinding SelectByPrimaryKey (Long ID) {return StudentBindingMapper.SelectByPrimaryKey (ID); } @Override public int updateByPrimaryKeySelective (StudentBinding Record) {return StudentBindingMapper.UpdateByPrimaryKeySelective (enregistrement); } @Override public int updateByPrimaryKey (StudentBinding Record) {return StudentBindingMapper.UpDateByPrimaryKey (enregistrement); } @Override @Transactional public void validTransaction (Long ID) {// Après suppression, insérez les données de l'ID StudentBindingMapper.DeleteByPrimaryKey (ID); StudentBinding Record = new StudentBinding (); record.setid (id); StudentBindingMapper.InsertSelective (enregistrement); } @Override Public List <StudentBinding> GetStudentBindByQuery (StudentBinding Record) {return StudentBindingMapper.getStudentBindByQuery (enregistrement); }}Ajout d'étudiantbindingController
package com.example.springbootdemo.web; import com.example.springbootdemo.entity.studentbinding; import com.example.springbootdemo.response.response; import com.example.springbootdemo.response.responseCode; import. com.example.springbootdemo.service.studentbindingService; import org.springframework.beans.factory.annotation.autowired; import org.springframework.sterreotype.controller; import org.springframework.web.bind.annotation.requestMapping; import; org.springframework.web.bind.annotation.requestParam; import org.springframework.web.bind.annotation.responsebody; Import org.springframework.web.multing.multuparlandVile; java.io.ioException; import java.util.list; @ contrôleur @ requestmapping (value = "/ studentbind") public class StudentBindingController {@autowired private StudentBindingService StudentBindingService; / ** * Supprimer les informations des élèves liés en fonction des paramètres de demande * @param id * @return * / @requestmapping ("DeleteByprimaryKey") @ResponseBody Public Response DeleteByPrimaryKey (Long ID) {réponse réponse = nouvelle réponse (); if (id == null) {réponse.setRetcode (ResponseCode.ParamARTER_ERROR); Response.SetRetDesc ("Erreur de paramètre"); réponse de retour; } essayez {StudentBindingService.DeleteByPrimaryKey (id); Response.SetRetcode (ResponseCode.Success); Response.SetTredScsc ("DeleteSuccess"); } catch (exception e) {e.printStackTrace (); Response.SetRetcode (ResponseCode.failed); Response.SetRetDesc ("DeleteException"); } Retour Response; } / ** * Ajouter des informations sur les étudiants liés en fonction des paramètres de demande * @param enregistre * @return * / @requestmapping ("insertSelective") @ResponseBody Public Response InsèreSelective (StudentBinding Record) {Response Response = new Response (); if (enregistre == null) {réponse.setReTcode (ResponseCode.ParamARTER_ERROR); Response.SetRetDesc ("Erreur de paramètre"); réponse de retour; } essayez {StudentBindingService.InsertSelective (enregistrement); Response.SetRetcode (ResponseCode.Success); Response.SetRetDesc ("Ajouter un succès"); } catch (exception e) {e.printStackTrace (); Response.SetRetcode (ResponseCode.failed); réponse.setRetDesc ("Ajouter une exception"); } Retour Response; } / ** * Selon les paramètres de demande, interrogez les informations de l'élève lié * @param id * @return * / @RequestMapping ("selectByPrimaryKey") @ResponseBody Réponse publique selectByPrimaryKey (Long ID) {réponse réponse = nouvelle réponse (); if (id == null) {réponse.setRetcode (ResponseCode.ParamARTER_ERROR); Response.SetRetDesc ("Erreur de paramètre"); réponse de retour; } essayez {StudentBinding StudentBinding = StudentBindingService.SelectByprimaryKey (id); Response.SetData (StudentBinding); Response.SetRetcode (ResponseCode.Success); Response.SetTredScsc ("Succès de la requête"); } catch (exception e) {e.printStackTrace (); Response.SetRetcode (ResponseCode.failed); Response.SetRetDesc ("Exception de requête"); } Retour Response; } / ** * Vérifiez si l'annotation @Transaction est facile à utiliser * @param id * @return * / @requestmapping ("validTransaction") @ResponseBody Réponse publique ValidTransaction (Long ID) {réponse réponse = nouvelle réponse (); if (id == null) {réponse.setRetcode (ResponseCode.ParamARTER_ERROR); Response.SetRetDesc ("Erreur de paramètre"); réponse de retour; } essayez {StudentBindingService.validTransaction (id); Response.SetRetcode (ResponseCode.Success); } catch (exception e) {e.printStackTrace (); Response.SetRetcode (ResponseCode.failed); } Retour Response; } / ** * Render la page JSP * @return * / @RequestMapping ("WelcomeIndex") Public ModelandView WelcomeIndex () {List <StudentBinding> StudentBindings = StudentBinDingService.getStudentBindbyQuery (New StudentBinding ()); // Model.AddAtTrribute ("StudentBindings", StudentBindings); ModelAndView mv = new ModelAndView (); mv.setViewName ("bienvenue"); MV.AddObject ("StudentBindings", StudentBindings); retour MV; } / ** * SUPPORT pour télécharger la page de fichier * @return * / @RequestMapping ("MultiparTAnTindex") Public String MultipartIndex () {return "multipart-index"; } / ** * Téléchargez le fichier dans le répertoire spécifié * @param fichier * @return * / @requestmapping ("/ upload") @ResponseBody Public Response upload (@RequestParam ("fichier") Fichier multipartFile) {réponse réponse = nouvelle réponse (); if (file.isempty ()) {réponse.SetTreTcode (ResponseCode.ParamARTER_ERROR); Response.SetRetDesc ("Erreur de paramètre"); réponse de retour; } essayez {string filepath = "d: // ceshi // upload //"; File dir = nouveau fichier (filepath); if (! dir.isdirectory ()) {dir.mkdir (); } String FileOriginalName = file.getoriginalFileName (); File writefile = new File (filepath + fileoriginalName); // Écrivez le fichier sur disque file.transferto (writeFile); Response.SetRetcode (ResponseCode.Success); Response.SetRetDesc ("Téléchargé avec succès"); } catch (ioException e) {e.printStackTrace (); Response.SetRetcode (ResponseCode.failed); Response.SetTredScsc ("Échec du téléchargement"); } Retour Response; }}Après avoir redémarré le projet, vous pouvez accéder à diverses interfaces
Transactions de configuration de Springboot
Il existe deux façons de configurer les transactions à Springboot
1. Dans l'entrée du projet SpringbootDemoApplication.Java, ajoutez l'annotation @enabletransactionManagement pour démarrer la transaction
2. Ajouter une annotation @transactionnelle à la classe d'implémentation du service, alors toutes les méthodes de la classe sont gérées par le biais de transactions; Vous pouvez également ajouter directement @Transactional Annotation aux méthodes de classe d'implémentation de service, alors seule la gestion des transactions est effectuée sur cette méthode. Il existe des exemples d'ajout de transactions aux méthodes dans le code ci-dessus.
Package Springboot pour le déploiement Tomcat
Modifier la configuration -> maven -> add -> Démarrer -> Copiez le package de guerre -> Tomcat WebApp -> Modifier le nom du package de guerre -> Tomcat bin -> startup.bat
Après le démarrage de Tomcat, visitez http: // localhost: 8080 / SpringbootDemo / Welcome / WelcomeIndex pour la vérification
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.