『收藏向 期末SSM课设救急』 教你从搭建到测试运行手撸一个SSM项目实战,附带源码,前端页面、解析和一般遇到的问题(排雷)
🛫ssm知識(shí)學(xué)習(xí)見(jiàn)SSM_面向CRUD編程專(zhuān)欄
🚕本項(xiàng)目來(lái)自動(dòng)力節(jié)點(diǎn)的【米米商城】
🚒博主對(duì)于該知識(shí)尚在學(xué)習(xí)階段
🚄如果發(fā)現(xiàn)存在問(wèn)題請(qǐng)毫不吝嗇的指出
🚀🚀扎哇太棗糕的博客主頁(yè)🚀🚀
項(xiàng)目完成并更新到giteeZaoGao_ssm: ssm項(xiàng)目——棗糕商城?,但是不建議使用倉(cāng)庫(kù)中g(shù)itee的前端頁(yè)面,博客中會(huì)有相應(yīng)的初始化的前端頁(yè)面下載,從頭跟著博客一步一步的做
目錄
1 框架構(gòu)建
1.1 項(xiàng)目所需技術(shù)
1.2 項(xiàng)目搭建
1.3 配置所有的文件信息
2 登錄功能的業(yè)務(wù)邏輯?
2.1?MD5加密算法
2.2?登錄代碼
2.3 測(cè)試執(zhí)行?
3 商品管理功能的業(yè)務(wù)邏輯?
3.1 商品管理之查詢(xún)所有產(chǎn)品
3.2?商品管理之Ajax分頁(yè)翻頁(yè)顯示
3.3?商品管理之新增商品
3.3.1 新增商品之下拉框顯示商品類(lèi)型
3.3.2?新增商品之異步Ajax圖片上傳
3.3.3 新增商品之信息持久化數(shù)據(jù)庫(kù)
3.4?商品管理之商品編輯
?3.5?商品管理之商品刪除
3.5.1 商品刪除之單個(gè)刪除
3.5.2?商品刪除之批量刪除
3.6?商品管理之多條件查詢(xún)
3.6?商品管理之刪除優(yōu)化
1 框架構(gòu)建
1.1 項(xiàng)目所需技術(shù)
- 服務(wù)端:Spring+SpringMVC+MyBatis
- 數(shù)據(jù)庫(kù):MySql
- web服務(wù)器:Tomcat
- 項(xiàng)目管理:Maven
- 前端:jQuery+BootStrap+JavaScript+Ajax
- 開(kāi)發(fā)工具:idea
????????其中前端頁(yè)面、圖片等部分提供源碼,不需要我們自己進(jìn)行編寫(xiě),只需要了解即可。
1.2 項(xiàng)目搭建
第一步:創(chuàng)建一個(gè)maven項(xiàng)目
第二步:添加web依賴(lài)成為web項(xiàng)目?
這里因?yàn)橐恍┰蚴褂玫氖且郧暗膱D,本次項(xiàng)目需要在上步創(chuàng)建好的項(xiàng)目上右鍵,一通操作之后將生成的web目錄放到src/main目錄下
第三步:搭建層級(jí)結(jié)構(gòu),里面內(nèi)容為空?
第四步:導(dǎo)入所有的前端頁(yè)面
????????下載前端頁(yè)面復(fù)制粘貼到web目錄下,下載地址:棗糕商城所需的前端頁(yè)面下載
第五步:創(chuàng)建數(shù)據(jù)庫(kù)
????????下載數(shù)據(jù)庫(kù)的SQL文件,在Navicat的連接處右鍵運(yùn)行SQL文件選中文件并運(yùn)行,或者直接將下載好的文件拖拽到Navicat的連接處,SQL文件下載地址:棗糕商城的數(shù)據(jù)庫(kù)SQL文件下載
第六步:pom.xml文件導(dǎo)入依賴(lài)
<!-- 集中定義依賴(lài)版本號(hào) --><properties><junit.version>4.12</junit.version><spring.version>5.2.5.RELEASE</spring.version><mybatis.version>3.5.1</mybatis.version><mybatis.spring.version>1.3.1</mybatis.spring.version><mybatis.paginator.version>1.2.15</mybatis.paginator.version><mysql.version>8.0.22</mysql.version><slf4j.version>1.6.4</slf4j.version><druid.version>1.1.12</druid.version><pagehelper.version>5.1.2</pagehelper.version><jstl.version>1.2</jstl.version><servlet-api.version>3.0.1</servlet-api.version><jsp-api.version>2.0</jsp-api.version><jackson.version>2.9.6</jackson.version></properties><dependencies><!-- spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</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-aspects</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jms</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!-- Mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis.spring.version}</version></dependency><dependency><groupId>com.github.miemiedev</groupId><artifactId>mybatis-paginator</artifactId><version>${mybatis.paginator.version}</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>${pagehelper.version}</version></dependency><!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!-- 連接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>${druid.version}</version></dependency><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><!-- JSP相關(guān) --><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.0.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jsp-api</artifactId><scope>provided</scope><version>${jsp-api.version}</version></dependency><!-- Jackson Json處理工具包 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency></dependencies><!-- 插件配置 --><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin></plugins><!--識(shí)別所有的配置文件--><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>1.3 配置所有的文件信息
配置文件先都創(chuàng)建好并加入一些基本配置信息,后期還會(huì)對(duì)其中內(nèi)容進(jìn)行增添
mybatis.xml
resource目錄右鍵-->new-->File
<?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><!--分頁(yè)插件的配置--><plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin></plugins> </configuration>jdbc.properties
resource目錄右鍵-->new-->File
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/zaogaossm?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true jdbc.username=root jdbc.password=123456spring-dao.xml
resource目錄右鍵-->new-->XML Configuration File-->Spring Config
<?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"><!--讀取jdbc.properties文件--><context:property-placeholder location="classpath:jdbc.properties"/><!--創(chuàng)建數(shù)據(jù)源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--創(chuàng)建sqlSessionFactory的bean--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--配置數(shù)據(jù)源--><property name="dataSource" ref="dataSource"/><!--配置mybatis.xml文件--><property name="configLocation" value="classpath:mybatis.xml"/><!--配置實(shí)體類(lèi)--><property name="typeAliasesPackage" value="com.xiaochen.domain"/></bean><!--創(chuàng)建mapper的掃描器--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.xiaochen.mapper"/></bean> </beans>spring-service.xml
resource目錄右鍵-->new-->XML Configuration File-->Spring Config
<?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 http://www.springframework.org/schema/context/spring-context.xsd"><!--設(shè)置包掃描器,加載@Service注解--><context:component-scan base-package="com.xiaochen.service"><!-- 制定掃包規(guī)則 ,不掃描@Controller注解的JAVA類(lèi) --><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan></beans>spring-tx.xml
resource目錄右鍵-->new-->XML Configuration File-->Spring Config
<?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:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsd"><!--聲明式事務(wù)控制--><!--事務(wù)管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--配置切面--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 傳播行為 --><tx:method name="save*" propagation="REQUIRED" /><tx:method name="insert*" propagation="REQUIRED" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><tx:method name="select*" propagation="SUPPORTS" read-only="true" /><tx:method name="get*" propagation="SUPPORTS" read-only="true" /><tx:method name="query*" propagation="SUPPORTS" read-only="true" /><tx:method name="*" propagation="SUPPORTS"/></tx:attributes></tx:advice><!--aop織入--><aop:config><aop:pointcut id="txPointcut" expression="execution(* com.xiaochen.service.*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/></aop:config> </beans>springMVC.xml
resource目錄右鍵-->new-->XML Configuration File-->Spring Config
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd"><!--注解驅(qū)動(dòng)--><mvc:annotation-driven/> <!-- <!–配置SpringMVC無(wú)法使用靜態(tài)文件的問(wèn)題–><mvc:default-servlet-handler/>--><!--設(shè)置掃描器,掃描@Controller注解--><context:component-scan base-package="com.xiaochen.controller"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!--設(shè)置視圖解析器,頁(yè)面轉(zhuǎn)發(fā)時(shí)可以少寫(xiě)代碼,拼接訪問(wèn)路徑--><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/admin/"/><property name="suffix" value=".jsp"/></bean><!--設(shè)置文件上傳,其中可以設(shè)置文件上傳大小等,這里不配使用默認(rèn)設(shè)置--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/></beans>web.xml
添加web支持之后生成的web/WEB-INF/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"><!--設(shè)置主界面--><welcome-file-list><welcome-file>/admin/login.jsp</welcome-file></welcome-file-list><!--引入前端控制器--><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--引入SpringMVC的配置文件--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springMVC.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>*.action</url-pattern></servlet-mapping><!--配置Spring的監(jiān)聽(tīng)器,web應(yīng)用一啟動(dòng)就創(chuàng)建實(shí)例化的對(duì)象放到域中,隨用隨取--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--引入Spring的配置文件--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-*.xml</param-value></context-param><!--配置Spring的過(guò)濾器--><filter><filter-name>encode</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>encode</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>2 登錄功能的業(yè)務(wù)邏輯?
2.1?MD5加密算法
? ? ? ? MD5加密算法可以直接下載該java文件放到utils目錄下即可使用,下載地址:實(shí)現(xiàn)MD5加密java文件下載?,下載之后復(fù)制粘貼到utils目錄下?????????這里插播一個(gè)小內(nèi)容,前面生成數(shù)據(jù)庫(kù)表的sql文件有一點(diǎn)點(diǎn)的問(wèn)題,在admin表中存儲(chǔ)的數(shù)據(jù)是000000,實(shí)際上應(yīng)該是c984aed014aec7623a54f0591da07a85fd4b762d, 即是000000經(jīng)過(guò)MD5加密之后的字符串。所以我們要先改變一下a_pass這個(gè)字段的長(zhǎng)度為255,在將加密之后的字符串存進(jìn)去。
2.2?登錄代碼
????????按本人業(yè)務(wù)實(shí)現(xiàn)習(xí)慣都是先編寫(xiě)domain層的數(shù)據(jù)庫(kù)對(duì)應(yīng)實(shí)體類(lèi)(有的話就不寫(xiě)),然后是mapper接口和對(duì)應(yīng)的xml映射文件的編寫(xiě),再然后就是service接口和對(duì)應(yīng)實(shí)現(xiàn)類(lèi)的編寫(xiě),最后就是controller與前端交互的編寫(xiě)。編寫(xiě)順序依照個(gè)人習(xí)慣而言,寫(xiě)著舒服即可。
domain層
admin數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)
public class Admin {private Integer aId;private String aName;private String aPass;public Integer getaId() {return aId;}public void setaId(Integer aId) {this.aId = aId;}public String getaName() {return aName;}public void setaName(String aName) {this.aName = aName == null ? null : aName.trim();}public String getaPass() {return aPass;}public void setaPass(String aPass) {this.aPass = aPass == null ? null : aPass.trim();} }mapper層
mapper接口實(shí)現(xiàn)按用戶(hù)名查詢(xún)數(shù)據(jù)庫(kù)
public interface AdminMapper {/*** 管理員的登錄* @param name 管理員的用戶(hù)名* @return Admin* */List<Admin> queryByName(String name); }????????在resource目錄下新建一個(gè)package使用com/xiaochen/mapper命名,這里的分割符一定是/而不是.具體為啥我也不知道😑,package中新建一個(gè)AdminMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.xiaochen.mapper.AdminMapper"><!--將實(shí)體類(lèi)中的private屬性與數(shù)據(jù)中的字段進(jìn)行映射,column ==>數(shù)據(jù)庫(kù)字段名 property==>實(shí)體類(lèi)屬性名--><resultMap id="BaseResultMap" type="com.xiaochen.domain.Admin"><id column="a_id" jdbcType="INTEGER" property="aId" /><result column="a_name" jdbcType="VARCHAR" property="aName" /><result column="a_pass" jdbcType="VARCHAR" property="aPass" /></resultMap><!--通過(guò)用戶(hù)名查詢(xún)admin表中的信息--><select id="queryByName" parameterType="string" resultMap="BaseResultMap">select * from admin where a_name=#{name}</select></mapper>service層
AdminService接口
public interface AdminService {/*** 管理員的登錄* @param name 管理員的用戶(hù)名* @return Admin* */List<Admin> queryByName(String name); }創(chuàng)建一個(gè)AdminServiceImpl
@Service public class AdminServiceImpl implements AdminService {// 創(chuàng)建mapper層的對(duì)象,注入@Autowiredprivate AdminMapper adminMapper;@Overridepublic List<Admin> queryByName(String name) {// 調(diào)用mapper的queryByName方法,得到所有用戶(hù)名為name的管理員信息return adminMapper.queryByName(name);} }controller層
AdminController實(shí)現(xiàn)登錄判斷
@Controller @RequestMapping("/admin") public class AdminController {// 注入adminservice對(duì)象@Autowiredprivate AdminService adminService;// 實(shí)現(xiàn)登錄判斷并進(jìn)行相應(yīng)的跳轉(zhuǎn)@RequestMapping("/login")public String login(String name, String pwd, HttpServletRequest request) {List<Admin> admins = adminService.queryByName(name);// 對(duì)查詢(xún)到的所有管理員進(jìn)行密碼比對(duì) for (Admin admin : admins) {// 數(shù)據(jù)庫(kù)中存儲(chǔ)的是加密之后的密碼,于是要將輸入的密碼進(jìn)行加密之后再進(jìn)行比較if (MD5Util.getMD5(pwd).equals(admin.getaPass())) {// 登陸成功,跳轉(zhuǎn)admin.jsp頁(yè)面并將這個(gè)admin對(duì)象傳遞給前端request.setAttribute("admin", admin);return "main";}}// 所有的管理員密碼都不匹配的話登陸失敗,跳回login.jsp頁(yè)面并傳遞失敗信息request.setAttribute("errmsg", "用戶(hù)名或者密碼不正確!!");return "login";} }2.3 測(cè)試執(zhí)行?
????????tomcat版本安裝(切記,不要安裝tomcat 9!!如果安裝tomcat9的話會(huì)導(dǎo)致下一步的商品管理顯示不出來(lái),本人使用的是tomcat 7.0.108僅供參考)以及idea中配置tomcat參考我的這篇博客,點(diǎn)擊鏈接直接在目錄上點(diǎn)擊Tomcat的部分直接空降即可:關(guān)于黑馬程序員最全SSM框架教程視頻,P37集老師跳過(guò)的模塊創(chuàng)建以及tomcat下載安裝配置和運(yùn)行等諸多問(wèn)題
如果運(yùn)行不開(kāi)的話,自查一下以下兩小項(xiàng)
依賴(lài)jar包是否已經(jīng)導(dǎo)入到lib目錄下
web.xml文件是否加載上且正確加載
一切就緒之后運(yùn)行tomcat服務(wù)器會(huì)彈出登錄界面(因?yàn)橹皐eb.xml文件設(shè)置了<welcome-file-list>標(biāo)簽,所以一啟動(dòng)就會(huì)跳轉(zhuǎn)到這個(gè)登錄的jsp頁(yè)面)
?登陸成功,網(wǎng)頁(yè)跳轉(zhuǎn)
登陸失敗,回寫(xiě)數(shù)據(jù)
3 商品管理功能的業(yè)務(wù)邏輯?
3.1 商品管理之查詢(xún)所有產(chǎn)品
?domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)
public class ProductInfo {private Integer pId;private String pName;private String pContent;private Integer pPrice;private String pImage;private Integer pNumber;private Integer typeId;private Date pDate;public Integer getpId() {return pId;}public void setpId(Integer pId) {this.pId = pId;}public String getpName() {return pName;}public void setpName(String pName) {this.pName = pName == null ? null : pName.trim();}public String getpContent() {return pContent;}public void setpContent(String pContent) {this.pContent = pContent == null ? null : pContent.trim();}public Integer getpPrice() {return pPrice;}public void setpPrice(Integer pPrice) {this.pPrice = pPrice;}public String getpImage() {return pImage;}public void setpImage(String pImage) {this.pImage = pImage == null ? null : pImage.trim();}public Integer getpNumber() {return pNumber;}public void setpNumber(Integer pNumber) {this.pNumber = pNumber;}public Integer getTypeId() {return typeId;}public void setTypeId(Integer typeId) {this.typeId = typeId;}public Date getpDate() {return pDate;}public void setpDate(Date pDate) {this.pDate = pDate;} }mapper層
ProductInfoMapper接口
public interface ProductInfoMapper {/*** 全部商品的顯示* @return ProductInfo*/List<ProductInfo> queryAll(); }????????在resource目錄的com/xiaochen/mapper的package中新建一個(gè)ProductInfoMapper.xml文件
<?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.xiaochen.mapper.ProductInfoMapper" ><!--將實(shí)體類(lèi)中的private屬性與數(shù)據(jù)中的字段進(jìn)行映射,column ==>數(shù)據(jù)庫(kù)字段名 property==>實(shí)體類(lèi)屬性名--><resultMap id="BaseResultMap" type="com.xiaochen.domain.ProductInfo" ><id column="p_id" property="pId" jdbcType="INTEGER" /><result column="p_name" property="pName" jdbcType="VARCHAR" /><result column="p_content" property="pContent" jdbcType="VARCHAR" /><result column="p_price" property="pPrice" jdbcType="INTEGER" /><result column="p_image" property="pImage" jdbcType="VARCHAR" /><result column="p_number" property="pNumber" jdbcType="INTEGER" /><result column="type_id" property="typeId" jdbcType="INTEGER" /><result column="p_date" property="pDate" jdbcType="DATE" /></resultMap><!--查詢(xún)所有的商品信息--><select id="queryAll" resultMap="BaseResultMap">select * from product_info</select></mapper>service層
ProductInfoService接口
public interface ProductInfoService {/*** 全部商品的顯示* @return ProductInfo*/List<ProductInfo> queryAll(); }創(chuàng)建一個(gè)ProductInfoServiceImpl
@Service public class ProductInfoServiceImpl implements ProductInfoService {// 注入productInfoMapper@Autowiredprivate ProductInfoMapper productInfoMapper;@Overridepublic List<ProductInfo> queryAll() {return productInfoMapper.queryAll();} }controller層
ProductInfoController查詢(xún)所有的商品信息
@Controller @RequestMapping("/prod") public class ProductInfoController {// 注入productInfoService@Autowiredprivate ProductInfoService productInfoService;// 查詢(xún)所有的產(chǎn)品信息@RequestMapping("/queryAll")public String queryAll(HttpServletRequest request) {List<ProductInfo> products= productInfoService.queryAll();request.setAttribute("list", products);return "product";}}運(yùn)行測(cè)試
????????運(yùn)行之前先修改一下前端頁(yè)面mian.jsp和product.jsp的一個(gè)小小的代碼,這個(gè)地方不是說(shuō)前端代碼有錯(cuò)只是本次測(cè)試使用,下面的功能還是要再改回來(lái)滴
?運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.2?商品管理之Ajax分頁(yè)翻頁(yè)顯示
? ? ? ? 為了便于觀察后面添加商品,也是符合實(shí)際場(chǎng)景,讓數(shù)據(jù)庫(kù)中的產(chǎn)品信息按照主鍵p_id倒序查出,這樣的話新插入的數(shù)據(jù)就是在第一條顯示了,這個(gè)功能交由MyBatis的查詢(xún)解決。
??domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi),已經(jīng)存在不再創(chuàng)建
mapper層
ProductInfoMapper接口添加方法
/** * 對(duì)某表按某字段某順序排序 * @param tableName 某表 * @param field 某字段 * @param order 某順序desc降序或者abs升序 */ List<ProductInfo> orderById(@Param("tableName") String tableName, @Param("field") String field, @Param("order") String order);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件添加動(dòng)態(tài)SQL查詢(xún)語(yǔ)句
<!--對(duì)某表按某字段某順序排序--><select id="orderById" parameterType="string" resultMap="BaseResultMap">select * from ${tableName}<if test="field != null">order by ${field}</if><if test="order!=null">${order}</if></select>service層
ProductInfoService接口添加分頁(yè)方法
/*** 分頁(yè)操作* @param pageNum 查詢(xún)第幾頁(yè)的數(shù)據(jù)* @param PageSize 每頁(yè)有幾條數(shù)據(jù)* @return 分頁(yè)插件中帶的pageInfo實(shí)體類(lèi)*/PageInfo splitPage(int pageNum, int PageSize);????????ProductInfoServiceImpl添加分頁(yè)方法,先調(diào)用倒序查詢(xún)?cè)賹⒔Y(jié)果封裝到分頁(yè)插件自帶的pageInfo實(shí)體類(lèi)中,封裝進(jìn)去之后分頁(yè)插件自動(dòng)將查詢(xún)到的集合轉(zhuǎn)換成諸如一共可以分多少頁(yè)上一頁(yè)下一頁(yè)等屬性,然后就可以很簡(jiǎn)單的調(diào)用實(shí)體類(lèi)中的屬性完成分頁(yè)翻頁(yè)操作了
@Overridepublic PageInfo splitPage(int pageNum, int PageSize) {// 分頁(yè)插件使用pageHelper進(jìn)行分頁(yè)設(shè)置PageHelper.startPage(pageNum, PageSize);// 調(diào)用orderById方法,對(duì)product_info表的p_id字段進(jìn)行desc降序操作List<ProductInfo> productInfos = productInfoMapper.orderById("product_info", "p_id", "desc");// 將查詢(xún)到的集合封裝到pageInfo對(duì)象中并返回PageInfo<ProductInfo> pageInfo = new PageInfo<>(productInfos);return pageInfo;}controller層
ProductInfoController進(jìn)行分頁(yè)用于返回展示一開(kāi)始的五條數(shù)據(jù),翻頁(yè)是調(diào)用Ajax的翻頁(yè),翻頁(yè)的技術(shù)前端已經(jīng)完成,我們只需要編寫(xiě)翻頁(yè)代碼,將前端傳回來(lái)的第幾頁(yè)查出來(lái)并返回給前端進(jìn)行顯示
首先需要在ProductInfoController類(lèi)的最上面定義一個(gè)常量PAGE_SIZE值為5
然后添加split方法
// Ajax分頁(yè)@RequestMapping("/split")public String split(HttpServletRequest request) {PageInfo pageInfo = productInfoService.splitPage(1, PAGE_SIZE);// 放到域中,前端接收request.setAttribute("info", pageInfo);return "product";}// Ajax翻頁(yè)@ResponseBody@RequestMapping("/ajaxsplit")public void ajaxSplit(int page, HttpSession session) {PageInfo pageInfo = productInfoService.splitPage(page, PAGE_SIZE);// 放到域中,前端接收session.setAttribute("info", pageInfo);}運(yùn)行測(cè)試
????????運(yùn)行之前先將前端頁(yè)面mian.jsp和product.jsp的代碼修改回來(lái),一個(gè)加上info.一個(gè)改成split.action
?運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.3?商品管理之新增商品
3.3.1 新增商品之下拉框顯示商品類(lèi)型
??domain層
productType數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)
public class ProductType {private Integer typeId;private String typeName;public Integer getTypeId() {return typeId;}public void setTypeId(Integer typeId) {this.typeId = typeId;}public String getTypeName() {return typeName;}public void setTypeName(String typeName) {this.typeName = typeName == null ? null : typeName.trim();} }mapper層
新建ProductTypeMapper接口
public interface ProductTypeMapper {/*** 查詢(xún)所有的商品類(lèi)別* @return ProductType*/List<ProductType> queryAll(); }????????在resource目錄的com/xiaochen/mapper的package中新建ProductTypeMapper.xml文件
<?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.xiaochen.mapper.ProductTypeMapper" ><!--將實(shí)體類(lèi)中的private屬性與數(shù)據(jù)中的字段進(jìn)行映射,column ==>數(shù)據(jù)庫(kù)字段名 property==>實(shí)體類(lèi)屬性名--><resultMap id="BaseResultMap" type="com.xiaochen.domain.ProductType" ><id column="type_id" property="typeId" jdbcType="INTEGER" /><result column="type_name" property="typeName" jdbcType="VARCHAR" /></resultMap><!--查詢(xún)所有的商品類(lèi)別--><select id="queryAll" resultMap="BaseResultMap">select * from product_type</select> </mapper>service層
ProductTypeService接口
public interface ProductTypeService {/*** 查詢(xún)所有的商品類(lèi)別* @return ProductType*/List<ProductType> queryAll(); }ProductTypeServiceImpl實(shí)現(xiàn)類(lèi)
// 注解加字符串為了監(jiān)聽(tīng)器中創(chuàng)建對(duì)象使用 @Service("productTypeServiceImpl") public class ProductTypeServiceImpl implements ProductTypeService {// 注入ProductTypeMapper對(duì)象@Autowiredprivate ProductTypeMapper productTypeMapper;@Overridepublic List<ProductType> queryAll() {List<ProductType> productTypes = productTypeMapper.queryAll();return productTypes;} }新建一個(gè)listener層
ProductTypeListener是一個(gè)監(jiān)聽(tīng)器類(lèi),用于在web項(xiàng)目啟動(dòng)的時(shí)候獲取所有的商品類(lèi)別,并放到全局應(yīng)用作用域中,供新增、修改、查詢(xún)提供全部商品類(lèi)型集合
@WebListener public class ProductTypeListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent servletContextEvent) {// 手工從spring容器取出ProductTypeServiceImpl的對(duì)象ApplicationContext context = new ClassPathXmlApplicationContext("spring-*.xml");ProductTypeService productTypeService = (ProductTypeService) context.getBean("productTypeServiceImpl");// 獲取所有的商品類(lèi)別,并放到全局應(yīng)用作用域中,供新增、修改、查詢(xún)提供全部商品類(lèi)型集合List<ProductType> productTypes = productTypeService.queryAll();servletContextEvent.getServletContext().setAttribute("ptlist", productTypes);}@Overridepublic void contextDestroyed(ServletContextEvent servletContextEvent) {} }運(yùn)行測(cè)試
?? ? ? ? 直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.3.2?新增商品之異步Ajax圖片上傳
????????下載隨機(jī)生成文件名稱(chēng)的工具類(lèi),并將其復(fù)制粘貼到utils包下,下載地址:隨機(jī)生成文件名的工具類(lèi)下載使用UUID生成文件名,再拼接上圖片的后綴,給圖片隨機(jī)生成一個(gè)新的名稱(chēng),這么做的目的是新添加進(jìn)去的圖片不會(huì)因?yàn)槊嗤桓采w掉
pom.xml文件添加依賴(lài)
<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20140107</version> </dependency>controller層
????????ProductInfoController類(lèi)中添加異步上傳方法,主要就是將選擇的圖片重新生成一個(gè)新的名字轉(zhuǎn)存在項(xiàng)目的webapp下的image_big文件夾下,并將封面圖片的路徑封裝在一個(gè)JSON類(lèi)型數(shù)據(jù)中,前端獲取到JSON得到文件路徑取出圖片在前端進(jìn)行一個(gè)回顯的操作
// 異步Ajax上傳 @ResponseBody @RequestMapping("/ajaxImg") public Object ajaxImg(MultipartFile pimage, HttpServletRequest request) throws IOException {// 提取生成文件名:UUID+上傳文件的后綴String saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());// 得到項(xiàng)目中圖片存儲(chǔ)的路徑String path = request.getServletContext().getRealPath("/image_big");// 轉(zhuǎn)存圖片 image_big的路徑 動(dòng)態(tài)分隔符 新生成的文件名pimage.transferTo(new File(path + File.separator + saveFileName));// 返回客戶(hù)端JSON對(duì)象,封面圖片的路徑,為了在頁(yè)面進(jìn)行回顯操作JSONObject object = new JSONObject();object.put("imgurl", saveFileName);return object.toString(); }運(yùn)行測(cè)試
直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.3.3 新增商品之信息持久化數(shù)據(jù)庫(kù)
??domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)已經(jīng)存在不用創(chuàng)建
mapper層
ProductInfoMapper接口添加方法
/*** 新增商品信息持久化數(shù)據(jù)庫(kù)* @param info 產(chǎn)品信息的數(shù)據(jù)庫(kù)* @return 是否insert成功*/ int save(ProductInfo info);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件,添加插入數(shù)據(jù)的SQL
<!--insert產(chǎn)品數(shù)據(jù)--> <insert id="save" parameterType="com.xiaochen.domain.ProductInfo">insert into product_info(p_name,p_content,p_price,p_image,p_number,type_id,p_date) values (#{pName},#{pContent},#{pPrice},#{pImage},#{pNumber},#{typeId},#{pDate}) </insert>service層
ProductInfoService接口添加方法
/*** 新增商品信息持久化數(shù)據(jù)庫(kù)* @param info 產(chǎn)品信息的數(shù)據(jù)庫(kù)* @return 是否insert成功*/ int save(ProductInfo info);ProductInfoServiceImpl實(shí)現(xiàn)類(lèi)
@Override public int save(ProductInfo info) {int flag = productInfoMapper.save(info);return flag; }controller層
ProductInfoController將添加商品的所有信息持久化到數(shù)據(jù)庫(kù)中
????????為了方便獲取圖片名稱(chēng),現(xiàn)將ProductInfoController類(lèi)的ajaxImg方法中的方法變量saveFileName提升為類(lèi)的成員變量,這樣的話就可以在ProductInfoController類(lèi)的所有方法中調(diào)用變量的值。具體操作是在常量PAGE_SIZE的下面定義變量saveFileName
并將ajaxImg方法中的String定義刪去,相當(dāng)于在類(lèi)中定義并初始化,在方法中重新賦值
ProductInfoController類(lèi)中添加save方法
// 持久化數(shù)據(jù)庫(kù) @RequestMapping("/save") public String save(ProductInfo info, HttpServletRequest request) {// 前端已經(jīng)獲取到新增商品的商品名稱(chēng)、商品介紹、定價(jià)、總數(shù)量、類(lèi)別// 后端添加圖片名稱(chēng)和添加日期info.setpImage(saveFileName);info.setpDate(new Date());// 調(diào)用插入數(shù)據(jù)的方法,并返回msg給前臺(tái)彈窗使用int flag = -1;try {flag = productInfoService.save(info);} catch (Exception e) {e.printStackTrace();}if (flag > 0) {request.setAttribute("msg", "增加成功!!");}else {request.setAttribute("msg", "增加失敗");}// 清空saveFileName里的值,為了下次增加或者修改的異步Ajax圖片上傳saveFileName = "";// 插入成功之后跳轉(zhuǎn)執(zhí)行上面的展示產(chǎn)品return "forward:/prod/split.action"; }運(yùn)行測(cè)試
????????直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.4?商品管理之商品編輯
????????商品編輯有兩個(gè)需求,需求一:就是需要先根據(jù)主鍵p_id查詢(xún)到所有的商品信息,交給前端做一個(gè)回顯的操作。需求二:將前端頁(yè)面中的數(shù)據(jù)更新到數(shù)據(jù)庫(kù)(p_date不做更改),回顯到前端頁(yè)面的數(shù)據(jù)在數(shù)據(jù)庫(kù)按照主鍵p_id進(jìn)行一個(gè)更新操作
???domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)已經(jīng)存在不用創(chuàng)建
mapper層
ProductInfoMapper接口添加方法
/*** 按主鍵p_id查詢(xún)所有的數(shù)據(jù)* @param pid 商品的主鍵* @return 一個(gè)使用實(shí)體類(lèi)封裝好的商品所有信息*/ ProductInfo queryById(int pid);/*** 更新商品信息* @param info 使用實(shí)體類(lèi)封裝好的商品所有信息* @return 是否更新成功*/ int update(ProductInfo info);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件,添加插入數(shù)據(jù)的SQL
<!--按照p_id查找商品的所有信息--> <select id="queryById" parameterType="int" resultMap="BaseResultMap">select * from product_info where p_id=#{p_id} </select><!--更新商品--> <update id="update" parameterType="com.xiaochen.domain.ProductInfo">update product_info set p_name=#{pName},p_content=#{pContent},p_price=#{pPrice},p_image=#{pImage},p_number=#{pNumber},type_id=#{typeId} WHERE p_id=#{pId} </update>service層
ProductInfoService接口添加方法
/*** 按主鍵p_id查詢(xún)所有的數(shù)據(jù)* @param pid 商品的主鍵* @return 一個(gè)使用實(shí)體類(lèi)封裝好的商品所有信息*/ ProductInfo queryById(int pid);/*** 更新商品信息* @param info 使用實(shí)體類(lèi)封裝好的商品所有信息* @return 是否更新成功*/ int update(ProductInfo info);ProductInfoServiceImpl實(shí)現(xiàn)類(lèi)
@Override public ProductInfo queryById(int pid) {ProductInfo productInfo = productInfoMapper.queryById(pid);return productInfo; }@Override public int update(ProductInfo info) {int flag = productInfoMapper.update(info);return flag; }controller層
ProductInfoController實(shí)現(xiàn)兩個(gè)需求
// 根據(jù)主鍵查找商品,并傳遞給前端做一個(gè)回顯的操作(點(diǎn)擊編輯文本框里是該商品在數(shù)據(jù)庫(kù)中的信息) @RequestMapping("/one") public String one(int pid, Model model) {ProductInfo info = productInfoService.queryById(pid);model.addAttribute("prod", info);return "update"; }// 更新商品信息 @RequestMapping("update") public String update(ProductInfo info, HttpServletRequest request) {// 判斷一下,如果點(diǎn)擊編輯之后不去更新圖片的話,saveFileName就是空的,此時(shí)圖片使用的是前端隱藏域信息,圖片的名稱(chēng)從前端域中獲取并回顯// 反之,點(diǎn)擊瀏覽修改圖片信息的話,相當(dāng)于又是一次的Ajax異步上傳,這時(shí)就會(huì)使用UUID生成一個(gè)新的圖片名saveFileName// 需要我們手動(dòng)將圖片的名設(shè)置為saveFileNameif (!saveFileName.equals("")) {info.setpImage(saveFileName);}// 數(shù)據(jù)庫(kù)更新int num = -1;try {num = productInfoService.update(info);} catch (Exception e) {e.printStackTrace();}// 返回msg信息給前端彈窗使用if (num > 0) {request.setAttribute("msg", "更新成功!");}else {request.setAttribute("msg", "更新失敗!");}//清空saveFileName,不影響下一次操作saveFileName = "";// 插入成功之后跳轉(zhuǎn)執(zhí)行上面的展示產(chǎn)品return "forward:/prod/split.action"; }運(yùn)行測(cè)試
????????首先修改一下前端update.jsp第119行左右的一個(gè)代碼
????????直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
?3.5?商品管理之商品刪除
3.5.1 商品刪除之單個(gè)刪除
? ? ? ? 頁(yè)面上的商品刪除工作有一個(gè)需求,就是在第幾頁(yè)刪除之后還是返回還是在第幾頁(yè),只不過(guò)需要用到查詢(xún)的內(nèi)容,于是先讓其返回第一頁(yè),最后再優(yōu)化實(shí)現(xiàn)同頁(yè)返回。
domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)已經(jīng)存在不用創(chuàng)建
mapper層
ProductInfoMapper接口添加方法
/*** 按照主鍵對(duì)商品進(jìn)行刪除* @param pid 商品的主鍵* @return 是否刪除成功*/ int delete(int pid);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件,添加插入數(shù)據(jù)的SQL
<!--按照主鍵刪除商品信息--> <delete id="delete" parameterType="int">delete from product_info where p_id=#{pid} </delete>service層
ProductInfoService接口添加方法
/*** 按照主鍵對(duì)商品進(jìn)行刪除* @param pid 商品的主鍵* @return 是否刪除成功*/ int delete(int pid);ProductInfoServiceImpl實(shí)現(xiàn)類(lèi)
@Override public int delete(int pid) {int flag = productInfoMapper.delete(pid);return flag; }controller層
ProductInfoController實(shí)現(xiàn)兩個(gè)需求
// 更新商品信息 @RequestMapping("/delete") public String delete(int pid, HttpServletRequest request) {// 刪除數(shù)據(jù)int flag = -1;try {flag = productInfoService.delete(pid);} catch (Exception e) {e.printStackTrace();}if (flag > 0) {request.setAttribute("msg", "刪除成功!!");}else {request.setAttribute("msg", "刪除失敗!!");}// 刪除成功之后跳轉(zhuǎn)執(zhí)行上面的展示產(chǎn)品return "forward:/prod/deleteAjaxSplit.action"; }// 返回彈窗的msg信息 @ResponseBody @RequestMapping(value = "/deleteAjaxSplit", produces = "text/html;charset=UTF-8") public Object deleteAjaxSplit(HttpServletRequest request) {// 取得第一頁(yè)的數(shù)據(jù)PageInfo info = productInfoService.splitPage(1, PAGE_SIZE);request.getSession().setAttribute("info", info);// 返回msg語(yǔ)句return request.getAttribute("msg"); }運(yùn)行測(cè)試
????????首先修改一下前端product.jsp的兩處代碼
$.ajax({url:"${pageContext.request.contextPath}/prod/delete.action",data:{"pid":pid},type:"post",dataType:"text",success:function (msg) {alert(msg);$("#table").load("${pageContext.request.contextPath}/admin/product.jsp #table");} });????????直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.5.2?商品刪除之批量刪除
domain層
productInfo數(shù)據(jù)表對(duì)應(yīng)的實(shí)體類(lèi)已經(jīng)存在不用創(chuàng)建
mapper層
ProductInfoMapper接口添加方法
/*** 批量刪除商品* @param ids 刪除商品的主鍵p_id們* @return 是否刪除成功*/ int deleteBatch(String[] ids);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件,添加插入數(shù)據(jù)的SQL
<!--批量刪除商品--> <delete id="deleteBatch">delete from product_info<where><foreach collection="array" item="pid" separator="," open="p_id in(" close=")">#{pid}</foreach></where> </delete>service層
ProductInfoService接口添加方法
/*** 批量刪除商品* @param ids 刪除商品的主鍵p_id們* @return 是否刪除成功*/ int deleteBatch(String[] ids);ProductInfoServiceImpl實(shí)現(xiàn)類(lèi)
@Override public int deleteBatch(String[] ids) {int flag = productInfoMapper.deleteBatch(ids);return flag; }controller層
ProductInfoController實(shí)現(xiàn)兩個(gè)需求
// 批量刪除商品 @RequestMapping("/deleteBatch") public String deleteBatch(String pids, HttpServletRequest request) {// 分隔傳過(guò)來(lái)的字符串,拆分為數(shù)組String[] ps = pids.split(",");// 批量刪除并返回msg信息int flag = productInfoService.deleteBatch(ps);try {if (flag > 0) {request.setAttribute("msg", "批量刪除成功!!");}else {request.setAttribute("msg", "批量刪除成功!!");}} catch (Exception e) {request.setAttribute("msg", "商品不可刪除!!");}return "forward:/prod/deleteAjaxSplit.action"; }運(yùn)行測(cè)試
????????首先修改一下前端product.jsp的一處代碼
function deleteBatch() {//取得所有被選中刪除商品的pidvar cks=$("input[name=ck]:checked");if(cks.length==0){alert("請(qǐng)先選擇將要?jiǎng)h除的商品!!");}else{var str="";var pid="";// 有選中的商品,則取出每個(gè)選 中商品的ID,拼提交的ID的數(shù)據(jù)if(confirm("您確定刪除這"+cks.length+"條商品嗎?")){//拼接ID$.each(cks,function () {pid=$(this).val(); //22 33if(pid!=null) {str += pid + ","; //22,33,44}});//發(fā)送ajax請(qǐng)求進(jìn)行批量刪除$.ajax({url:"${pageContext.request.contextPath}/prod/deleteBatch.action",data:{"pids":str},type:"post",dataType:"text",success:function (msg) {alert(msg);// 重新刷新div塊的內(nèi)容$("#table").load("${pageContext.request.contextPath}/admin/product.jsp #table");}});}}????????直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
3.6?商品管理之多條件查詢(xún)
domain層
domain包下創(chuàng)建一個(gè)vo包,vo包下創(chuàng)建一個(gè)ProductInfoVo類(lèi),用于封裝查詢(xún)條件
public class ProductInfoVo {// 商品名稱(chēng)private String pname;// 商品類(lèi)型private Integer typeid;// 最低價(jià)格private Integer lprice;// 最高價(jià)格private Integer hprice;// 設(shè)置頁(yè)碼private Integer page = 1;public ProductInfoVo() {}public ProductInfoVo(String pname, Integer typeid, Integer lprice, Integer hprice, Integer page) {this.pname = pname;this.typeid = typeid;this.lprice = lprice;this.hprice = hprice;this.page = page;}public String getPname() {return pname;}public void setPname(String pname) {this.pname = pname;}public Integer getTypeid() {return typeid;}public void setTypeid(Integer typeid) {this.typeid = typeid;}public Integer getLprice() {return lprice;}public void setLprice(Integer lprice) {this.lprice = lprice;}public Integer getHprice() {return hprice;}public void setHprice(Integer hprice) {this.hprice = hprice;}public Integer getPage() {return page;}public void setPage(Integer page) {this.page = page;} }mapper層
ProductInfoMapper接口添加方法
/*** 多條件查詢(xún)* @param vo 所有條件的封裝* @return 返回所有的商品信息*/ List<ProductInfo> queryByCondition(ProductInfoVo vo);????????在resource目錄的com/xiaochen/mapper的package中的ProductInfoMapper.xml文件,添加插入數(shù)據(jù)的SQL
<!--多條件查詢(xún)--> <select id="queryByCondition" parameterType="com.xiaochen.domain.vo.ProductInfoVo" resultMap="BaseResultMap">select * from product_info<where><!--商品名稱(chēng)不為空,拼接商品名稱(chēng)的模糊查詢(xún)--><if test="pname != null and pname != ''">and p_name like '%${pname}%'</if><!--拼接商品類(lèi)型--><if test="typeid != null and typeid != -1">and type_id = #{typeid}</if><!--價(jià)格最低價(jià)格不為空,最高價(jià)格為空,大于最低價(jià)格--><if test="(lprice != null and lprice != '') and (hprice == null or hprice == '')">and p_price >= #{lprice}</if><!--最低價(jià)格為空,最高價(jià)格不為空,小于最高價(jià)格--><if test="(lprice == null or lprice == '') and (hprice != null and hprice != '')">and p_price <= #{hprice}</if><!--都不為空,大于最低價(jià)格 且 小于最高價(jià)格--><if test="(lprice != null and lprice != '') and (hprice != null and hprice != '')">and p_price between #{lprice} and #{hprice}</if></where>order by p_id desc </select>service層
ProductInfoService接口添加方法
/*** 多條件查詢(xún)* @param vo 所有條件的封裝* @return 返回所有的商品信息*/ List<ProductInfo> queryByCondition(ProductInfoVo vo);/*** 多條件查詢(xún)分頁(yè)* @param vo 查詢(xún)條件* @param pageSize 每頁(yè)有幾條數(shù)據(jù)* @return*/ PageInfo<ProductInfo> splitPageVo(ProductInfoVo vo, int pageSize);ProductInfoServiceImpl實(shí)現(xiàn)類(lèi)
@Override public List<ProductInfo> queryByCondition(ProductInfoVo vo) {List<ProductInfo> productInfos = productInfoMapper.queryByCondition(vo);return productInfos; }@Override public PageInfo<ProductInfo> splitPageVo(ProductInfoVo vo, int pageSize) {// 分頁(yè)插件使用pageHelper進(jìn)行分頁(yè)設(shè)置PageHelper.startPage(vo.getPage(), pageSize);// 調(diào)用orderById方法,對(duì)product_info表的p_id字段進(jìn)行desc降序操作List<ProductInfo> productInfos = productInfoMapper.queryByCondition(vo);// 將查詢(xún)到的集合封裝到pageInfo對(duì)象中并返回PageInfo<ProductInfo> pageInfo = new PageInfo<>(productInfos);return pageInfo; }controller層
?ProductInfoController修改上面的split方法,調(diào)用分頁(yè)時(shí)判斷是有條件還是無(wú)條件的
// Ajax分頁(yè) @RequestMapping("/split") public String split(HttpServletRequest request) {PageInfo pageInfo = null;// 獲取條件封裝類(lèi)voProductInfoVo prodVo = (ProductInfoVo) request.getSession().getAttribute("prodVo");// 判斷vo中是否有條件if (prodVo != null) {// 如果有條件的話就調(diào)用帶條件的分頁(yè)方法splitPageVo顯示條件頁(yè)面的數(shù)據(jù)pageInfo = productInfoService.splitPageVo(prodVo, PAGE_SIZE);// 從session中清除prodVo,以防對(duì)后面的操作有影響request.getSession().removeAttribute("prodVo");}else {// 如果沒(méi)有條件的話就調(diào)用不帶條件的分頁(yè)方法splitPage顯示第一頁(yè)面的數(shù)據(jù)pageInfo = productInfoService.splitPage(1, PAGE_SIZE);}// 放到域中,前端接收request.setAttribute("info", pageInfo);return "product"; }ProductInfoController修改上面的one方法,更新之后能夠停留在當(dāng)前頁(yè)面
?ProductInfoController修改上面的ajaxSplit方法,翻頁(yè)的時(shí)候獲取頁(yè)碼,停留到vo當(dāng)前頁(yè),如果vo沒(méi)值的話就是第一頁(yè)
// 批量刪除商品 @RequestMapping("/deleteBatch") public String deleteBatch(String pids, HttpServletRequest request) {// 分隔傳過(guò)來(lái)的字符串,拆分為數(shù)組String[] ps = pids.split(",");// 批量刪除并返回msg信息int flag = productInfoService.deleteBatch(ps);try {if (flag > 0) {request.setAttribute("msg", "批量刪除成功!!");}else {request.setAttribute("msg", "批量刪除成功!!");}} catch (Exception e) {request.setAttribute("msg", "商品不可刪除!!");}return "forward:/prod/deleteAjaxSplit.action"; }運(yùn)行測(cè)試
????????首先修改一下前端product.jsp的四處代碼
function one(pid, page) {// 取出查詢(xún)條件var pname = $("#pname").val();var typeid = $("#typeid").val();var lprice = $("#lprice").val();var hprice = $("#hprice").val();//拼接查詢(xún)條件var str = "?pid=" + pid + "&page=" + page + "&pname=" + pname + "&typeid=" + typeid + "&lprice=" + lprice + "&hprice=" + hprice;location.href = "${pageContext.request.contextPath}/prod/one.action" + str; } function ajaxsplit(page) {// 取出查詢(xún)條件var pname = $("#pname").val();var typeid = $("#typeid").val();var lprice = $("#lprice").val();var hprice = $("#hprice").val();//異步ajax分頁(yè)請(qǐng)求$.ajax({url:"${pageContext.request.contextPath}/prod/ajaxsplit.action",data:{"page":page, "pname":pname, "typeid":typeid, "lprice":lprice, "hprice":hprice},type:"post",success:function () {//重新加載分頁(yè)顯示的組件table//location.href---->http://localhost:8080/admin/login.action$("#table").load("http://localhost:8080/admin/product.jsp #table");}}); } function condition() {var pname = $("#pname").val();var typeid = $("#typeid").val();var lprice = $("#lprice").val();var hprice = $("#hprice").val();$.ajax({type:"post",url:"${pageContext.request.contextPath}/prod/ajaxsplit.action",data:{"pname":pname, "typeid":typeid, "lprice":lprice, "hprice":hprice},success:function () {// 刷新顯示table的div$("#table").load("${pageContext.request.contextPath}/admin/product.jsp #table");}}); }???????直接運(yùn)行,切記是tomcat7,9的高版本會(huì)有問(wèn)題?
????????這部分就不再給大家演示了,可以自己操作測(cè)試,完成的成果是:在上面的查詢(xún)時(shí)能按照所填的條件查詢(xún)出相應(yīng)的商品,更新后依舊停留在當(dāng)前頁(yè)面
3.6?商品管理之刪除優(yōu)化
前端代碼修改
//單個(gè)刪除 function del(pid, page) {// 彈窗提示if (confirm("確定刪除嗎")) {// 發(fā)送異步Ajax請(qǐng)求,進(jìn)行刪除操作// 取出查詢(xún)條件var pname = $("#pname").val();var typeid = $("#typeid").val();var lprice = $("#lprice").val();var hprice = $("#hprice").val();$.ajax({url:"${pageContext.request.contextPath}/prod/delete.action",data:{"pid":pid, "page":page, "pname":pname, "typeid":typeid, "lprice":lprice, "hprice":hprice},type:"post",dataType:"text",success:function (msg) {alert(msg);$("#table").load("${pageContext.request.contextPath}/admin/product.jsp #table");}});} }后端?ProductInfoController
// 返回彈窗的msg信息 @ResponseBody @RequestMapping(value = "/deleteAjaxSplit", produces = "text/html;charset=UTF-8") public Object deleteAjaxSplit(HttpServletRequest request) {// 取得第一頁(yè)的數(shù)據(jù)PageInfo info = null;// 獲取條件封裝類(lèi)voProductInfoVo deleteProdVo = (ProductInfoVo) request.getSession().getAttribute("deleteProdVo");// 判斷vo中是否有條件if (deleteProdVo != null) {// 如果有條件的話就調(diào)用帶條件的分頁(yè)方法splitPageVo顯示條件頁(yè)面的數(shù)據(jù)info = productInfoService.splitPageVo(deleteProdVo, PAGE_SIZE);}else {// 如果沒(méi)有條件的話就調(diào)用不帶條件的分頁(yè)方法splitPage顯示第一頁(yè)面的數(shù)據(jù)info = productInfoService.splitPage(1, PAGE_SIZE);}request.getSession().setAttribute("info", info);// 返回msg語(yǔ)句return request.getAttribute("msg"); }至此,棗糕商城ssm項(xiàng)目已經(jīng)算是告一段落了,但是項(xiàng)目本身還存在一些小問(wèn)題和未開(kāi)發(fā)的模塊,敬請(qǐng)大家期待完善
總結(jié)
以上是生活随笔為你收集整理的『收藏向 期末SSM课设救急』 教你从搭建到测试运行手撸一个SSM项目实战,附带源码,前端页面、解析和一般遇到的问题(排雷)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php laravel 返回统一格式,封
- 下一篇: html中所有的标签,HTML中的所有标