欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

运用springboot搭建并部署web项目的示例

程序员文章站 2023-12-20 21:02:40
前言 一直以来都是用springmvc+mybatis进行后端接口开发工作,最近闲来无事,根据现有功能需求,用springboot+mybatis部署一套简单的web项目...

前言

一直以来都是用springmvc+mybatis进行后端接口开发工作,最近闲来无事,根据现有功能需求,用springboot+mybatis部署一套简单的web项目。

所用工具

  1. intellij idea 2018.1.4
  2. jdk 1.8
  3. apache-tomcat-8.0.50

所解决的问题

1、如何用idea创建springboot项目

2、如何进行 服务器、数据库、mybatis、视图解析器的配置

3、如何使用mybatis generator 自动生成代码

4、如何使用multipart进行文件上传

5、如何运用springboot的事务

6、如何打包进行tomcat部署

运用idea创建springboot项目

1、打开idea,file -> new -> project,选择spring initializr,然后next。

运用springboot搭建并部署web项目的示例

2、修改ariifact,下面的name、package会自动修改;packaging有两种模式,一种是jar,一种是war;因为springboot中自带了tomcat,因此可以将项目打成jar,直接运行;而我现有项目是部署到tomcat上,因此我需要打成war包;然后next。

运用springboot搭建并部署web项目的示例

3、设置项目依赖,然后next ,进入下一页 ,设置project name,点击finish完成。

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

4、进入项目

运用springboot搭建并部署web项目的示例

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">
  <modelversion>4.0.0</modelversion>

  <groupid>com.example</groupid>
  <artifactid>springbootdemo</artifactid>
  <version>0.0.1-snapshot</version>
  <packaging>war</packaging>

  <name>springbootdemo</name>
  <description>demo project for spring boot</description>

  <parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.0.2.release</version>
    <relativepath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-jdbc</artifactid>
    </dependency>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <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>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupid>com.microsoft.sqlserver</groupid>
      <artifactid>mssql-jdbc</artifactid>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework.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>
      <plugin>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-maven-plugin</artifactid>
      </plugin>
    </plugins>
  </build>
</project>

无配置文件的springmvc

通过两个例子:1、http请求访问并渲染页面 2、http请求返回json字符串

-配置数据源、视图渲染

-添加视图渲染pom依赖

-创建welcomecontroller、welcome.jsp

新增之后的项目结构

运用springboot搭建并部署web项目的示例

application.yml 配置数据源 和 视图渲染

# 数据源、视图配置
spring:
 datasource:
   url: jdbc:sqlserver://xx:1433;databasename=xx
   username: xx
   password: xx
   driver-class-name: com.microsoft.sqlserver.jdbc.sqlserverdriver
 mvc:
  view:
   prefix: /web-inf/views/
   suffix: .jsp

pom.xml新增视图渲染依赖

<!-- 使用 jsp 必要依赖 -->
    <dependency>
      <groupid>org.apache.tomcat.embed</groupid>
      <artifactid>tomcat-embed-jasper</artifactid>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupid>javax.servlet</groupid>
      <artifactid>jstl</artifactid>
    </dependency>

创建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.stereotype.controller;
import 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;

@controller
@requestmapping("/welcome")
public class welcomecontroller {
  /**
   * 访问welcome.jsp页面
   * @return
   */
  @requestmapping("welcomeindex")
  public modelandview welcomeindex(){
    modelandview mv = new modelandview();
    mv.setviewname("welcome");
    mv.addobject("name","xx");
    return mv;
  }

  /**
   * 返回json字符串
   * @return
   */
  @requestmapping("getwelcomeinfo")
  @responsebody
  public response getwelcomeinfo(){
    /**
     * 测试数据
     */
    list<welcome> welcomes = new arraylist<>();
    welcome w1 = new welcome();
    w1.setid("1");
    w1.setname("xx1");
    w1.setage(11);
    w1.setgender("女");

    welcome w2 = new welcome();
    w2.setid("2");
    w2.setname("xx2");
    w2.setage(22);
    w2.setgender("男");
    welcomes.add(w1);
    welcomes.add(w2);

    response response = new response();
    response.setdata(welcomes);
    response.setretcode(responsecode.success);
    response.setretdesc("success");
    return response;
  }
}

创建welcome.jsp

<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
  <title>视图渲染</title>
</head>
<body>
  您好,${name}
</body>
</html>

启动项目,并访问

http://localhost:8080/welcome/getwelcomeinfo

http://localhost:8080/welcome/welcomeindex

使用mybatis generator自动生成代码

用于为表创建 *mapper.xml、model、dao文件

在pom.xml 添加mybatis generator 自动生成代码插件

<build>
    <plugins>
      <plugin>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-maven-plugin</artifactid>
      </plugin>
      <!-- mybatis generator 自动生成代码插件 -->
      <plugin>
        <groupid>org.mybatis.generator</groupid>
        <artifactid>mybatis-generator-maven-plugin</artifactid>
        <version>1.3.2</version>
        <configuration>
          <configurationfile>${basedir}/src/main/resources/generator/generatorconfig.xml</configurationfile>
          <overwrite>true</overwrite>
          <verbose>true</verbose>
        </configuration>
      </plugin>
    </plugins>
  </build>

