文章目录:
2.4 创建项目中需要用到的几类包(entity、dao、service、controller、vo)
1.开篇
在这篇文章结束之后:https://blog.csdn.net/weixin_43823808/article/details/115443814,SSM基本上就算是学完了,所以呢,我在这里手写一个关于(省份城市的一个小项目,可以想指定的省份中添加城市、也可以查询出指定的省份中有哪些城市)这样的功能实现。
就算是对SSM做一个结束吧,同时应该要开始下一阶段的学习了。。。SpringBoot
2.项目的总体步骤
· entity包:两个实体类。(省份Province类、城市City类)
· dao包:对应两个dao接口和两个mapper文件。(ProvinceDao、CityDao)
· service包:对应两个service接口和实现类。(ProvinceService、CityService、ProvinceServiceImpl、CityServiceImpl)
· controller包:对应两个controller。(ProvinceController、CityController)
· vo包:一个用来封装处理结果信息的类。(CommonResult,可以理解为代替了ModelAndView)
· conf:SSM三个框架各自的主配置文件、jdbc外部属性配置文件。
· js:结合 ajax 和 jquery 来发起请求。(index.jsp)
2.1 先给出数据库中省份表和城市表的SQL源码
这里我没有使用Navicat,直接在IDEA中连接上数据库之后,写的。
数据在这里仅仅给大家做一个参考,因为我之前写完这个项目做了好多组测试,所以表中id自增的结果可能对不上号。
SET foreign_key_checks =0; DROP TABLE IF EXISTS `province`; CREATE TABLE `province`( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL COMMENT '省份名称', `jiancheng` varchar(255) DEFAULT NULL COMMENT '省份简称', `shenghui` varchar(255) DEFAULT NULL COMMENT '省份省会', PRIMARY KEY (id) )ENGINE =InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET =utf8; INSERT INTO `province` VALUES ('1','河南','豫','郑州'); INSERT INTO `province` VALUES ('2','河北','冀','石家庄'); INSERT INTO `province` VALUES ('3','山西','晋','太原'); INSERT INTO `province` VALUES ('4','陕西','陕','西安'); INSERT INTO `province` VALUES ('5','湖北','鄂','武汉'); INSERT INTO `province` VALUES ('6','湖南','湘','长沙'); INSERT INTO `province` VALUES ('7','江苏','苏','南京'); INSERT INTO `province` VALUES ('8','浙江','浙','杭州'); INSERT INTO `province` VALUES ('9','辽宁','辽','沈阳'); INSERT INTO `province` VALUES ('10','福建','闽','福州');
SET foreign_key_checks =0; DROP TABLE IF EXISTS `city`; CREATE TABLE `city`( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL COMMENT '城市名称', `provinceid` int(11) DEFAULT NULL COMMENT '对应省份的id', PRIMARY KEY(`id`) )ENGINE =InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET =utf8; INSERT INTO `city` VALUES ('1','郑州','1'); INSERT INTO `city` VALUES ('2','洛阳','1'); INSERT INTO `city` VALUES ('3','开封','1'); INSERT INTO `city` VALUES ('4','驻马店','1'); INSERT INTO `city` VALUES ('5','石家庄','2'); INSERT INTO `city` VALUES ('6','保定','2'); INSERT INTO `city` VALUES ('7','太原','3'); INSERT INTO `city` VALUES ('8','大同','3'); INSERT INTO `city` VALUES ('9','西安','4'); INSERT INTO `city` VALUES ('10','武汉','5'); INSERT INTO `city` VALUES ('11','黄冈','5'); INSERT INTO `city` VALUES ('12','长沙','6'); INSERT INTO `city` VALUES ('13','苏州','7'); INSERT INTO `city` VALUES ('14','杭州','8'); INSERT INTO `city` VALUES ('15','沈阳','9');
2.2 IDEA中使用Maven创建一个web项目
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>14</maven.compiler.source> <maven.compiler.target>14</maven.compiler.target> <spring-version>5.2.5.RELEASE</spring-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory><!--所在的目录--> <includes> <include>**/*.properties</include><!--包括目录下的.properties,.xml 文件都会扫描到--> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
2.4 创建项目中需要用到的几类包(entity、dao、service、controller、vo)
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=12345678
2.5.2 mybatis主配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 设置日志 --> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <mappers> <package name="com.songzihao.dao"/> </mappers> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载外部属性配置文件 --> <context:property-placeholder location="classpath:/conf/jdbc.properties" /> <!-- 声明组件扫描器 --> <context:component-scan base-package="com.songzihao.service" /> <!-- 声明数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- url --> <property name="url" value="${jdbc.url}" /> <!-- username --> <property name="username" value="${jdbc.username}" /> <!-- password --> <property name="password" value="${jdbc.password}" /> </bean> <!-- 创建SqlSeesionFactory对象 --> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加载数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 读取mybatis主配置文件 --> <property name="configLocation" value="classpath:/conf/mybatis-config.xml" /> </bean> <!-- 创建SqlSession对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 通过SqlSeesionFactory创建SqlSession对象 --> <property name="sqlSessionFactoryBeanName" value="factory" /> <!-- 扫描com.songzihao.dao包下的所有mapper文件 --> <property name="basePackage" value="com.songzihao.dao" /> </bean> </beans>
2.5.4 springmvc主配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 声明组件扫描器 --> <context:component-scan base-package="com.songzihao.controller" /> <!-- 声明springmvc注解驱动 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </mvc:message-converters> </mvc:annotation-driven> <!-- 声明视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>
2.6 web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 声明spring的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <!-- 自定义配置文件的位置 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:/conf/applicationContext.xml</param-value> </context-param> <!-- 声明springmvc的中央调度器 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 自定义配置文件的位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/conf/dispatcherServlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 声明字符集过滤器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
package com.songzihao.entity; /** * */ public class Province { private Integer id; private String name; private String jiancheng; private String shenghui; //getter and setter //toString }
package com.songzihao.entity; /** * */ public class City { private Integer id; private String name; private Integer provinceId; //getter and setter //toString }
package com.songzihao.dao; import com.songzihao.entity.Province; import java.util.List; /** * */ public interface ProvinceDao { List<Province> selectAllProvinces(); }
<?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.songzihao.dao.ProvinceDao"> <!-- 使用insert、update、delete、select标签编写sql语句 --> <select id="selectAllProvinces" resultType="com.songzihao.entity.Province"> select * from province order by id </select> </mapper>
package com.songzihao.dao; import com.songzihao.entity.City; import org.apache.ibatis.annotations.Param; import java.util.List; /** * */ public interface CityDao { int insertCity(City city); List<City> selectCityByProvinceId(@Param("provinceid") Integer pid); }
<?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.songzihao.dao.CityDao"> <!-- 使用insert、update、delete、select标签编写sql语句 --> <insert id="insertCity"> insert into city(name,provinceid) values (#{name},#{provinceId}) </insert> <select id="selectCityByProvinceId" resultType="com.songzihao.entity.City"> select id,name,provinceid from city where provinceid=#{provinceid} </select> </mapper>
package com.songzihao.service; import com.songzihao.entity.Province; import java.util.List; /** * */ public interface ProvinceService { List<Province> queryAllProvinces(); }
package com.songzihao.service.impl; import com.songzihao.dao.ProvinceDao; import com.songzihao.entity.Province; import com.songzihao.service.ProvinceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * */ @Service public class ProvinceServiceImpl implements ProvinceService { @Autowired private ProvinceDao provinceDao; @Override public List<Province> queryAllProvinces() { List<Province> provinceList=provinceDao.selectAllProvinces(); return provinceList; } }
package com.songzihao.service; import com.songzihao.entity.City; import java.util.List; /** * */ public interface CityService { int addCity(City city); List<City> queryCityByProvinceId(Integer provinceId); }
package com.songzihao.service.impl; import com.songzihao.dao.CityDao; import com.songzihao.entity.City; import com.songzihao.service.CityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * */ @Service public class CityServiceImpl implements CityService { @Autowired private CityDao cityDao; @Override public int addCity(City city) { int rows=cityDao.insertCity(city); return rows; } @Override public List<City> queryCityByProvinceId(Integer provinceId) { List<City> cityList=cityDao.selectCityByProvinceId(provinceId); return cityList; } }
package com.songzihao.vo; /** * */ public class CommonResult { //表示本次请求是否处理成功,成功为1,失败为0 private Integer code; //反馈原因 private String msg; //数据 private Object data; public CommonResult() { } public CommonResult(Integer code, String msg, Object data) { this.code = code; this.msg = msg; this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
package com.songzihao.controller; import com.songzihao.entity.Province; import com.songzihao.service.ProvinceService; import com.songzihao.vo.CommonResult; 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.ResponseBody; import java.util.List; /** * */ @Controller public class ProvinceController { @Autowired private ProvinceService provinceService; @RequestMapping(value = "/queryProvince.do") @ResponseBody public CommonResult queryAllProvinces() { List<Province> provinceList=provinceService.queryAllProvinces(); CommonResult cr=null; if(provinceList!=null && provinceList.size()>0) { cr=new CommonResult(1,"查询成功",provinceList); }else { cr=new CommonResult(0,"查询无结果",""); } return cr; } }
package com.songzihao.controller; import com.songzihao.entity.City; import com.songzihao.service.CityService; import com.songzihao.vo.CommonResult; 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.ResponseBody; import java.util.List; /** * */ @Controller public class CityController { @Autowired private CityService cityService; @RequestMapping(value = "/addCity.do") @ResponseBody public CommonResult addCity(City city) { int rows=cityService.addCity(city); CommonResult cr=new CommonResult(); if (rows>0) { cr.setCode(1); cr.setMsg("添加城市" + city.getName() + "成功!!!"); cr.setData(city); }else { cr.setCode(0); cr.setMsg("添加城市失败。。。"); cr.setData(""); } return cr; } @RequestMapping(value = "/queryCity.do") @ResponseBody public CommonResult queryCity(Integer pid) { List<City> cityList=cityService.queryCityByProvinceId(pid); CommonResult cr=new CommonResult(); if(cityList!=null && cityList.size()>0) { cr.setCode(1); cr.setMsg("一共查询到" + cityList.size() + "个城市!!!"); cr.setData(cityList); }else { cr.setCode(0); cr.setMsg("查询无结果。。。"); cr.setData(""); } return cr; } }
<%@ page contentType="text/html;charset=utf-8" language="java" %> <% String basePath=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <html> <head> <title>首页</title> <base href="<%=basePath%>"> <script type="text/javascript" src="js/jquery-3.6.0.js"></script> <script type="text/javascript"> $(function () { //添加省份的select组件 getProvinceList(); //查询城市 $("#queryCity").click(function () { var pid=$("#province>option:selected").val(); $.get( "queryCity.do", //url {pid: pid}, //data function (response) { //function if (response.code==1) { alert(response.msg); $("#cityInfo").empty(); $.each(response.data,function (i,n) { $("#cityInfo").append("<tr><td>" + n.id + "</td><td>" + n.name + "</td></tr>"); }) }else { alert(response.msg); } }, "json" //dataType ) }) //添加城市 $("#addCity").on("click",function () { var pid=$("#province>option:selected").val(); var name=$(":text").val(); $.post( "addCity.do", //url {provinceId: pid,name: name}, //data function (response) { //function if(response.code==1) { alert(response.msg); }else { alert(response.msg); } }, "json" //dataType ) }) }) function getProvinceList() { $.ajax({ url: "queryProvince.do", dataType: "json", success: function (response) { $("#province").empty(); $.each(response.data,function (i,n) { $("#province").append("<option value='" + n.id + "'>" + n.name + "</option>"); }) } }) } </script> </head> <body> <div align="center"> <table> <tr> <td>省份列表:</td> <td> <select id="province"> <option value="0">请选择...</option> </select> </td> </tr> <tr> <td>城市名称:</td> <td><input type="text" id="cityName"></td> </tr> <tr> <td><input type="button" id="addCity" value="添加城市"></td> <td><button id="queryCity">根据省份查询城市</button></td> </tr> </table> <br/> <div id="dataDiv"> <table border="1"> <thead> <tr> <td>城市id</td> <td>城市名称</td> </tr> </thead> <tbody id="cityInfo"> </tbody> </table> </div> </div> </body> </html>
首先是我们的首页,访问到了 index.jsp。
在省份列表中选择河南,点击 “根据省份查询城市” 这个按钮,就可以弹出下面的窗口和相应的结果。
在城市名称的文本框中,输入 “南阳”,点击 “添加城市” 按钮,就可以弹出下面的窗口和相应的结果。
3.写在最后
这个破烂项目,我写了一个下午😥😥😥,改bug就TM改了一个小时,唉,真不容易啊。。。
大佬勿喷,大佬我勿喷,大佬勿喷!!!