springboot+thymeleaf+mysql实现省市联动下拉

本文档展示了如何使用Spring Boot、MyBatis Plus和Thymeleaf实现省市联动的下拉菜单功能。通过获取省份和城市数据,利用Ajax异步更新城市列表,实现了动态加载的效果。同时,利用session缓存数据,提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、数据准备

①数据获取:获取省市数据以及建表和插入表数据语句

二、实现编码

①效果图示:

在这里插入图片描述

②项目目录:

在这里插入图片描述

③代码实现:

controller:(核心)

CasCadeController

package com.cfay.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cfay.pojo.City;
import com.cfay.pojo.Province;
import com.cfay.service.CityService;
import com.cfay.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CasCadeController {
   
   
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;

    //获取省份信息
    @GetMapping("/main")
    public String toIndex(Model model, HttpSession session){
   
   
        String proListSession = (String) session.getAttribute("proList");
        //省份数据已经有了
        if(proListSession != null && proListSession.length() != 0) {
   
   
            model.addAttribute("proList",proListSession);
            System.out.println("已存在省份信息");
        }else{
   
   
            //还没有省份数据
            List<Province> proList = provinceService.list();
            String strProList = JSON.toJSONString(proList);
            session.setAttribute("proList",strProList);
            model.addAttribute("proList",strProList);
        }
        return "main";
    }

    //获取省份对应的城市信息
    @GetMapping("/getCityMessage")
    @ResponseBody
    public String getCityMessage(String cityKey){
   
   
        //建议:这里可以把已经查出来的城市保存在session中,然后查询的时候先判断是否有这个数据,有的话,就直接从session中获取,没有的话再去查数据库,可参考上面的方式实现
        City city = new City();
        city.setPCode(cityKey);
        List<City> cityList = cityService.list(Wrappers.query(city));
        return JSON.toJSONString(cityList);
    }
}
Dao:

CityDao

package com.cfay.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cfay.pojo.City;

public interface CityDao extends BaseMapper<City> {
   
   
}

ProvinceDao

package com.cfay.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cfay.pojo.Province;

public interface ProvinceDao extends BaseMapper<Province> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楚风岸影

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值