3.elm Springboot 完善

8.28 emlboot

创建后台项目

创建spring boot项目

只选这两个就可以。


image.png

如果网速太慢,下载不出来,在setting里调整一下maven。(创建springboot教程里有)

pom里引进依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
springboot配置文件:application.properties
#更改端口号:
#server.port=8089

#配置上下文的路径
server.servlet.context-path=/elm

#连接数据库:用spring提供的工具 不需要配置
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/elm?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username = root
spring.datasource.password = root

#扫描mapper下所有因发射文件
mybatis.mapper-locations=classpath:mapper/*.xml
#起路径的别名
mybatis.type-aliases-package=com.foreknow.elmboot.po

#在控制台显示执行的sql
logging.level.org.springframework=debug
logging.level.com.foreknow.elmboot.mapper=debug
跨域的配置文件:WebMvcConfig

解决前后端跨域问题,直接拿来用

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                /*
                 * addMapping:配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。
                 * allowedMethods:允许的请求方式,如:POST、GET、PUT、DELETE等。
                 * allowedOrigins:允许访问的url,可以固定单条或者多条内容,如:"http://www.baidu.com"。前台接口
                 * allowedHeaders:允许的请求header,可以自定义设置任意请求头信息。
                 * maxAge:配置预检请求的有效时间
                 */
                registry.addMapping("/**")
                        //前端端口号
                        .allowedOrigins("http://localhost:8081")
                        .allowCredentials(true)
                        .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                        .allowedHeaders("*")
                        .maxAge(36000);
            }
        };
    }
}
简单的单表操作时,dao层的写法:以Business表为例

可以写映射文件mapper,直接在接口的方法上,用注解的方法写sql

package com.foreknow.elmboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.foreknow.elmboot.po.Business;

@Mapper
public interface BusinessMapper {

    @Select("select * from business where orderTypeId=#{orderTypeId} order by businessId")
    public List<Business> listBusinessByOrderTypeId(Integer orderTypeId);

    @Select("select * from business where businessId=#{businessId}")
    public Business getBusinessById(Integer businessId);
}
service

应为现在还没有什么业务,所以service和dao差不多

controller

controller里要从前台获取到参数,有两种方法

  • 第一种:老师的方法
    直接把参数用对象的方式传过来
import com.foreknow.elmboot.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/BusinessController")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @RequestMapping("/listBusinessByOrderTypeId")
    public List<Business> listBusinessByOrderTypeId(Business business) throws Exception{
        return businessService.listBusinessByOrderTypeId(business.getOrderTypeId());
    }
}
  • 第二种:@RequestParam
    把前台传过来的参数,以注解@RequestParam赋值给不同名字的参数orderTypeId,之所以要改成这个名字,是因为要和bean里的属性名字保持一致。


    image.png

    写法

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/BusinessController")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @RequestMapping("/listBusinessByOrderTypeId")
    public List<Business> listBusinessByOrderTypeId(@RequestParam(required=false)Integer orderTypeId, Model model) throws Exception{
        return businessService.listBusinessByOrderTypeId(orderTypeId);
    }
}

注解@RequestParam的语法:


语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
 
value:参数名
 
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
 
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
传递参数

前台向后台传递参数,前台使用的方法是qs提供的插件序列化传递,序列化的传递方式是类似于
userId=1&passworld=123456
这种名值对的模式。
而后台获取的方式是以key和value的方式,servlet里request.getParameter获取,现在spring给封装起来了,不需要再调用这个方法。前台定义对象的话,属性要和后台Bean里的属性名字相同,之后前台直接向后台传对象,后台就能获取到参数了。

前台定义的属性:
image.png

bean里定义的属性:
image.png

前台调用方法并传递参数:
image.png

controller里定义的方法:
image.png
多表

购物车表与商家id和食品id是多对一的关系,在bean里的表现方法不变,但在持久层会有一些变化,以前会写很多东西,现在单表操作的方法可以直接用注解,而多表操作的方法可以在映射mapper文件夹里进行映射。
持久层接口中:

@Mapper
public interface CartMapper {
    /**
     *查询购物车信息
     * @param cart
     * @return
     */
    public List<Cart> listCart(Cart cart);

    /**
     * 添加购物车
     * @param cart
     * @return
     */
    @Insert("insert into cart(foodId,businessId,userId,quantity) values(#{foodId},#{businessId},#{userId},1)")
    public int saveCart(Cart cart);

    @Update("update cart set quantity=#{quantity} where foodId=#{foodId} and businessId=#{businessId} and userId=#{userId}")
    public int updateCart(Cart cart);

    /**
     * 删除购物车
     * @param cart
     * @return
     */
    public int removeCart(Cart cart);

}

映射文件:
和以前写的方法不同,这词用的分步查询,老师的教程:https://www.jianshu.com/p/78261df9daea
不需要再用数据库的属性名和bean的属性一一关联,可以分步查询,直接用属性select等这种属性名直接关联到其他持久层的方法上。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.foreknow.elmboot.mapper.CartMapper">
    <select id="listCart" resultMap="cartInfoMap" parameterType="com.foreknow.elmboot.po.Cart">
        select * from cart
        <where>
            userId=#{userId}
            <if test="businessId!=null and businessId!='' ">
                and businessId=#{businessId}
            </if>
        </where>
    </select>
    
    <resultMap id="cartInfoMap" type="com.foreknow.elmboot.po.Cart">
        <result column="cartId" property="cartId"/>
        <result column="foodId" property="foodId"/>
        <result column="businessId" property="businessId"/>
        <result column="userId" property="userId"/>
        <result column="quantity" property="quantity"/>

        <association property="food" column="foodId"
                     select="com.foreknow.elmboot.mapper.FoodMapper.getFoodById" />
        <association property="business" column="businessId"
                     select="com.foreknow.elmboot.mapper.BusinessMapper.getBusinessById" />
    </resultMap>


    <delete id="removeCart" parameterType="com.foreknow.elmboot.po.Cart">
        delete from cart
        <where>
            userId=#{userId} and businessId=#{businessId}
            <if test="foodId!=null and foodId!='' ">
                and foodId=#{foodId}
            </if>
        </where>
    </delete>
</mapper>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,825评论 6 546
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,814评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,980评论 0 384
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 64,064评论 1 319
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,779评论 6 414
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 56,109评论 1 330
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 44,099评论 3 450
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,287评论 0 291
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,799评论 1 338
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,515评论 3 361
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,750评论 1 375
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,221评论 5 365
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,933评论 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,327评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,667评论 1 296
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,492评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,703评论 2 380

推荐阅读更多精彩内容