在上面pom.xml配置的pugin路径resources/generator 文件夹下添加generatorconfig.xml

<?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">
<generatorconfiguration>
  <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
  <classpathentry location="c:\users\.m2\repository\com\microsoft\sqlserver\mssql-jdbc\6.2.2.jre8\mssql-jdbc-6.2.2.jre8.jar"/>
  <context id="db2tables" targetruntime="mybatis3">
    <commentgenerator>
      <property name="suppressdate" value="true"/>
      <!-- 是否去除自动生成的注释 true:是 : false:否 -->
      <property name="suppressallcomments" value="true"/>
    </commentgenerator>
    <!--数据库链接url,用户名、密码 -->
    <jdbcconnection driverclass="com.microsoft.sqlserver.jdbc.sqlserverdriver" connectionurl="jdbc:sqlserver://xx:1433;databasename=xx" userid="xx" password="xx">
    </jdbcconnection>
    <javatyperesolver>
      <property name="forcebigdecimals" value="false"/>
    </javatyperesolver>
    <!-- 生成模型的包名和位置-->
    <javamodelgenerator targetpackage="com.example.springbootdemo.entity" targetproject="src/main/java">
      <property name="enablesubpackages" value="true"/>
      <property name="trimstrings" value="true"/>
    </javamodelgenerator>
    <!-- 生成映射文件的包名和位置-->
    <sqlmapgenerator targetpackage="mybatis" targetproject="src/main/resources">
      <property name="enablesubpackages" value="true"/>
    </sqlmapgenerator>
    <!-- 生成dao的包名和位置-->
    <javaclientgenerator type="xmlmapper" targetpackage="com.example.springbootdemo.mapper" targetproject="src/main/java">
      <property name="enablesubpackages" value="true"/>
    </javaclientgenerator>
    <!-- 要生成的表 tablename是数据库中的表名或视图名 domainobjectname是实体类名-->
    <table tablename="xx" domainobjectname="studentbinding" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"></table>
  </context>
</generatorconfiguration>

使用maven中的mybatis-generator:generate根据数据库里面表生产相关的类

edit configurations -> 添加 -> maven

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

 配置mybatis

在application.yml 中添加mybatis的配置

