第一个SSM程序 springmvc实现json返回前端

java程序文档

环境要求
  • IDEA 2020.2
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.8.4
数据库环境

创建一个存放用户打卡数据的数据库表

CREATE DATABASE `expressql`;

USE `expressql`;

DROP TABLE IF EXISTS `clockon`;

CREATE TABLE `clockon` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`time` DATETIME(8) NOT NULL,
`oC` FLOAT(3) NOT NULL,
`GPS` VARCHAR(255) NOT NULL,
`riskName` VARCHAR(255) NOT NULL,
`riskNumber` VARCHAR(11) NOT NULL,   
 PRIMARY KEY ( `id` )
) ENGINE=INNODB DEFAULT CHARSET=utf8
基本环境搭建

1、新建一Maven项目!clockOn , 添加web的支持

2、导入相关的pom依赖!

<dependencies>
        <dependency>
            <!--   导入json的包-->
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <!-- 导入fastjson包-->
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

        <dependency>
            <!-- 导入lombok包-->
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <!--  mysql mybatis-->
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--一导入了SpringMVC 的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

3、Maven资源过滤设置

<build>
   <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>

4、建立基本结构和配置框架

  • com.haoyuan.clockOn.pojo

  • com…haoyuan.clockOn.dao

  • com…haoyuan.clockOn.service

  • com.haoyuan.clockOn.controller

  • mybatis-config.xml

    <?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>
    
    </configuration
    
  • 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"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    </beans>
    
Mybatis层编写

1、数据库配置文件 database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://101.43.219.238:3306/expresssql?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=expresssql
jdbc.password=sgc1459

2、IDEA关联数据库

3、编写MyBatis的核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--  配置数据源,交给spring-->
    <typeAliases>
        <package name="com.haoYuan.clockOn.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.haoYuan.clockOn.dao.clockOnMapper"/>
    </mappers>
</configuration>

4、编写数据库对应的实体类 com.haoyuan.clockOn.pojo.User

​ 使用lombok插件!

package com.haoYuan.clockOn.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User{
    private int id;//用户ID
    private String  time;//打卡时间
    private double oC;//体温
    private String GPS;//打卡位置
    private String riskName;//紧急联系人
    private String riskNumber;//紧急联系人电话
}

5、编写状态类 com.haoyuan.clockOn.pojo.status

package com.haoYuan.clockOn.pojo;

