Prefacio
Siempre he usado SpringMVC+MyBatis para desarrollar interfaces de fondo. He estado inactivo recientemente. De acuerdo con los requisitos funcionales existentes, uso SpringBoot+MyBatis para implementar un proyecto web simple.
Herramientas utilizadas
Problemas resueltos
1. Cómo crear un proyecto Springboot con idea
2. Cómo configurar servidor, base de datos, mybatis, ver analizador
3. Cómo usar el generador MyBatis para generar automáticamente el código
4. Cómo usar multipart para cargar archivos
5. Cómo usar transacciones SpringBoot
6. Cómo empaquetar la implementación de Tomcat
Use la idea para crear el proyecto SpringBoot
1. Abra la idea, archivo -> nuevo -> proyecto, seleccione Spring Initializr y luego Siguiente.
2. Modificar Ariifact, el nombre y el paquete a continuación se modificarán automáticamente; El embalaje tiene dos modos, uno es jar y el otro es la guerra; Debido a que Springboot viene con Tomcat, el proyecto puede ser JAR y ejecutar directamente; Si bien mi proyecto existente se implementa en Tomcat, necesito ser un paquete de guerra; Y luego a continuación.
3. Establezca la dependencia del proyecto, luego, vaya a la página siguiente, establezca el nombre del proyecto y haga clic en Finalizar para finalizar.
4. Ingrese el proyecto
pom.xml
<? xml versión = "1.0" encoding = "utf-8"?> <Project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschemainstance" xsi: schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion> 4.0.0 </modelversion> <MoupRoupid> com.example </groupid> <artifactid> <versión> 0.0.1-snapshot </versión> <compagument> war </packaging> <name> springBootDemo </name> <scuidt> Proyecto de demostración para el arranque de primavera </scription> <Parent> <MoupRupid> org.springframework.boot </groupId> <ArtifactId> spring-boot-starter-parent </artifactid> <version> 2.0.2. <RelativePath/> <!-Búsqueda de padres desde el repositorio-> </parent> <properties> <proyect.build.sourceEncoding> UTF-8 </project.build.sourceEncoding> <jection.rePorting.outputEncoding> UTF-8 </project.Reporting.outputenCoding> <Java.Version> </propiedades> <pendencies> <spendency> <uproupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-jdbc </artifactid> </dependency> <pendency> <proupid> org.springFrame.Boot </groupid> <artifactid> spring-boot-sharter-web </artid-web </artid-web </arthamework> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <cope> runtime </cope> </pepertency> <epardency> <uproupid> com.microsoft.sqlserver </groupid> <artifactid> mssql-jdbc </artifactid> <apope> runtime </cope> </dependency> <epardency> <proupid> org.spreingframework.boot </groupid> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <MoupRid> org.springframework.boot </groupid> <artifactID> spring-boot-saven-plugin </arfactid> </glugin> </glugins> </stract> </proyecto>
SpringMVC sin archivo de configuración
Dos ejemplos: 1. HTTP Solicitar acceso y representar la página 2. La solicitud HTTP devuelve la cadena JSON
-Configurar la fuente de datos y la representación de la vista
-Agente Vista de presentación de dependencias de POM
-Create welcomecontroller, bevie.jsp
Nueva estructura de proyecto
Application.yml Configurar la fuente de datos y la representación de la vista
# Fuente de datos y vista Configuración Spring: DataSource: URL: JDBC: SQLServer: // xx: 1433; DatabAsename = xx UserName: XX Password: XX Driver-Class-Name: com.microsoft.sqlserver.jdbc.sqlSerVerDriver mvc: View: View: PREFIX:/Web-inf/Views/SUFTF/VEAD
pom.xml agrega la dependencia de la representación de la vista
<
Crear un bienvenido Welcomecontroller
paquete com.example.springbootdemo.web; import com.example.springbootdemo.entity.welcome; import com.example.springbootdemo.response.esponse; import com.example.springbootdemo.response.Responsecode org.springframework.web.bind.annotation.requestMapping; import org.springframework.web.bind.annotation.responseBody; import org.springframework.web.servlet.modelandview; import java.util.arraylist; import java.util.list;@controlador@controlador@controlador@controlador (" WELCOMECONTROLLER { / *** Visite Welcome.jsp Page* @return* / @RequestMapping ("Welcomeindex") public ModelAndView WelcomeIndex () {ModelAndView mv = new ModelAndView (); MV.SetViewName ("Bienvenido"); mv.addoBject ("nombre", "xx"); regresar MV; } / *** return json cadena* @return* / @requestmapping ("getWelcomeInfo") @ResponseBody Respuesta pública getWelcomeInfo () { / *** Test Data* / List <Welcome> Welcules = new ArrayList <> (); Bienvenido w1 = new Welcome (); w1.setId ("1"); w1.setName ("xx1"); W1.Setage (11); w1.setgender ("mujer"); Bienvenido w2 = new Welcome (); w2.setid ("2"); w2.setName ("xx2"); W2.Setage (22); w2.setgender ("hombre"); breve.Add (W1); breve.Add (W2); Respuesta de respuesta = nueva respuesta (); Response.setData (bienvenido); Response.SetRetCode (ResponseCode.Success); respuesta.setRetDesc ("éxito"); Respuesta de retorno; }}Crear bienvenido.jsp
< %@ página contentType = "text/html; charset = utf-8" lenguaje = "java" %> <html> <fead> <title> Ver Rendering </title> </head> <body> hello, $ {name} </body> </html>>Iniciar el proyecto y el acceso
http: // localhost: 8080/bienvenido/getwelcomeInfo
http: // localhost: 8080/bienvenido/welcomeindex
Genere automáticamente código usando el generador mybatis
Se usa para crear *mapper.xml, modelo, archivos DAO para tablas
Agregue el generador MyBatis para generar automáticamente el complemento de código en pom.xml
<DIARD> <GULTINS> <GLEGIN> <MOUMPROUD> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> </glugin> <!-MyBatis Generator Generación automáticamente complementada de código-> <glugin> <grupo> org.mybatis.generator </groupid> <AtifactId> myBatis-Generator-Maven-Plugin </artifactid> <versión> 1.3.2 </versión> <necuteation> <ConfigurationFile> $ {Basedir} /src/main/resources/generator/generatorConfig.xml </glugin> </glugins> </build>Agregue generadorconfig.xml en la carpeta de recursos/generador configurada en el pom.xml anterior
<? xml versión = "1.0" encoding = "utf-8"?> <! DOCTYPE GeneratorConfiguration public "-// mybatis.org//dtd Configuración del generador de MyBatis 1.0 // en" "http://mybatis.org/dtd/mybatis-Generator-config_1_0.dtdd" <200 * TargetRuntime = "MyBatis3"> <CommentGenerator> <Property name = "supressDate" value = "true"/> <!-si eliminar los comentarios generados automáticamente True: sí: falso: no-> <propiedad name = "supressallComments" value = "true"/> </commentGenerator> <!-Link de base de datos url, nombre de usuario, contraseña-> <jdbcconnectionnectionnection conductClass = "com.microsoft.sqlserver.jdbc.sqlserverdriver" conectionUrl = "jdbc: sqlserver: // xx: 1433; dataBASEname = xx" userId = "xx" contraseña = "xx"> </jdbcconnection> <javatyperesOlver> <product namei "ForceSe value="false"/> </javaTypeResolver> <!-- Generate model package name and location--> <javaModelGenerator targetPackage="com.example.springbootdemo.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-Genere el nombre del paquete y la ubicación del archivo de asignación-> <sqlMapGenerator TargetPackage = "myBatis" TargetProject = "Src/Main/Recursos"> <Property Name = "en ABABLEUBPACKAGES" Value = "True"/> </sqlMapGenerator> <!-Generate de la ubicación del paquete y la ubicación de Dao-> <JAVACLENTENA type="XMLMAPPER" targetPackage="com.example.springbootdemo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- The table to be generated is the table name in the database or the view name domainObjectName is the entity class name--> <table tableName = "xx" domaineObjectName = "StudentBinding" EnableCountByExample = "False" EnableUpdateByExample = "False" EndableLeteByExample = "false" habildByExample = "false" selectbyExampleId = "false"> </xtual> </textute> </generadorconfiguración>
Use myBatis-Generator: Genere en Maven para producir clases relacionadas basadas en las tablas de la base de datos
Editar configuraciones -> Agregar -> Maven
Configurar mybatis
Agregue la configuración de MyBatis en Application.yml
# Configuración de MyBatis MyBatis: Mapper-Locations: classpath*: mybatis/*mapper.xml type-aliases-package: com.example.springbootdemo.entity
Agregar @Repository ("StudentBindingMapper") Anotación en StudentBindingMapper.java para escanear
@Repository ("StudentBindingMapper") Interfaz pública de StudentBindingMapper {}Agregar @mapperscan en springbootdemoapplication.java
paquete com.example.springbootdemo; import org.mybatis.spring.annotation.mapperscan; import org.springframework.boot.springapplication; importar; org.springframework.boot.autoconfigure.springbootapplication;@springbootapplication@mapperscan ("com.example.springbootdemo.mapper") clase pública springbootdemoapplication {public static void main (string [] args) {springapplication.raN (springBootDemoApplication. }}Agregar servicio y capas de controlador
Nivel de proyecto
Agregue StudentBindingService
paquete com.example.springbootdemo.service; import com.example.springbootdemo.entity.studentbinding; import java.util.list; interfaz pública StudentBindingService {int deletebyprimarykey (ID larga); int Insert (Registro de Binding Student); int Insertselective (Registro de Binding Student); StudentBinding SelectByPrimaryKey (ID largo); int uplyByPrimaryKeySelective (Registro de Binding Student); int uplyByPrimaryKey (Registro de Binding Student); void ValidTransaction (ID largo); Lista <SentralBinding> GetStudentBindByQuery (Registro de Estudiantilios);}Agregar StudentBindingServiceImpl
paquete com.example.springbootdemo.service.impl; import com.example.springbootdemo.entity.studentbinding; import org.springframework.beans.factory.annotation.aUtowired; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.transactional; import java.util.list; @Service (valor = "estudiante Bindingservice") @AUTOWIREDIREDIRDREDIREDIRD PINDINGMAPPER ESTUDIANTEBINDINGMAPER; @Override public int DeleteByPrimaryKey (Long ID) {return StudentBindingMapper.DeleteByPrimaryKey (id); } @Override public int Insert (StudentBinding Record) {return StudentBindingMapper.insert (registro); } @Override public int InsertSelective (Registro de Estudiantilingsbinding) {return StudentBindingMapper.insertSelective (registro); } @Override Public StudentBinding SelectByPrimaryKey (Long ID) {return StudentBindingMapper.SelectByPrimaryKey (id); } @Override public int UpdateByPrimaryKeySelective (Registro de Estudiantes de Binding) {return StudentBindingMapper.UpdateByPrimaryKeySelective (registro); } @Override public int UpdateByPrimaryKey (Registro de Estudiantilios) {return StudentBindingMapper.UpdateByPrimaryKey (registro); } @Override @Transactional public void ValidTransaction (Long ID) {// Después de la eliminación, inserte los datos de ID StudentBindingMapper.DeleteByPrimaryKey (id); EstudentBinding Record = New StudentBinding (); registro.setId (id); StudentBindingMapper.insertSelective (registro); } @Override Public List <SentordBinding> GetStudentBindByQuery (Registro de Binding Student) {return StudentBindingMapper.getStudentBindByQuery (registro); }}Se agregó StudentBindingController
paquete 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.stereotype.controller; import org.springfframework.web.bind.annotation.requestmapping; importación org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responseBody; import org.springframework.web.multipart.multipartfile; import. java.io.ioException; import java.util.list;@controlador@requestmapping (valor = "/studentbind") public class StudentBindingController {@aUtowired student student bindingservice studentBindingService; / ** * Eliminar la información de alumno vinculada de acuerdo con los parámetros de solicitud * @param id * @return */ @requestmapping ("deletybyprimarykey") @ResponseBody Respuesta pública deletyprimarykey (ID larga) {respuesta respuesta = nueva respuesta (); if (id == null) {Response.SetRetCode (ResponseCode.Paramarter_error); Response.SetRetDesc ("Error de parámetro"); Respuesta de retorno; } try {StudentBindingService.DeleteByPrimaryKey (id); Response.SetRetCode (ResponseCode.Success); respuesta.setRetDesc ("DeleteSuccess"); } catch (Exception e) {E.PrintStackTrace (); Response.SetRetCode (ResponseCode.Failed); respuesta.setRetDesc ("DeleteException"); } Respuesta de retorno; } / ** * Agregue información de alumno vinculada de acuerdo con los parámetros de solicitud * @param registro * @return * / @RequestMapping ("insertSelective") @ResponseBody Respuesta pública Insertselective (StudentBinding Record) {Respuesta de respuesta = nueva respuesta (); if (registro == null) {Response.SetRetCode (ResponseCode.Paramarter_Error); Response.SetRetDesc ("Error de parámetro"); Respuesta de retorno; } try {StudentBindingService.insertSelective (registro); Response.SetRetCode (ResponseCode.Success); respuesta.setRetDesc ("Agregar éxito"); } catch (Exception e) {E.PrintStackTrace (); Response.SetRetCode (ResponseCode.Failed); Response.SetRetDesc ("Agregar excepción"); } Respuesta de retorno; } / ** * Según los parámetros de solicitud, consulte la información de estudiante encuadernada * @param id * @return * / @requestmapping ("selectByPrimaryKey") @ResponseBody Respuesta pública SelectByPrimaryKey (Long ID) {Respuesta de respuesta = nueva respuesta (); if (id == null) {Response.SetRetCode (ResponseCode.Paramarter_error); Response.SetRetDesc ("Error de parámetro"); Respuesta de retorno; } try {StudentBinding StudentBinding = StudentBindingService.SelectbyPrimaryKey (id); Response.setData (StudentBinding); Response.SetRetCode (ResponseCode.Success); Response.setRetDesc ("éxito de consulta"); } catch (Exception e) {E.PrintStackTrace (); Response.SetRetCode (ResponseCode.Failed); Response.SetRetDesc ("Excepción de consulta"); } Respuesta de retorno; } / ** * Verifique si la anotación @Transaction es fácil de usar * @param id * @return * / @RequestMapping ("ValidTransaction") @ResponseBody Public Respuesta ValidTransaction (ID larga) {Respuesta respuesta = nueva respuesta (); if (id == null) {Response.SetRetCode (ResponseCode.Paramarter_error); Response.SetRetDesc ("Error de parámetro"); Respuesta de retorno; } try {StudentBindingService.ValidTransaction (id); Response.SetRetCode (ResponseCode.Success); } catch (Exception e) {E.PrintStackTrace (); Response.SetRetCode (ResponseCode.Failed); } Respuesta de retorno; }/ *** Render JSP Página* @return*/ @RequestMapping ("Welcomeindex") public ModelAndView Welcomeindex () {list <SentorDebinding> StudentBindings = StudentBindingService.getStudentBindByQuery (new StudentBinding ()); // Model.addattribute ("StudentBindings", StudentBindings); ModelandView mv = new ModelAndView (); MV.SetViewName ("Bienvenido"); MV.AddoBject ("StudentBindings", StudentBindings); regresar MV; } / *** Jump para cargar la página del archivo* @return* / @RequestMapping ("multipartIndex") public string multipartIndex () {return "multipart-index"; }/** * Sube el archivo en el directorio especificado * @param archivo * @return */@RequestMapping ("/upload") @ResponseBody Public Response upload (@RequestParam ("Archivo") File multipartfile) {respuesta respuesta = nueva respuesta (); if (file.isEmpty ()) {Response.SetRetCode (ResponseCode.ParAMARTER_ERROR); Response.SetRetDesc ("Error de parámetro"); Respuesta de retorno; } try {String filePath = "d: // ceshi // upload //"; Archivo dir = nuevo archivo (filepath); if (! dir.isDirectory ()) {dir.mkdir (); } Cadena fileOriginalName = file.getOriginalFileName (); Archivo writeFile = nuevo archivo (filePath + fileOriginalName); // Escribir el archivo en disco File.transferto (WriteFile); Response.SetRetCode (ResponseCode.Success); Respuesta.SetRetDesc ("cargado con éxito"); } catch (ioException e) {E.PrintStackTrace (); Response.SetRetCode (ResponseCode.Failed); Respuesta.SetRetDesc ("Cargar fallido"); } Respuesta de retorno; }}Después de reiniciar el proyecto, puede acceder a varias interfaces
Transacciones de configuración de SpringBoot
Hay dos formas de configurar las transacciones en Springboot
1. En la entrada del proyecto SpringBootDemoApplication.Java, agregue la anotación @EnabletransactionManagement para comenzar la transacción
2. Agregar anotación @Transactional a la clase de implementación del servicio, entonces todos los métodos de la clase se administran a través de transacciones; También puede agregar directamente la anotación @Transactional a los métodos de clase de implementación del servicio, entonces solo se realiza la gestión de transacciones en este método. Hay ejemplos de agregar transacciones a los métodos en el código anterior.
Paquete SpringBoot para la implementación de Tomcat
Editar configuración -> Maven -> Agregar -> Inicio -> Copie el paquete de guerra -> Tomcat WebApp -> Modifique el nombre del paquete de guerra -> Tomcat bin -> startup.bat
Después de comenzar Tomcat, visite http: // localhost: 8080/springbootdemo/welcome/welcomeindex para verificación
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.