IDEA实现SSM框架整合并在网页上显示数据

IDEA实现SSM框架整合并在网页上显示数据

关注公众号,每天更新优质好文!
IDEA实现SSM框架整合并在网页上显示数据_第1张图片
IDEA实现SSM框架整合并在网页上显示数据_第2张图片

接下来我们来整合SSM框架。

第一步、

创建一个maven工程。配置Tomcat,并测试是否正常访问HelloWorld.
这一步就省略了。
不懂得看这个博客:

idea创建maven项目

创建出来是这样的:
IDEA实现SSM框架整合并在网页上显示数据_第3张图片

我们从这里开始整合ssm。

第二步、

在pom.xml导入依赖,以下依赖是ssm常用的一些依赖,都导进去,没有坏处。

 <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
    <jackson.version>2.9.0jackson.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.1.3.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>aopalliancegroupId>
      <artifactId>aopallianceartifactId>
      <version>1.0version>
    dependency>
    
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.9.2version>
    dependency>

    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-dbcp2artifactId>
      <version>2.7.0version>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-pool2artifactId>
      <version>2.8.0version>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>5.1.3.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>5.1.3.RELEASEversion>
    dependency>

    
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.46version>
    dependency>
    <dependency>
      <groupId>com.mchangegroupId>
      <artifactId>c3p0artifactId>
      <version>0.9.5.2version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.5version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.1.3.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>5.1.3.RELEASEversion>
    dependency>

    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.10version>
    dependency>

    
    <dependency>
      <groupId>net.sf.json-libgroupId>
      <artifactId>json-libartifactId>
      <version>2.4version>
      <classifier>jdk15classifier>
    dependency>
    <dependency>
      <groupId>commons-beanutilsgroupId>
      <artifactId>commons-beanutilsartifactId>
      <version>1.7.0version>
    dependency>
    <dependency>
      <groupId>commons-collectionsgroupId>
      <artifactId>commons-collectionsartifactId>
      <version>3.1version>
    dependency>
    <dependency>
      <groupId>commons-langgroupId>
      <artifactId>commons-langartifactId>
      <version>2.5version>
    dependency>
    <dependency>
      <groupId>net.sf.ezmorphgroupId>
      <artifactId>ezmorphartifactId>
      <version>1.0.3version>
    dependency>
    <dependency>
      <groupId>commons-logginggroupId>
      <artifactId>commons-loggingartifactId>
      <version>1.2version>
    dependency>


    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.2.6version>
    dependency>

    <dependency>
      <groupId>javax.servlet.jsp.jstlgroupId>
      <artifactId>jstl-apiartifactId>
      <version>1.2-rev-1version>
    dependency>
    <dependency>
      <groupId>taglibsgroupId>
      <artifactId>standardartifactId>
      <version>1.1.2version>
    dependency>
    <dependency>
      <groupId>org.apache.taglibsgroupId>
      <artifactId>taglibs-standard-specartifactId>
      <version>1.2.5version>
    dependency>
    <dependency>
      <groupId>org.apache.taglibsgroupId>
      <artifactId>taglibs-standard-implartifactId>
      <version>1.2.5version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>${jackson.version}version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>${jackson.version}version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>${jackson.version}version>
    dependency>

    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>easyexcelartifactId>
      <version>2.1.1version>
    dependency>
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poiartifactId>
      <version>3.17version>
    dependency>

    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-ooxmlartifactId>
      <version>3.17version>
    dependency>

  dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
      resource>
    resources>
  build>

第三步、

创建数据表。
创建一个名称为category_的数据表,只有两个字段,一个id, 一个name,id自增。随便插入点数据。

DROP TABLE IF EXISTS `category_`;
CREATE TABLE `category_` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `category_` VALUES ('1', 'sadf');
INSERT INTO `category_` VALUES ('2', 'safa');
INSERT INTO `category_` VALUES ('3', 'adfasdfas');
INSERT INTO `category_` VALUES ('4', '张阿道夫');
INSERT INTO `category_` VALUES ('5', '违法收费');
INSERT INTO `category_` VALUES ('6', '发生的v');
INSERT INTO `category_` VALUES ('7', 'sdfsd');
INSERT INTO `category_` VALUES ('8', '34535');

IDEA实现SSM框架整合并在网页上显示数据_第4张图片

第四步、

编写实体类;DAO层;Service层;Controller层。

像我这样,在java文件夹目录下,创建这几个包。
IDEA实现SSM框架整合并在网页上显示数据_第5张图片

然后在包下创建对应的java文件或配置文件,最终的项目结构是这样的:
(那些打马赛克的东西你们用不到,小孩子别看那些。)
IDEA实现SSM框架整合并在网页上显示数据_第6张图片

接下来开始写实体类:

实体类名称最好见名知意,跟数据表名称要对上。因为使用了lombok插件,所以使用@Data注解,减少代码量。

Category.java

package com.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Category {
     
    private int id;
    private String name;
}

然后是DAO层,这里写的多是接口,只写方法,不实现。

CategoryDao.java

package com.dao;
import com.entity.Category;
import java.util.List;

public interface CategoryDao {
     
    public int add(Category category);
    public void delete(int id);
    public Category get(int id);
    public int update(Category category);
    public List<Category> list();
}

然后在DAO层下创建对应的Mapper.xml文件。
注意namespace要对上,还有id对应上方法名。

CategoryMapper.xml




