快速搭建SSM项目
开发环境:jdk1.8、服务器Tomcat8、项目管理工具apache-maven-3.6.0、MySQL数据库
1、新建项目:
选择【Maven】,勾选【Create from archetype】,选择【maven-archetype-webapp】 (可以选择jdk),具体如下图:
填写【GroupId】和【ArtifactId】等信息,具体如下图:
在【Maven home directory】中选择Maven的安装路径,在【User settings】和【Local repository】中选择Maven的配置文件和仓库的位置(尽量不要使用默认的位置,因为它是放在C盘,需要在Maven文件夹中创建一个文件夹repository),在【Properties】属性列表中添加属性名name:archetypeCatalog,Value:internal,具体如下图:
点击【Finish】,如下图:
创建完成后,在/src/main目录下创建java和resource目录,将java标记为Sources Root、resource标记为Resources Root,具体如下:
2、集成Spring
在pom文件中添加Spring相关的依赖,具体代码如下:
<properties> <spring.version>5.0.5.RELEASE</spring.version> </properties> <!--spring start--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</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-aop</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-expression</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-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- spring end-->
在/src/main/resources目录下创建applicationContext.xml配置文件,具体代码如下:
<?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"> <context:component-scan base-package="com"/>
<!-- <context:component-scan/>注解:扫描base-package包或者子包下所有的Java类,并把匹配的Java类注册成Bean。这里我们设置成扫描com包下所有的Java类 -->
</beans>
在web.xml配置文件中添加如下代码:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--<web-app>--> <display-name>Archetype Created Web Application</display-name>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
</web-app>
3、集成Spring MVC框架
在pom.xml添加相关依赖,具体代码如下:
<properties> <javax.servlet.version>4.0.0</javax.servlet.version> <jstl.version>1.2</jstl.version> </properties> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring mvc end-->
在web.xml配置文件中添加DispatcherServlet配置,具体代码如下:
DispatcherServlet类:DispatcherServlet是前置控制器,主要用于拦截匹配的请求,拦截匹配规则要自己定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理。
<!-- 配置DispatcherServlet--> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC需要加载的配置文件spring-mvc.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>spring-dispatcher</servlet-name>
<!--匹配以.do为后缀的所有请求 --> <url-pattern>*.do</url-pattern> </servlet-mapping>
在/src/main/resources目录下创建配置文件spring-mvc.xml,具体代码如下:
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-- 扫描controller(后端控制器),并且扫描其中的注解 --> <context:component-scan base-package="com.controller"/> <!-- 设置配置方案--> <!--开启注解--> <mvc:annotation-driven/>
<!-- 配置JSP 显示ViewResolver(视图解析器) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
4、集成MyBatis框架
在pom.xml文件中添加相关依赖,具体代码如下:
<properties> <mybatis.version>3.4.6</mybatis.version> <mysql.connector.java.version>8.0.9-rc</mysql.connector.java.version> <druid.version>1.1.9</druid.version> <mybatis.spring.version>1.3.2</mybatis.spring.version> </properties> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.java.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <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> <!-- mybatis end-->
在/src/main/resources目录下创建jdbc.properties配置文件,具体代码如下:
#驱动 jdbc.driverClassName=com.mysql.cj.jdbc.Driver #mysql连接信息 jdbc.url=jdbc:mysql://127.0.0.1:3306/goodsapplydb?serverTimezone=GMT #goodsapplydb为数据库名称
#用户名 jdbc.username=root #密码 jdbc.password=123456
在applicationContext.xml配置文件中添加如下配置,具体代码如下:
<!-- 1、配置数据库相关参数--> <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> <!-- 2、数据源druid--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 3、配置SqlSessionFactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!-- 扫描sql配置文件:mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 扫描basePackage下所有以@MyBatisDao注解的接口--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="com.dao"/> </bean>
5、集成Log4j日志框架
在pom.xml中添加相关依赖,具体代码如下:
<properties> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log4j2 end-->
在/src/main/resources目录下创建log4j.properties配置文件,具体代码如下:
#log levels log4j.rootLogger = DEBUG,Console #输出到控制台 log4j.appender.Console = org.apache.log4j.ConsoleAppender log4j.appender.Console.Target = System.out log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n
6、配置服务器
在IDEA开发菜单栏中,选择【run】—>【Edit Configuration】,点击【+】—>【Tomcat Server】—>【Local】,在【Aplication server】中选择Tomcat的安装路径,在【JRE】中选择JDK的安装路径。
点击【Deployment】—>【+】—>【Artifact】
选择 【下图中选择的】
下图中画红线的地方 删掉(我之前因为没有删掉 就总是报错)
注意下图画红线的地方,在【Deployment】配置好之后,改变下图中的地方。设置这个的目的是:在修改一些东西之后就只需要在浏览器上面刷新一下就可以了,不需要改一点东西重新运行一下程序。
配置好服务器之后,就可以运行程序了。
结果如下图:
下面开发一个比较复杂的画面,将数据库中的数据查询出来显示在画面上
下图为项目的目录: 注意静态资源文件,如css、js等,最好放在webapp目录下面,之前我是放在WEB-INF下面,最后文件总是获取不到
在model目录下创建数据表的实体类
package com.model; import java.io.Serializable; public class goodsApply implements Serializable { //属性首字母需小写 否则在JSP画面中获取时,会报错 private Integer id; private String goodsName; private String claimant; private String applyTime; private String unit; private Integer quantity; private Integer isApply; private String comment; public Integer getId() { return id; } public String getApplyTime() { return applyTime; } public String getClaimant() { return claimant; } public Integer getIsApply() { return isApply; } public String getGoodsName() { return goodsName; } public String getUnit() { return unit; } public Integer getQuantity() { return quantity; } public String getComment() { return comment; } public void setId(Integer id) { this.id = id; } public void setApplyTime(String applyTime) { this.applyTime = applyTime; } public void setClaimant(String claimant) { this.claimant = claimant; } public void setComment(String comment) { this.comment = comment; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } public void setIsApply(Integer isApply) { this.isApply = isApply; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public void setUnit(String unit) { this.unit = unit; } }
在【dao】目录下创建相应接口,该接口与之后的...mapper.xml文件有关
package com.dao; import com.model.goodsApply; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface GoodsApplyDao { List<goodsApply> findAll(); int delGoods(@Param("id") int id); goodsApply findGoodsById(@Param("id") int id); int addGoods(goodsApply goods); int updateGoods(goodsApply goods); }
在【mapper】目录下创建与表相关的mapper文件
<?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.dao.GoodsApplyDao"> <sql id="goodsApplyField"> ${prefix}.id as "id", ${prefix}.goodsName as "goodsName", ${prefix}.claimant as "claimant", ${prefix}.applyTime as "applyTime", ${prefix}.unit as "unit", ${prefix}.quantity as "quantity", ${prefix}.isApply as "isApply", ${prefix}.comment as "comment" </sql> <!-- 获取所有物品申请记录--> <resultMap id="goodsApplyMap" type="com.model.goodsApply"> <id property="id" column="id"/> <id property="goodsName" column="goodsName"/> <id property="claimant" column="claimant"/> <id property="applyTime" column="applyTime"/> <id property="unit" column="unit"/> <id property="quantity" column="quantity"/> <id property="isApply" column="isApply"/> <id property="comment" column="comment"/> </resultMap>
<!-- 下面的id与dao文件中的方法名称相同 --> <select id="findAll" resultMap="goodsApplyMap"> select <include refid="goodsApplyField"> <property name="prefix" value="a"/> </include> from goodsApplyTb as a </select>
<!-- 根据id删除一条物品记录--> <delete id="delGoods" parameterType="int"> delete from goodsApplyTb where id=#{id} </delete> <!-- 根据id查询一条物品记录--> <select id="findGoodsById" resultMap="goodsApplyMap" parameterType="int"> select <include refid="goodsApplyField"> <property name="prefix" value="a"/> </include> from goodsApplyTb as a where id=#{id} </select> <!-- 新增一条记录--> <insert id="addGoods" useGeneratedKeys="true" keyProperty="id" parameterType="com.model.goodsApply"> insert into goodsApplyTb(goodsName,claimant,applyTime,unit,quantity,isApply,comment) value(#{goodsName},#{claimant},#{applyTime},#{unit},#{quantity},#{isApply},#{comment}) </insert> <!-- 修改一条记录--> <update id="updateGoods" parameterType="com.model.goodsApply"> update goodsApplyTb set goodsName=#{goodsName}, claimant=#{claimant}, applyTime=#{applyTime}, unit=#{unit}, quantity=#{quantity}, isApply=#{isApply}, comment=#{comment} where id=#{id} </update> </mapper>
在【service】目录下创建相应的接口
package com.service; import com.model.goodsApply; import java.util.List; public interface GoodsApplyService { List<goodsApply> findAll(); int delGoods(int id); goodsApply findGoodsById(int id); int addGoods(goodsApply goods); int updateGoods(goodsApply goods); }
在【impl】目录下创建相应的service接口的实现类
package com.service.impl; import com.dao.GoodsApplyDao; import com.model.goodsApply; import com.service.GoodsApplyService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class GoodsApplyServiceImpl implements GoodsApplyService { @Resource private GoodsApplyDao goodsApplyDao; public List<goodsApply> findAll(){ return goodsApplyDao.findAll(); } public int delGoods(int id){ return goodsApplyDao.delGoods(id); } public goodsApply findGoodsById(int id){ return goodsApplyDao.findGoodsById(id); } public int addGoods(goodsApply goods){ return goodsApplyDao.addGoods(goods); } public int updateGoods(goodsApply goods){ return goodsApplyDao.updateGoods(goods); } }
在【controller】目录下创建controlle类
import com.model.goodsApply; import com.service.GoodsApplyService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; import static java.lang.Integer.parseInt; @Controller public class GoodsApplyController { @Resource private GoodsApplyService goodsApplyService; @GetMapping("/goodsList.do") public ModelAndView findAll(){ List<goodsApply> goodsApplyList=goodsApplyService.findAll(); // for (goodsApply goods : goodsApplyList) { // System.out.println(goods.getClaimant()+"申请了"+goods.getGoodsName()); // } ModelAndView mv = new ModelAndView(); mv.addObject("goodsApplyList",goodsApplyList);
//将查询到的数据返回到画面
mv.setViewName("goodsList"); return mv; } }
下面是相应的jsp画面
在index.jsp中直接跳转到goodsList.jsp画面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <% String path = request.getContextPath(); // http://localhost:8080 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML> <html> <head> <base href="<%=basePath%>"> <script type="text/javascript"> window.location = "<%=basePath%>goodsList.do"; </script> </head> <body> <h2>Hello World!</h2> </body> </html>
下面为goodsList.jsp画面
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="com.model.goodsApply" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path+"/"; %> <!DOCTYPE html> <html> <head> <%-- <base href="<%=basePath%>">--%> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>物品申请</title> <link rel="stylesheet" href="<%=path%>/css/goodsList.css"> <link href="<%=path%>/css/jquery-confirm.min.css" rel="stylesheet"> <script src="<%=path%>/js/jquery.min.js" type="text/javascript"></script> <script src="<%=path%>/js/jquery-confirm.min.js" type="text/javascript"></script> <script type="text/javascript"> //删除操作 function del(obj) { $('.delete').confirm({ title: '提示!', content: '您确定要删除这条数据?', type:'green', buttons: { 确定: function () { var id = $(obj).attr("rel"); window.location = "<%=basePath%>goodsDel.do?id=" + id; }, 取消: function () { // $.alert('取消!'); } } }); } // 跳转新增页面 function addGoods() { window.location="<%=basePath%>addGoods.do"; } // 修改记录 function updateGoods(obj) { var id = $(obj).attr("rel"); window.location = "<%=basePath%>selectGoods.do?id=" + id; } </script> </head> <body> <div class="content"> <div> <input type="button" value="新增" class="button" onclick="addGoods()"> <input type="hidden" value="${delete_result}" id="del_result"> <input type="hidden" value="${insert_result}" id="ins_result"> <input type="hidden" value="${update_result}" id="upd_result"> </div> <table id="goodsContent"> <thead> <tr> <th class="table-goodsname">物品名称</th> <th class="table-claimant">申领人</th> <th class="table-applyTime">申领时间</th> <th class="table-unit">单位</th> <th class="table-quantity">数量</th> <th class="table-isApply">已领</th> <th class="table-operate">操作</th> </tr> </thead> <tbody> <c:if test="${empty goodsApplyList}"> <tr> <td colspan="7" style="color: red"><b>没有数据!</b></td> </tr> </c:if> <c:forEach var="goodsApply" items="${goodsApplyList}"> <tr> <td>${goodsApply.goodsName}</td> <td>${goodsApply.claimant}</td> <td>${goodsApply.applyTime}</td> <td>${goodsApply.unit}</td> <td>${goodsApply.quantity}</td> <td id="isApply">${goodsApply.isApply}</td> <td> <input type="hidden" value="${goodsApply.id}" id="goodsId"> <a href="javascript:void(0)" class="operate alter" id="update" rel="${goodsApply.id}" onclick="updateGoods(this)">修改</a> <a href="javascript:void(0)" class="operate delete" id="delete" rel="${goodsApply.id}" onclick="del(this)">删除</a> </td> </tr> </c:forEach> </tbody> </table> </div> <script type="text/javascript"> var del_result = $('#del_result').val(); if(del_result==="success"){ alert("删除成功!"); } if(del_result==="failed"){ alert("删除失败!"); } var ins_result=$('#ins_result').val(); if(ins_result==="success"){ alert("新增成功!"); } var upd_result = $('#upd_result').val(); if(upd_result==="success"){ alert("修改成功!"); } if(upd_result==="failed"){ alert("修改失败!"); } $(document).ready(function () { $('#goodsContent tr').each(function () { var isApply=$(this).children('td:eq(5)').text(); if(isApply==="1"){ $(this).children('td:eq(5)').html('是'); // 当已经领用了的,不允许再删除 把删除按钮禁用 $(this).children('td:eq(6)').find('#delete').css("cursor","default"); $(this).children('td:eq(6)').find('#delete').css("color","grey"); $(this).children('td:eq(6)').find('#delete').removeAttr("onclick"); } else { $(this).children('td:eq(5)').html('否'); } }); }); </script> </body> </html>
最后还需要改一下web.xml文件。
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--<web-app>-->
<!--将web-app改为上面的-->
如果不改,会是下图这种情况
程序运行结果如下图
该程序还有新增、修改以及删除功能,具体可以下载全部程序查看
https://pan.baidu.com/s/15Jjrd4P6oWpa9gRLm2XLiQ