# mybatis配置
mybatis:
 mapper-locations: classpath*:mybatis/*mapper.xml
 type-aliases-package: com.example.springbootdemo.entity

在studentbindingmapper.java中添加 @repository("studentbindingmapper")注解才能使用@mapperscan扫描到

@repository("studentbindingmapper")
public interface studentbindingmapper {}

在springbootdemoapplication.java添加@mapperscan

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, args);
  }
}

添加service、controller层

项目层级

运用springboot搭建并部署web项目的示例

添加studentbindingservice

package com.example.springbootdemo.service;
import com.example.springbootdemo.entity.studentbinding;
import java.util.list;

public interface studentbindingservice {
  int deletebyprimarykey(long id);
  int insert(studentbinding record);
  int insertselective(studentbinding record);
  studentbinding selectbyprimarykey(long id);
  int updatebyprimarykeyselective(studentbinding record);
  int updatebyprimarykey(studentbinding record);
  void validtransaction(long id);
  list<studentbinding> getstudentbindbyquery(studentbinding record);
}

添加studentbindingserviceimpl

package com.example.springbootdemo.service.impl;

import com.example.springbootdemo.entity.studentbinding;
import com.example.springbootdemo.mapper.studentbindingmapper;
import com.example.springbootdemo.service.studentbindingservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import java.util.list;

@service(value = "studentbindingservice")
public class studentbindingserviceimpl implements studentbindingservice {
  @autowired
  private studentbindingmapper studentbindingmapper;

  @override
  public int deletebyprimarykey(long id) {
    return studentbindingmapper.deletebyprimarykey(id);
  }

  @override
  public int insert(studentbinding record) {
    return studentbindingmapper.insert(record);
  }

  @override
  public int insertselective(studentbinding record) {
    return studentbindingmapper.insertselective(record);
  }

  @override
  public studentbinding selectbyprimarykey(long id) {
    return studentbindingmapper.selectbyprimarykey(id);
  }

  @override
  public int updatebyprimarykeyselective(studentbinding record) {
    return studentbindingmapper.updatebyprimarykeyselective(record);
  }

  @override
  public int updatebyprimarykey(studentbinding record) {
    return studentbindingmapper.updatebyprimarykey(record);
  }

  @override
  @transactional
  public void validtransaction(long id){
    // 删除之后,插入该id的数据
    studentbindingmapper.deletebyprimarykey(id);

    studentbinding record = new studentbinding();
    record.setid(id);
    studentbindingmapper.insertselective(record);
  }

  @override
  public list<studentbinding> getstudentbindbyquery(studentbinding record) {
    return studentbindingmapper.getstudentbindbyquery(record);
  }
}

新增studentbindingcontroller

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.stereotype.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.multipart.multipartfile;
import org.springframework.web.servlet.modelandview;
import java.io.file;
import java.io.ioexception;
import java.util.list;

@controller
@requestmapping(value = "/studentbind")
public class studentbindingcontroller {
  @autowired
  private studentbindingservice studentbindingservice;

  /**
   * 根据请求参数,删除绑定学生信息
   * @param id
   * @return
   */
  @requestmapping("deletebyprimarykey")
  @responsebody
  public response deletebyprimarykey(long id){
    response response = new response();
    if(id==null){
      response.setretcode(responsecode.paramarter_error);
      response.setretdesc("参数错误");
      return response;
    }

    try{
      studentbindingservice.deletebyprimarykey(id);
      response.setretcode(responsecode.success);
      response.setretdesc("删除成功");
    }catch (exception e){
      e.printstacktrace();
      response.setretcode(responsecode.failed);
      response.setretdesc("删除异常");
    }
    return response;
  }

  /**
   * 根据请求参数,添加绑定学生信息
   * @param record
   * @return
   */
  @requestmapping("insertselective")
  @responsebody
  public response insertselective(studentbinding record){
    response response = new response();
    if(record==null){
      response.setretcode(responsecode.paramarter_error);
      response.setretdesc("参数错误");
      return response;
    }

    try{
      studentbindingservice.insertselective(record);
      response.setretcode(responsecode.success);
      response.setretdesc("添加成功");
    }catch (exception e){
      e.printstacktrace();
      response.setretcode(responsecode.failed);
      response.setretdesc("添加异常");
    }
    return response;
  }

  /**
   * 根据请求参数,查询绑定学生信息
   * @param id
   * @return
   */
  @requestmapping("selectbyprimarykey")
  @responsebody
  public response selectbyprimarykey(long id){
    response response = new response();
    if(id==null){
      response.setretcode(responsecode.paramarter_error);
      response.setretdesc("参数错误");
      return response;
    }

    try{
      studentbinding studentbinding = studentbindingservice.selectbyprimarykey(id);
      response.setdata(studentbinding);
      response.setretcode(responsecode.success);
      response.setretdesc("查询成功");
    }catch (exception e){
      e.printstacktrace();
      response.setretcode(responsecode.failed);
      response.setretdesc("查询异常");
    }
    return response;
  }

  /**
   * 验证@transaction注解是否好用
   * @param id
   * @return
   */
  @requestmapping("validtransaction")
  @responsebody
  public response validtransaction(long id){
    response response = new response();
    if(id==null){
      response.setretcode(responsecode.paramarter_error);
      response.setretdesc("参数错误");
      return response;
    }

    try{
      studentbindingservice.validtransaction(id);
      response.setretcode(responsecode.success);
    }catch (exception e){
      e.printstacktrace();
      response.setretcode(responsecode.failed);
    }
    return response;
  }

  /**
   * 渲染jsp页面
   * @return
   */
  @requestmapping("welcomeindex")
  public modelandview welcomeindex(){
    list<studentbinding> studentbindings = studentbindingservice.getstudentbindbyquery(new studentbinding());
//    model.addattribute("studentbindings",studentbindings);
    modelandview mv = new modelandview();
    mv.setviewname("welcome");
    mv.addobject("studentbindings",studentbindings);
    return mv;
  }

  /**
   * 跳转到上传文件页面
   * @return
   */
  @requestmapping("multipartindex")
  public string multipartindex(){
    return "multipart-index";
  }

  /**
   * 上传文件到指定目录
   * @param file
   * @return
   */
  @requestmapping("/upload")
  @responsebody
  public response upload(@requestparam("file") multipartfile file){
    response response = new response();
    if (file.isempty()){
      response.setretcode(responsecode.paramarter_error);
      response.setretdesc("参数错误");
      return response;
    }

    try {
      string filepath = "d:\\ceshi\\upload\\";
      file dir = new file(filepath);
      if(!dir.isdirectory()){
        dir.mkdir();
      }

      string fileoriginalname = file.getoriginalfilename();
      file writefile = new file(filepath + fileoriginalname);
      //文件写入磁盘
      file.transferto(writefile);

      response.setretcode(responsecode.success);
      response.setretdesc("上传成功");
    } catch (ioexception e) {
      e.printstacktrace();
      response.setretcode(responsecode.failed);
      response.setretdesc("上传失败");
    }

    return response;
  }
}

重启项目之后,就可以访问各个接口

springboot配置事务

springboot配置事务有两种方式

1、在springbootdemoapplication.java项目入口,添加@enabletransactionmanagement的注解用来开启事务

2、在service实现类上添加@transactional注解,那么该类的所有方法都进行事务管理;也可以直接在service实现类的方法上直接添加@transactional注解,那么只对该方法进行事务管理,上面代码中有对方法添加事务的例子

springboot打包进行tomcat部署

edit configuration -> maven -> 添加 ->启动 -> 复制war包 -> tomcat webapp ->修改war包的名字 -> tomcat bin -> startup.bat

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

运用springboot搭建并部署web项目的示例

tomcat启动之后,访问 http://localhost:8080/springbootdemo/welcome/welcomeindex 进行验证

运用springboot搭建并部署web项目的示例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: