idea中使用Maven,基于SSM(spring,springMVC,Mybatis)实现对tb_news表的增删该查

需求:

idea中使用Maven,基于SSM(spring,springMVC,Mybatis)实现对tb_news表的增删该查。要求要有简单的前台页面。

步骤:

第一步:新建Maven项目



第二步:导入SSM所依赖的jar包


1. 在pom.xml文件中配置<properties>标签。

  • <properties>标签:这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过 properties 元素的子元素来传递。
  • 代码:
<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <!-- spring版本号 -->
        <spring.version>4.3.3.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.4.1</mybatis.version>
        <!-- oracle驱动 -->
        <ojdbc6.version>11.2.0.4.0</ojdbc6.version>
        <!-- log4j日志文件管理包版本 -->
        <log4j.version>1.2.17</log4j.version>
        <!-- jackson版本号 -->
        <jackson.version>2.8.3</jackson.version>
    </properties>

2.导入依赖的jar包(网上可以搜索到类似的ssm框架整合所需要的jar包的稳定版,暂测我这个还可以)

  • 复制进入<dependencies>标签中,自动下载后,jar包导入完毕。
  • 代码:
 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</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.springframework</groupId>
            <artifactId>spring-aop</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>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- 导入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>


        <!-- log end -->

        <!-- 映入JSON -->

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- 上传组件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.12</version>
        </dependency>
        <!-- redis 开始 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.0.0</version>
        </dependency>
        <!-- redis 结束-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.10</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${ojdbc6.version}</version>
        </dependency>
    </dependencies>

第三步:项目中构建包结构


  • 基本包结构
    在这里插入图片描述
  • java文件夹:存放java代码(控制层,服务层,dao层,实体类,工具类。。。)
  • resources文件夹:存放各种配置文件(spring配置文件、springMVC-Mybatis整合的配置文件、数据库池等)
  • mapper文件夹:存放各个dao层实现类的映射文件。在resources下。
  • js包:存放js包,类似与静态资源。
  • jsp:存放jsp页面。
    js和jsp的文件夹存放位置看个人喜好。。。。。

第四步:配置spring

  • 打开web.xml文件(wabapp->WEB-INF->web.xml)
  • 分三步:
  1. 配置监听器(监听spring-mybatis-config.xml文件)
  2. 配置总调度器(配置springmvc)
  3. 配置spring自带的字符编码过滤器
  • 代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <!-- spring监听器 开始 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis-config.xml</param-value>
  </context-param>
  <!-- spring监听器 结束-->

  <!-- 配置总的调度器 开始 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 不配置init-param这个配置,默认框架会去找与web.xml同级目录下名字为hello-servlet.xml的文件 -->
    <init-param>
      <!-- spring源码加载自定义配置文件的时候,默认调用contextConfigLocation名称,所以是固定的,不能更改-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-config.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 配置总的调度器 结束 -->
    <filter>
        <filter-name>charSetFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>charSetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 解决post提交乱码 结束-->
</web-app>
  • 问题:此时有两处错误,是因为这两个文件还没有建成
    在这里插入图片描述

第五步:配置springmvc

  • 在resources文件夹中新建xml文件springmvc-config,xml
    在这里插入图片描述
  • 配置springmvc-config.xml文件
  • 分四步:
  1. 开启包扫描(扫描controller层)
  2. 开启springMVC注解驱动
  3. 开启视图解析器
  4. 上传配置
  • 代码:
<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 开启包扫描 -->
    <context:component-scan base-package="com.aaa.ssm.controller"></context:component-scan>
    <!-- 开启springmvc注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 上传配置 -->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"></property>
    </bean>
</beans>
  • 点开web.xml文件发现这一个文件已经不报红了,下面解决spring和mybatis的整合配置。
    在这里插入图片描述

第六步:配置spring-mybatis-config.xml

  • 在resources文件夹下新建spring-mybatis-config.xml文件(这个文件用于整合spring和mybatis)
    在这里插入图片描述
  • 分七步:
  1. 开启包扫描(扫描service层,这里报红是因为还没有这个文件)
  2. 加载数据源配置文件
  3. dbcp连接池配置(数据库有关,我这里配置的数据库连接池,连接池下一步配置,暂时报错)
  4. 创建SqlSessionFactory (mybatis使用SqlSessionFactory 来将dao实例化,还没有配置mapper/*.xml文件,展示报错)
  5. 利用配置的mybatis接口和配置文件 把dao实例化
  6. 配置事务管理类
  7. 开启注解事务
  • 代码:
<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启包扫描 -->
    <context:component-scan base-package="com.aaa.ssm.service"/>
    <!-- 加载数据源配置文件 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:dbcp.properties"></property>
    </bean>
    <!-- dbcp连接池配置 -->
    <bean id="dataSourceA" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="initialSize" value="${initialSize}"></property>
        <property name="maxActive" value="${maxActive}"></property>
        <property name="maxIdle" value="${maxIdle}"></property>
        <property name="minIdle" value="${minIdle}"></property>
        <property name="maxWait" value="${maxWait}"></property>

    </bean>
    <!-- 创建SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载数据源 -->
        <property name="dataSource" ref="dataSourceA"></property>
        <!-- 加载mapper文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!-- 利用配置的mybatis接口和配置文件 把dao实例化 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.aaa.ssm.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- 配置事务管理类 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSourceA"></property>
    </bean>
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
  • 配置数据库连接池
  • 在resources文件下新建dbcp.properties文件
    在这里插入图片描述
  • 代码:
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=scott
jdbc.password=luruihua
#初始连接数
initialSize=5
#最大活跃数
maxActive=10
#最大空闲连接
maxIdle=2
#最小idle数
minIdle=1
#最长等待时间(毫秒)
maxWait=1000
  • 配置告一段落。。。。。。。。

第七步:写java代码和jsp

在这里插入图片描述

  • 按照上图来新建包名(包名和扫描的地方要对应起来)
    -在这里插入图片描述

sql,创建一个.sql文件导入数据库

prompt PL/SQL Developer import file
prompt Created on 20181120by admin
set feedback off
set define off
prompt Creating TB_NEWS...
create table TB_NEWS
(
 newsid   NUMBER(3) not null,
 title    VARCHAR2(20),
 content  VARCHAR2(500),
 typeid   NUMBER(3),
 clicknum NUMBER(10)
)
tablespace USERS
 pctfree 10
 initrans 1
 maxtrans 255
 storage
 (
   initial 64K
   minextents 1
   maxextents unlimited
 );
alter table TB_NEWS
 add primary key (NEWSID)
 using index 
 tablespace USERS
 pctfree 10
 initrans 2
 maxtrans 255
 storage
 (
   initial 64K
   minextents 1
   maxextents unlimited
 );

prompt Creating TB_NEWSTYPE...
create table TB_NEWSTYPE
(
 typeid   NUMBER(3) not null,
 typename VARCHAR2(20),
 addtime  DATE
)
tablespace USERS
 pctfree 10
 initrans 1
 maxtrans 255
 storage
 (
   initial 64K
   minextents 1
   maxextents unlimited
 );
alter table TB_NEWSTYPE
 add primary key (TYPEID)
 using index 
 tablespace USERS
 pctfree 10
 initrans 2
 maxtrans 255
 storage
 (
   initial 64K
   minextents 1
   maxextents unlimited
 );

prompt Disabling triggers for TB_NEWS...
alter table TB_NEWS disable all triggers;
prompt Disabling triggers for TB_NEWSTYPE...
alter table TB_NEWSTYPE disable all triggers;
prompt Deleting TB_NEWSTYPE...
delete from TB_NEWSTYPE;
commit;
prompt Deleting TB_NEWS...
delete from TB_NEWS;
commit;
prompt Loading TB_NEWS...
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (1, 'java1', '123', 1, 100);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (2, 'java2', '1234', 1, 100);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (3, 'java3', '1235', 1, 101);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (4, 'php1', '1235', 2, 102);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (5, 'php2', '1235', 2, 103);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (6, 'c++1', '1235', 3, 104);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (7, 'c++2', '1235', 3, 1005);
insert into TB_NEWS (newsid, title, content, typeid, clicknum)
values (8, 'c++3', '1235', 3, 1001);
commit;
prompt 8 records loaded
prompt Loading TB_NEWSTYPE...
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (1, 'java', to_date('13-11-2018 19:38:50', 'dd-mm-yyyy hh24:mi:ss'));
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (2, 'php', to_date('13-11-2018 19:38:50', 'dd-mm-yyyy hh24:mi:ss'));
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (3, 'c++', to_date('13-11-2018 19:38:50', 'dd-mm-yyyy hh24:mi:ss'));
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (4, 'python', to_date('13-11-2018 20:00:55', 'dd-mm-yyyy hh24:mi:ss'));
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (5, 'com', to_date('13-11-2018 20:00:55', 'dd-mm-yyyy hh24:mi:ss'));
insert into TB_NEWSTYPE (typeid, typename, addtime)
values (6, 'aaa', to_date('13-11-2018 20:00:55', 'dd-mm-yyyy hh24:mi:ss'));
commit;
prompt 6 records loaded
prompt Enabling triggers for TB_NEWS...
alter table TB_NEWS enable all triggers;
prompt Enabling triggers for TB_NEWSTYPE...
alter table TB_NEWSTYPE enable all triggers;
set feedback on
set define on
prompt Done.

add.jsp代码

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/20
  Time: 14:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加页面</title>
    <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
    //获取新闻类别
    $(function(){
        var str='';
        $.get(
            "/news/getNewsTypeList.do",
            function(data) {
                if(data!=''){
                    $("#typeName").empty();
                    for(var i = 0;i<data.length;i++){
                        str += "<option  value = '"+data[i].TYPENAME+"'>"+data[i].TYPENAME+"</option>";	//拼接option
                    }
                    $("#typeName").append(str);
                }
            },
            "json"
        );
    });
    //添加按钮
    function insertNews() {
        var title = $("#title").val();
        var content = $("#content").val();
        var typeName = $("#typeName").val();
        $.get(
            "/news/insertNews.do",
            {title:title,content:content,typeName:typeName},
            function(data) {
                alert(data.msg);
                location.href="/news/list.do";
            },
            "json"
        );
    }
    </script>
</head>
<body>
<center>
    <h1>添加员工</h1>

        <table>
            <tbody>
            <tr>
                <td>新闻题目</td><td><input  id="title" type="text"></td>
            </tr>
            <tr>
                <td>内容</td><td><input id="content" type="text"></td>
            </tr>
            <tr>
                <td>类别</td>
                <td>
                    <select id="typeName" >

                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input onclick="insertNews()" type="button" value="添加"></td>
            </tr>
            </tbody>
        </table>
</center>
</body>
</html>

list.jsp代码

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/20
  Time: 14:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>新闻列表</title>
    <script src="/js/jquery-1.8.3.js"></script>
    <script>
        function addOne() {
            location.href="/news/locationAdd.do";
        }
    </script>
</head>
<body>
<center>
    <h1>新闻列表</h1>
    <input type="button" onclick="addOne()" value="添加">
    <table border="1">
        <tr><td>新闻题目</td> <td>内容</td> <td>类别</td><td>点击数</td> <td>操作</td> </tr>
        <c:forEach items="${newList}" var="news">
            <tr>
                <td hidden="hidden">${news.NEWSID}</td>
                <td>${news.TITLE}</td>
                <td>${news.CONTENT}</td>
                <td>${news.TYPENAME}</td>
                <td>${news.CLICKNUM}</td>
                <td><input type="button" value="更新" onclick="location='/news/locationUpdate.do?newsId=${news.NEWSID}'"/></a> &nbsp;
                    <input type="button" value="删除" onclick="deleteOne(${news.NEWSID})"/></a>
                </td>
            </tr>
        </c:forEach>
        <tr><td colspan="5" align="center"> ${pageString}</td> </tr>
    </table>
</center>
<script>
    function deleteOne(newsId) {
        if(confirm("确定删除吗?")){
            $.get(
                "/news/deleteNews.do",
                {newsId:newsId},
                function(data) {
                    alert(data.msg);
                    location.href="/news/list.do";
                },
                "json"
            );
        }
    }
</script>
</body>
</html>

update.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/20
  Time: 14:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>更新页面</title>
    <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
    //获取新闻类别
    $(function(){
       var str='';
         $.get(
            "/news/getNewsTypeList.do",
            function(data) {
                if(data!=''){
                    $("#typeName").empty();
                    for(var i = 0;i<data.length;i++){
                        str += "<option>"+data[i].TYPENAME+"</option>";	//拼接option
                    }
                    $("#typeName").append(str);
                }
            },
            "json"
        );
    });
    //更新按钮
    function insertNews() {
        var newsId = $("#newsId").val();
        var title = $("#title").val();
        var content = $("#content").val();
        var typeName = $("#typeName").val();
        $.get(
            "/news/updateNews.do",
            {title:title,content:content,typeName:typeName,newsId:newsId},
            function(data) {
                alert(data.msg);
                location.href="/news/list.do";
            },
            "json"
        );
    }

    </script>
</head>
<body>
<center>
    <h1>更新员工</h1>

        <table>
            <tbody>
            <c:forEach items="${newsList}" var="news">
            <tr>
                <td>新闻编号</td>
                <td><input readonly="readonly" id="newsid" value="${news.NEWSID}" type="text"></td>
            </tr>
            <tr>
                <td>新闻题目</td><td><input  id="title" value="${news.TITLE}" type="text"></td>

            </tr>
            <tr>
                <td>内容</td><td><input id="content" value="${news.CONTENT}" type="text"></td>
            </tr>
            <tr>
                <td>类别</td>
                <td>
                    <select id="typeName" value="${typeName}">

                    </select>
                </td>
            </tr>
            </c:forEach>
            <tr>
                <td colspan="2" align="center"><input onclick="insertNews()" type="button" value="更新"></td>
            </tr>
            </tbody>
        </table>
</center>
</body>
</html>

NewDaoMapper.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.aaa.ssm.dao.NewDao">
    <!--新闻分页查询-->
    <select id="getList" parameterType="map" resultType="map">
        select * from (
          select rownum rn,n.newsid,n.title,n.content,t.typename,n.clicknum
          from tb_news n
          join tb_newstype t
          on n.typeid = t.typeid
          where rownum &lt; #{end}
        ) a where a.rn &gt; #{start}
    </select>
    <!--查询分页总数量-->
    <select id="getCount" resultType="int">
        select count(*) as cnt from tb_news
    </select>
    <!--添加新闻-->
    <insert id="insertNews">
        insert into tb_news (newsid,title,content,typeid)values (seq_newsid.nextval,#{title}, #{content}, #{typeId})
    </insert>
    <!--通过id查news-->
    <select id="selectNewsMsgById" resultType="map">
        select n.newsid,n.title,n.content,t.typename,t.typeid
        from tb_news n
        join tb_newstype t
        on n.typeid = t.typeid
        where newsid = #{newsId}
    </select>
    <update id="updateNews">
        update tb_news
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="content != null">
                content = #{content},
            </if>
            <if test="typeId != null">
                typeid = #{typeId},
            </if>
        </set>
        where newsid = #{newsId}
    </update>
    <delete id="deleteNews">
        delete from tb_news where newsid = #{newsId}
    </delete>
</mapper>

NewsTypeDaoMapper.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.aaa.ssm.dao.NewsTypeDao">
    <select id="getNewsTypeLsit" resultType="map">
        select typename from tb_newstype
    </select>
    <select id="getNewsTypeId" resultType="map">
        select typeid from tb_newstype
        <where>
            <if test="typeName != null">
                and typename=#{typeName}
            </if>
        </where>
    </select>
</mapper>

PageUtil.java

package com.aaa.ssm.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * className:PageUtil
 * discription:
 * author:luRuiHua
 * createTime:2018-11-19 11:48
 */
public class PageUtil {
    //分页的要素
    private int pageNo;//页码(第几页)
    private int pageSize;//每页显示数量
    private int totalSize;//总条数
    //临时变量
    private String url;//请求的url
    private String pageString;//拼接后的分页字符串

    /**
     * 构造
     * @param pageNo
     * @param pageSize
     * @param totalSize
     * @param request  可以用来获取当前请求的地址和所有的请求参数
     */
    public PageUtil(int pageNo, int pageSize, int totalSize, HttpServletRequest request){
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.totalSize = totalSize;
        //获取本次请求的url(从项目名称开始)
        url = request.getRequestURI()+"?";  //  /web20180918/jsp/page/page3.jsp?pageNo=2&dname=内&id=&aa=11&bb=22
        //getParameterNames获取所有请求中带的参数的名称  pageNo=2&dname=内&id=   getParameterNames获取到结果为:
        Enumeration<String> parameterNames = request.getParameterNames();//获取参数名称集合  [pageNo,dname,id]
        while(parameterNames.hasMoreElements()){//判断有没有下一个元素
            String parameterName = parameterNames.nextElement();//第一次取到的pageNo
            //!"pageNo".equals(parameterName)  每次请求,pageNo都在变化,所以下面拼接pageString一直会带上
            if(!"pageNo".equals(parameterName)){
                //charAt 得到字符串某个位置的上的字符
                if(url.charAt(url.length()-1)=='?'){//判断请求的最后位置是否是?
                    url+=parameterName+"="+request.getParameter(parameterName);// /web20180918/jsp/page/page3.jsp?dname=内
                }else{
                    url+="&"+parameterName+"="+request.getParameter(parameterName);///web20180918/jsp/page/page3.jsp?dname=内&id=&&aa=11&
                }
            }
        }
        //为了下面拼接简单
        if(url.charAt(url.length()-1)!='?'){
            url+="&";
        }
    }
    // url =/web20180918/jsp/page/page3.jsp?dname=内&id=&&aa=11&
    /**
     * 拼装分页字符串
     * @return
     */
    public String getPageString(){
        //计算总页数
        int pageCount = totalSize%pageSize==0?totalSize/pageSize:totalSize/pageSize+1;
        StringBuffer stringBuffer = new StringBuffer();
        //上一页不能小于1
        if(pageNo<1){
            pageNo = 1;
        }
        if(pageNo>1){//不是第一页
            stringBuffer.append("<a href='"+url+"pageNo=1'>首页</a>&nbsp;<a href='"+url+"pageNo="+(pageNo-1)+"'>上一页</a>");
        }else{
            stringBuffer.append("首页&nbsp;上一页");
        }
        stringBuffer.append("&nbsp;");
        //不能大于最大页
        if(pageNo>pageCount){
            pageNo=pageCount;
        }
        if(pageNo<pageCount){//不是最大页(尾页)
            stringBuffer.append("<a href='"+url+"pageNo="+(pageNo+1)+"'>下一页</a>&nbsp;<a href='"+url+"pageNo="+pageCount+"'>尾页</a>");
        }else{
            stringBuffer.append("下一页&nbsp;尾页");
        }
        stringBuffer.append("&nbsp;");
        //拼装下拉第几页                                                                                                                                                                                //this.value  select元素选中值
        stringBuffer.append("第<select onchange=\"javascript:window.location.href='"+url+"pageNo='+this.value\">"); //为select添加onchange事件,能选择自定义页数
        for(int i=1;i<=pageCount;i++){
            if(pageNo==i){//如果当前页码(第几页)和i相等,让option被选中 selected='selected'
                stringBuffer.append("<option value='"+i+"' selected='selected'>"+i+"</option>");
            }else{
                stringBuffer.append("<option value='"+i+"'>"+i+"</option>");
            }
        }
        stringBuffer.append("</select>页&nbsp;共"+totalSize+"条&nbsp;"+pageCount+"页");
        return stringBuffer.toString();
    }
}

NewController.java

package com.aaa.ssm.controller;

import com.aaa.ssm.service.NewService;
import com.aaa.ssm.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * className:NewController
 * discription:
 * author:luRuiHua
 * createTime:2018-11-20 14:03
 */
@Controller
@RequestMapping("/news")//通用配置
public class NewController {
    //依赖注入
    @Autowired
    private NewService newService;
    /**
     * 获取新闻分页列表
     * @return
     */
    @RequestMapping("/list")//窄化映射请求
    public String getNewList(Integer pageNo, Model model, HttpServletRequest request){
        int pageSize=2;
        Map map = new HashMap();
        int tPageNo = pageNo==null?1:pageNo;
        map.put("pageNo",tPageNo);
        map.put("pageSize",pageSize);
        PageUtil pageUtil = new PageUtil(tPageNo, pageSize, newService.getCount(map), request);
        String pageString = pageUtil.getPageString();
        model.addAttribute("pageString",pageString);
        model.addAttribute("newList",newService.getList(map));
        return "new/list";
    }

    /**
     * 列表页面的添加按钮跳转功能
     * @return
     */
    @RequestMapping("/locationAdd")
    public String locationAdd() {
        return "new/add";
    }
    /**
     * 列表页面的更新按钮跳转功能
     * @return
     */
    @RequestMapping("/locationUpdate")
    public String locationUpdate(@RequestParam Map paramMap,Model model) {
        List<Map> news = newService.selectNewsMsgById(paramMap);
        System.out.println(news);
        model.addAttribute("newsList",news);
        return "new/update";
    }
    /**
     * 获取新闻类别名字
     * @return
     */
    @ResponseBody
    @RequestMapping("/getNewsTypeList")
    public Object getNewsTypeList() {
        return newService.getNewsTypeList();
    }



    /**
     * 插入新闻
     * @return
     */
    @ResponseBody
    @RequestMapping("/insertNews")
    public Object insertNews(@RequestParam Map map) {
        int i = newService.insertNews(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","添加成功!");
        } else {
            map1.put("msg","添加失败!");
        }
        return map1;
    }

    /**
     * 更新新闻
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateNews")
    public Object updateNews(@RequestParam Map map) {
        int i = newService.updateNews(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","更新成功!");
        } else {
            map1.put("msg","更新失败!");
        }
        return map1;
    }
    /**
     * 删除新闻
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteNews")
    public Object deleteNews(@RequestParam Map map) {
        int i = newService.deleteNews(map);
        Map map1 = new HashMap();
        if (i > 0) {
            map1.put("msg","删除成功!");
        } else {
            map1.put("msg","删除失败!");
        }
        return map1;
    }
}

NewDao.java

package com.aaa.ssm.dao;

import java.util.List;
import java.util.Map;

/**
 * className:NewDao
 * discription:
 * author:luRuiHua
 * createTime:2018-11-20 14:02
 */
public interface NewDao {
    /**
     * 获取分页列表
     * @return
     */
    List<Map> getList(Map map);

    /**
     * 获取分页总数量
     * @param map
     * @return
     */
    int getCount(Map map);

    /**
     * 添加新闻
     * @param map
     * @return
     */
    int insertNews(Map map);

    /**
     * 通过id查news
     * @param paramMap
     * @return
     */
    List<Map> selectNewsMsgById(Map paramMap);

    /**
     * 更新新闻
     * @param map
     * @return
     */
    int updateNews(Map map);

    /**
     * 删除
     * @param map
     * @return
     */
    int deleteNews(Map map);
}

NewsTypeDao.java

package com.aaa.ssm.dao;

import java.util.List;
import java.util.Map;

/**
 * className:NewsTypeDao
 * discription:
 * author:luRuiHua
 * createTime:2018-11-20 16:21
 */
public interface NewsTypeDao {
    /**
     * 获取新闻类别
     * @return
     */
    List<Map> getNewsTypeLsit();

    /**
     * 获取新闻类别id
     * @param map
     * @return
     */
    List<Map> getNewsTypeId(Map map);
}

NewService.java

package com.aaa.ssm.service;

import java.util.List;
import java.util.Map;

/**
 * className:NewService
 * discription:
 * author:luRuiHua
 * createTime:2018-11-20 14:03
 */
public interface NewService {
    /**
     * 获取分页列表
     * @return
     */
    List<Map> getList(Map map);

    /**
     * 获取分页总数量
     * @param map
     * @return
     */
    int getCount(Map map);

    /**
     * 获取新闻类型信息
     * @return
     */
    List<Map> getNewsTypeList();

    /**
     * 添加新闻
     * @return
     */
    int insertNews(Map map);

    /**
     * 通过id查新闻信息
     * @param paramMap
     * @return
     */
    List<Map> selectNewsMsgById(Map paramMap);

    /**
     * 更新新闻
     * @param map
     * @return
     */
    int updateNews(Map map);

    /**
     * 删除
     * @param map
     * @return
     */
    int deleteNews(Map map);
}

NewServiceImpl.java

package com.aaa.ssm.service;

import com.aaa.ssm.dao.NewDao;
import com.aaa.ssm.dao.NewsTypeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * className:NewServiceImpl
 * discription:
 * author:luRuiHua
 * createTime:2018-11-20 14:03
 */
@Service
public class NewServiceImpl implements NewService{
    //依赖注入
    @Autowired
    private NewDao newDao;
    @Autowired
    private NewsTypeDao newsTypeDao;

    /**
     * 获取分页列表
     * @param map
     * @return
     */
    @Override
    public List<Map> getList(Map map) {
        int pageNo =map.get("pageNo")==null?1:Integer.valueOf(map.get("pageNo")+"");
        int pageSize =map.get("pageSize")==null?5:Integer.valueOf(map.get("pageSize")+"");
        map.put("start",(pageNo-1)*pageSize);
        map.put("end",pageNo*pageSize+1);
        return newDao.getList(map);
    }

    /**
     * 获取分页数量
     * @param map
     * @return
     */
    @Override
    public int getCount(Map map) {
        return newDao.getCount(map);
    }

    /**
     * 获取新闻类型信息
     * @return
     */
    @Override
    public List<Map> getNewsTypeList() {
        List<Map> newsTypeLsit = newsTypeDao.getNewsTypeLsit();
        return newsTypeLsit;
    }

    /**
     * 添加新闻
     * @return
     */
    @Override
    public int insertNews(Map map) {
        List<Map> newsTypeId = newsTypeDao.getNewsTypeId(map);
        String typeid = newsTypeId.get(0).get("TYPEID")+"";
        map.put("typeId",typeid);
        int i = newDao.insertNews(map);
        return i;
    }

    /**
     * 通过id来查新闻信息
     * @param paramMap
     * @return
     */
    @Override
    public List<Map> selectNewsMsgById(Map paramMap) {
        List<Map> news = newDao.selectNewsMsgById(paramMap);
        return news;
    }

    /**
     * 更新新闻
     * @param map
     * @return
     */
    @Override
    public int updateNews(Map map) {
        List<Map> newsTypeId = newsTypeDao.getNewsTypeId(map);
        int typeid = Integer.valueOf(newsTypeId.get(0).get("TYPEID") + "");
        System.out.println(typeid);
        map.put("typeId",typeid);
        System.out.println(map);
        int i = newDao.updateNews(map);

        return i;
    }

    /**
     * 删除
     * @param map
     * @return
     */
    @Override
    public int deleteNews(Map map) {
        return newDao.deleteNews(map);
    }
}

总结:

  • 主要是搭ssm框架,再写各层代码的时候还是错误频出,好久没写增删该查了,还是得多练练。如有错误,敬请纠正!感谢!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值