<mapper namespace="com.dao.CategoryDao">
    <insert id="add" parameterType="Category" >
        insert into category_ ( name ) values (#{name})
    insert>

    <delete id="delete" parameterType="Category" >
        delete from category_ where id= #{id}
    delete>

    <select id="get" parameterType="_int" resultType="Category">
        select * from   category_  where id= #{id}
    select>

    <update id="update" parameterType="Category" >
        update category_ set name=#{name} where id=#{id}
    update>
    <select id="list" resultType="Category">
        select * from   category_
    select>
mapper>

然后是Service层,这里才是你要实现业务的地方。这里也是接口,在impl实现类里才是写真正实现的。
这里只实现一个:查询所有数据。

CategoryService.java

package com.service;

import com.entity.Category;

import java.util.List;

public interface CategoryService {
     
    List<Category> list();
}

然后写实现类。

CategoryServiceImpl.java

package com.service.impl;

import com.dao.CategoryDao;
import com.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.service.CategoryService;
import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService {
     
    @Autowired
    CategoryDao categoryDao;
    @Override
    public List<Category> list() {
     
        return categoryDao.list();
    }
}

然后写Controller层。

IndexController.java

package com.controller;
import com.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.service.CategoryService;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/")
public class IndexController {
     
    @Autowired
    CategoryService categoryService;

    @RequestMapping("listCategory")
    public ModelAndView listCategory(){
     
        ModelAndView mav = new ModelAndView();
        List<Category> cs= categoryService.list();
        // 放入转发参数
        mav.addObject("cs", cs);
        // 放入jsp路径
        mav.setViewName("listCategory");
        return mav;
    }
}

OK,写到这里,你已经成功一半啦!给自己鼓鼓掌!
接下来,我们一鼓作气,写好配置文件并访问数据吧!
在这里插入图片描述

第五步、
编写配置文件。

在resources目录下,创建两个配置文件。

注意把数据库,密码,改成自己的,

applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.service" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Drivervalue>
        property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/ssm?characterEncoding=UTF-8value>

        property>
        <property name="username">
            <value>rootvalue>
        property>
        <property name="password">
            <value>rootvalue>
        property>
    bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="typeAliasesPackage" value="com.entity" />
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/dao/*.xml"/>
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao"/>
    bean>

beans>

springMVC.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="com.controller">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        mvc:message-converters>
    mvc:annotation-driven>

    <mvc:default-servlet-handler />

    
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    bean>
beans>

最后就是web.xml了。

web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="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_2_5.xsd" version="2.5">

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>mvc-dispatcherservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springMVC.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcherservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

第六步、

创建listCategory.jsp文件。
在WEB-INF目录下创建jsp文件夹,将jsp文件都放在这里,因为我们在springMVC.xml中配置过的,就不过多解释了。

不知道在哪创建的可以回头看一下我的那个项目路径,根据那个来即可

listCategory.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/5/12
  Time: 12:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
         pageEncoding="UTF-8" import="java.util.*"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
    <title>Titletitle>
head>
<body>


<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>idtd>
        <td>nametd>
    tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}td>
            <td>${c.name}td>

        tr>
    c:forEach>
table>

body>
html>

这里得到数据的思路我就不多说了吧,懂得都懂。就是jsp页面中通过jstl标签来获取到Controller中返回的数据。

OK,到这里,大功告成!启动Tomcat,测试一下。

没问题吧,注意这里的访问路径,http://localhost:8885/listCategory ,不是直接访问jsp页面,是访问controller中的请求路径。
ok,就到这吧,
IDEA实现SSM框架整合并在网页上显示数据_第7张图片

===============================================================================================

这里有一个小小的改进,就是controller的改变,使用@ResponseBody注解来返回数据,然后前端通过ajax来异步请求数据。

ListController.java

package com.controller;

import com.entity.Category;
import com.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
@RequestMapping("/")
public class ListController {
     
    @Autowired
    CategoryService categoryService;

    @RequestMapping("list/allCategory")
    @ResponseBody
    public List<Category> findAll(){
     
        List<Category> list = categoryService.list();
        System.out.println(list.size());
        return  list;
    }

    @RequestMapping("/listall")
    public String listAll(){
     
        return "listall";
    }

}

在jsp文件夹下创建listall.jsp页面。

listall.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/5/14
  Time: 10:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
    <title>首页title>
head>
<body>

<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
    <tr>
        <td>idtd>
        <td>姓名td>

    tr>
    <tbody id="content">
    tbody>

table>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
script>
<script type="text/javascript">
    $(function () {
      
        $('#btn').click(function () {
      
            $.post("list/allCategory",function (data) {
      
                console.log(data);
                var html = "";
                for(var i = 0; i <data.length;i++){
      
                    html += "" +
                        ""+ data[i].id+""+
                        ""+ data[i].name+""+
                        +"";
                }
                $('#content').html(html);

            })
        })
    })

script>
body>
html>


然后访问测试listall页面:

先访问list/allCategory请求路径,看看数据是否正常回显。
在这里插入图片描述

然后访问listall, 点击一下获取数据,OK,没问题吧,老铁们。
IDEA实现SSM框架整合并在网页上显示数据_第8张图片

今天就先写到这吧,差不多德勒!

IDEA实现SSM框架整合并在网页上显示数据_第9张图片

你可能感兴趣的:(web,spring,java,mybatis)