public class status {
    private String info;
    private int code;//返回状态
    public status(int code) {
        this.code = code;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public status(String info) {
        this.info = info;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}

6、编写Dao层的 Mapper接口

import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface clockOnMapper {
    //增加一个用户
    int  addUser(User user);
    //查询一个用户
    User queryUserById(@Param("id") int id);

}

7、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 绑定这个接口-->
<mapper namespace="com.haoYuan.clockOn.dao.clockOnMapper">
    <insert id="addUser" parameterType="User">
        # 添加打卡信息
        insert into expresssql.clockon (id, time, oC, GPS, riskName, riskNumber)
        values (#{id}, #{time}, #{oC}, #{GPS}, #{riskName}, #{riskNumber})

        ON DUPLICATE KEY UPDATE id=#{id},
                                time=#{time},
                                oC=#{oC},
                                GPS=#{GPS},
                                riskName=#{riskName},
                                riskNumber=#{riskNumber}
    </insert>

    <select id="queryUserById" parameterType="User" resultType="User">
        #  查询一个用户
        select *
        from expresssql.clockon
        where id = #{id}
    </select>
</mapper>

8、编写Service层的接口和实现类

​ 接口:

package com.haoYuan.clockOn.service;

import com.haoYuan.clockOn.pojo.User;
import java.util.List;

public interface ClockOnService {
    //增加一个用户
    int addUser(User user);
    
    //查询一个用户
    User queryUserById(int id);


}

实现类:

package com.haoYuan.clockOn.service;

import com.haoYuan.clockOn.dao.clockOnMapper;
import com.haoYuan.clockOn.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClockOnServiceImpl implements ClockOnService {
    @Autowired
    //service调dao层:组合dao层
    private clockOnMapper clockOnMapper;

    public void setClockOnMapper(com.haoYuan.clockOn.dao.clockOnMapper clockOnMapper) {
        this.clockOnMapper = clockOnMapper;
    }
    @Override
    //实现增加用户信息接口
    public int addUser(User user) {
        return clockOnMapper.addUser(user);
    }

    @Override
    //实现根据用户ID查询信息
    public User queryUserById(int id) {
        return clockOnMapper.queryUserById(id);
    }

}
Spring层

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池

2、编写Spring整合Mybatis的相关的配置文件;spring-dao.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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置整合mybatis -->
    <!-- 1.关联数据库文件 -->
    <!--   导入配置文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.数据库连接池
        dbcp:半自动化操作,不能自动连接
        c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中!这里使用的他)
        druid: hikari
     -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

<!--    4.配置dao接口自动扫描包,动态实现dao接口可以注入spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 扫描dao包-->
    <property name="basePackage" value="com.haoYuan.clockOn.dao"/>
    </bean>
</beans>

3、Spring整合service层

<?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">

    <!-- 1.扫描service下的包-->
    <context:component-scan base-package="com.haoYuan.clockOn.service"/>
    <!--2.将所有的业务类,注入到spring,可以通过配置和注解实现-->
    <bean id="ClockOnServiceImpl" class="com.haoYuan.clockOn.service.ClockOnServiceImpl">
        <property name="clockOnMapper" ref="clockOnMapper"/>
    </bean>
    <!--3.声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>
SpringMVC层

1、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">

    <!--1.DispatcherServlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContest.xml</param-value>
        </init-param>
        <!-- 启动顺序,数字越小,启动越早 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--所有请求都会被springmvc拦截 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 乱码过滤-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Session-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

2、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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--1.注解驱动-->
    <mvc:annotation-driven/>
    <!-- 2.静态资源过滤-->
    <mvc:default-servlet-handler/>

    <!--3. 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
    <context:component-scan base-package="com.haoYuan.clockOn.controller"/>

    <!--4.json乱码问题配置-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--5.视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3、Spring配置整合文件,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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:springmvc-servlet.xml"/>
</beans>
Controller 和 视图层编写

1、ClockOnController类编写 :

  • 方法一:添加一个用户信息并以json方式返回客户端

@RestController//控制器类器返回json数据
public class ClockOnController extends HttpServlet {
    //controller 调service 层
    @Autowired(required = false)//对类自动装配 spring的依赖注入
    @Qualifier("ClockOnServiceImpl")//指明注入的bean
    private ClockOnService clockOnService = new ClockOnServiceImpl();

@RequestMapping("/addClockOn")
public String toAddPaper(HttpServletRequest req,HttpServletResponse response,  Model model) throws JsonProcessingException {
        int id = Integer.parseInt(req.getParameter("id"));//用户输入ID
        String time = req.getParameter("time");//用户输入时间
        Double oC = Double.valueOf(req.getParameter("oC"));//用户输入温度
        String GPS = req.getParameter("GPS");//用户输入ID
        String riskName = req.getParameter("riskName");//用户输入紧急联系人
        String riskNumber = req.getParameter("riskNumber");//用户输入紧急联系人电话
        status n2 = new status(200);//设置成功状态码
        status n3 = new status("添加成功");
        ObjectMapper mapper = null;
        int list = 0;//初始化list
        mapper = new ObjectMapper();//解析json对象
        list = clockOnService.addUser(new User(id, time, oC, GPS, riskName, riskNumber));//添加打卡信息
        model.addAttribute("listmapper.writeValueAsString", list);//list打卡信息传向前端

        String add = null;
        Object add1 = mapper.writeValueAsString(n2);
        add = mapper.writeValueAsString(list);
        //查看数据是否返回成功
        try {
            if (!Objects.equals(add, "1")) {
                add = mapper.writeValueAsString(n2);
            }else{
                add = mapper.writeValueAsString(n3);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return add;
    }

方法二:根据用户id查询一个用户信息并以json方式返回客户端

//    查询一个用户
@RequestMapping("/queryClockOn")
public String queryUserPaper1 (HttpServletRequest req, Model model) throws JsonProcessingException {
    System.out.println(req.getParameter("id"));
    ObjectMapper mapper = new ObjectMapper();
    int id = Integer.parseInt(req.getParameter("id"));
    status status = new status(200);
    status n1 = new status(":用户不存在");
    List list = Collections.singletonList(clockOnService.queryUserById(id));

    model.addAttribute("list", list);
    String query ;
    if (list.size() >=0) {
        query = mapper.writeValueAsString(list);
    } else {
        query = mapper.writeValueAsString(n1);
    }
    return query;
}

最后配置Tomcat,进行运行!

项目结构

|-- clockOn	打卡系统根目录
	|-- .idea 存放项目的配置信息
	|-- out  渲染输出文件
	|-- src  默认的源文件路径
		|-- main
			|--java 存放项目的java类源文件
				|-- com.aoyuan.clockOn 创建存放java文件的包
            		|-- controller
            			|-- clockOnController
            		|-- dao
            			|-- clockOnMapper
            			|-- clockOnMapper.xml
            		|-- pojo
            			|-- status
            			|-- User
            		|-- service
            			|-- ClockOnService
            			|-- ClockOnServicelmpl
            		|-- utils
            			|-- JsonUtils
			|-- resources  存放项目的资源文件
				|-- applicationContest.xml
				|-- database.properties
				|-- mybatis-config.xml
				|-- spring-dao.xml
				|-- spring-service.xml
				|-- springmvc-servlet.xml
	|-- test  存放项目的用于测试的java类源文件
	|-- target  存放项目构建后的文件和目录
	|-- web  web应用的目录
		|-- WEB-INF
		|-- web.xml
		|-- index.jsp
	|-- pom.xml  配置文件及导入的包
	|-- External Libraries  存放导入的相关jar包
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值