Spring框架学习第八天

提要

今天学习REST规则
简单扼要的说,就是这样


我们需要遵守的前后端分离思想规则如下

例如

/**
 * Class Describe:
 * 查询密码为同一内容的所有用户
 * GET http://localhost/user/xxx/users
 * <p>
 * 添加一个密码为xxx,账号名为xxx的用户
 * POST http://localhost/user/xxx/users/xx
 * <p>
 * 查询密码为xxx的最新用户
 * GET http://localhost/user/xxx/users/new
 * <p>
 * 删除密码为xxx的最老用户
 * DELETE http://localhost/user/xxx/users/old
 * <p>
 * 更新密码为xxx的所有用户xx
 * PUT http://localhost/user/xxx/users/xx
 *
 * @author biuaxia
 * @date 2018/11/21
 * @time 15:59
 */

我们需要编写后端接口,而不做view视图层了,那么开始代码

步骤

  1. 配置DispatcherServlet
  2. 配置SpringMvc的HandlerMapping
  3. 配置对应的Controller控制器
  4. 控制器调用dao得到数据并返回

操作开始

配置DispatcherServlet

<?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">
    <servlet>
        <servlet-name>SpringMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:Spring*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置SpringMvc的HandlerMapping

SpringMvc.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:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

    <!--HandlerMapping-->
    <mvc:annotation-driven/>

    <!--开启mvc的组件扫描-->
    <context:component-scan base-package="mvc.controller"/>
</beans>

SpringDao.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:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

    <!-- 扫描所有Dao -->
    <context:component-scan base-package="mvc.model.dao"/>

    <!--引入db.properties配置文件-->
    <util:properties id="db" location="classpath:db.properties"/>
    <!--配置数据源dataSource-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="#{db.driverClassName}"/>
        <property name="url" value="#{db.url}"/>
        <property name="username" value="#{db.username}"/>
        <property name="password" value="#{db.password}"/>
    </bean>
    <!--配置JDBCTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource"></constructor-arg>
    </bean>

    <!--开启声明式事务 transaction-manager就是事务管理器的意思,proxy-target-class如果是false代表jdk的代理机制(必须要求你的这个类实现接口),如果是true代表使用cglib的动态代理-->
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>


    <!--创建事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

配置对应的Controller控制器

UserController.java

package mvc.controller;

import mvc.model.bean.User;
import mvc.model.dao.UserDao;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Class Describe:
 * 查询密码为同一内容的所有用户
 * GET http://localhost/user/xxx/users
 * <p>
 * 添加一个密码为xxx,账号名为xxx的用户
 * POST http://localhost/user/xxx/users/xx
 * <p>
 * 查询密码为xxx的最新用户
 * GET http://localhost/user/xxx/users/new
 * <p>
 * 删除密码为xxx的最老用户
 * DELETE http://localhost/user/xxx/users/old
 * <p>
 * 更新密码为xxx的所有用户xx
 * PUT http://localhost/user/xxx/users/xx
 *
 * @author biuaxia
 * @date 2018/11/21
 * @time 15:59
 */
@Controller
public class UserController {

    @Resource
    private UserDao dao;

    /**
     * 查询密码为同一内容的所有用户
     * GET http://localhost/user/xxx/users
     *
     * @return 数据库所有密码为xxx的用户集合
     */
    @RequestMapping(value = "user/{password}/users", method = RequestMethod.GET)
    @ResponseBody
    public Map findView(@PathVariable("password") String password) {
        Map<String, Object> results = new HashMap<>(5);
        List<User> lists = dao.findAllUserByPassword(password);
        if (!lists.isEmpty()) {
            results.put("status", 200);
            results.put("msg", "success");
            results.put("datas", lists);
        } else {
            results.put("status", 400);
            results.put("msg", "failed");
        }
        return results;
    }

    /**
     * 添加一个密码为xxx,账号名为xxx的用户
     * POST http://localhost/user/xxx/users/xx
     *
     * @return 数据库添加成功后的数据内容
     */
    @RequestMapping(value = "user/{password}/users/{username}", method = RequestMethod.GET)
    @ResponseBody
    public Map addView(@PathVariable("username") String username, @PathVariable("password") String password) {
        Map<String, Object> results = new HashMap<>(3);
        User user = dao.addUserByPasswordAndUsername(password, username);
        if (user != null) {
            results.put("status", 200);
            results.put("msg", "success");
            results.put("data", user);
        } else {
            results.put("status", 400);
            results.put("msg", "failed");
        }
        return results;
    }
}

UserDao.java接口

package mvc.model.dao;

import mvc.model.bean.User;

import java.util.List;

/**
 * @author biuaxia
 */
public interface UserDao {

    /**
     * 根据密码查询所有相同密码用户
     *
     * @param password
     * @return
     */
    List<User> findAllUserByPassword(String password);

    /**
     * 根据id查询所有的用户
     *
     * @param username,password
     * @return
     */
    User findUserByUsername(String username);

    /**
     * 根据用户名密码新增用户
     *
     * @param password
     * @param username
     * @return
     */
    User addUserByPasswordAndUsername(String username, String password);
}

UserDaoImpl.javadao的实现类

package mvc.model.dao.impl;

import mvc.model.bean.User;
import mvc.model.dao.UserDao;
import mvc.model.rowmapper.UserRowMapper;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Class Describe:
 *
 * @author biuaxia
 * @date 2018/11/21
 * @time 16:48
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> findAllUserByPassword(String password) {
        String sql = "SELECT * FROM XX_USER WHERE UPASS = ?";
        List<User> query = jdbcTemplate.query(sql, new UserRowMapper(), password);
        return query;
    }

    @Override
    public User findUserByUsername(String username) {
        User toClient = null;
        String sql = "SELECT * FROM XX_USER WHERE UNAME = ? ";
        List<User> userList;
        try {
            userList = jdbcTemplate.query(sql, new UserRowMapper(), username);
        } catch (DataAccessException e) {
            return null;
        }
        for (User user : userList) {
            toClient = new User();
            toClient.setUserId(user.getUserId());
            toClient.setUserName(user.getUserName());
            toClient.setUserPass(user.getUserPass());
            toClient.setUseremail(user.getUseremail());
        }
        return toClient;
    }

    @Override
    public User addUserByPasswordAndUsername(String username, String password) {
        User checkUser = findUserByUsername(username);
        User dbUser = null;
        if (checkUser != null) {
            //表示用户已存在,停止用户操作
            return null;
        } else {
            String sql = "INSERT INTO XX_USER VALUES \t(\n" +
                    "\tXX_USER_ID_SEQ.nextval,\n" +
                    "\t?,\n" +
                    "\t?,\n" +
                    "?||XX_USER_ID_SEQ.currval || '@qq.com')\n";
            int result;
            result = jdbcTemplate.update(sql, username, password, username);
            //执行查询数据操作
            if (result > 0) {
                dbUser = findUserByUsername(username);
            }
        }
        return dbUser;
    }
}

TestDao.java测试dao接口,这里引入了Spring的测试注解和test包

package mvc.model.test;

import mvc.model.dao.UserDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Class Describe:
 *
 * @author biuaxia
 * @date 2018/11/21
 * @time 18:35
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:SpringDao.xml"})
public class TestDao {
    @Resource
    private UserDao dao;

    @Test
    public void test1() {
        System.out.println(dao.addUserByPasswordAndUsername("admin23233", "1231232131"));
    }

}

控制器调用dao得到数据并返回

这里其实就是前台调用了,我为了方便直接采取了get而不是规范中的post,当然明天会更深入的遵守REST服务规则

效果截图

  • 调用生成账户API
  • 再次调用的效果
  • 调用查询密码为同一内容的所有用户

数据库数据

这样能让大家照着文章走得通,俺是Oracle数据库哦!

/*
 Navicat Premium Data Transfer

 Source Server         : oracle
 Source Server Type    : Oracle
 Source Server Version : 110200
 Source Host           : localhost:1521
 Source Schema         : SYSTEM

 Target Server Type    : Oracle
 Target Server Version : 110200
 File Encoding         : 65001

 Date: 21/11/2018 21:03:10
*/


-- ----------------------------
-- Table structure for XX_USER
-- ----------------------------
DROP TABLE "SYSTEM"."XX_USER";
CREATE TABLE "SYSTEM"."XX_USER" (
  "ID" NUMBER NOT NULL ,
  "UNAME" VARCHAR2(30 BYTE) ,
  "UPASS" VARCHAR2(30 BYTE) ,
  "UEMAIL" VARCHAR2(30 BYTE) 
)
TABLESPACE "SYSTEM"
LOGGING
NOCOMPRESS
PCTFREE 10
INITRANS 1
STORAGE (
  INITIAL 65536 
  NEXT 1048576 
  MINEXTENTS 1
  MAXEXTENTS 2147483645
  FREELISTS 1
  FREELIST GROUPS 1
  BUFFER_POOL DEFAULT
)
PARALLEL 1
NOCACHE
DISABLE ROW MOVEMENT
;

-- ----------------------------
-- Records of XX_USER
-- ----------------------------
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1113', 'username', '12345', 'username1113@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1116', 'username1', '1231232131', 'username11116@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1118', 'usernamsde1', '1231232131', 'usernamsde11118@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1119', 'usernsdadamsde1', '1231232131', 'usernsdadamsde11119@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1124', 'usernasme', '12345', 'usernasme1124@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1125', 'xcxczx', '12345', 'xcxczx1125@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1130', 'xcxczx1', '12345xc', 'xcxczx11130@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1134', 'xcxczx12', '12345xc', 'xcxczx121134@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1135', 'admin', '1231232131', 'admin1135@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1136', 'adm22in', '1231232131', 'adm22in1136@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1137', 'admin233', '1231232131', 'admin2331137@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1138', 'admin23233', '1231232131', 'admin232331138@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1141', '2323', '213123', '23231141@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1149', '23asdasd23', '156', '23asdasd231149@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1150', 'biuaxia', 'qweqweqewqeda', 'biuaxia1150@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1151', 'qweqweqewqeda', 'qweqweqewqeda', 'qweqweqewqeda1151@qq.com');
INSERT INTO "SYSTEM"."XX_USER" VALUES ('1152', '1231232131', 'qweqweqewqeda', '12312321311152@qq.com');

-- ----------------------------
-- Primary Key structure for table XX_USER
-- ----------------------------
ALTER TABLE "SYSTEM"."XX_USER" ADD CONSTRAINT "TEST100_ID_PK" PRIMARY KEY ("ID");

-- ----------------------------
-- Indexes structure for table XX_USER
-- ----------------------------
CREATE UNIQUE INDEX "SYSTEM"."名不为空"
  ON "SYSTEM"."XX_USER" ("UNAME" ASC)
  LOGGING
  TABLESPACE "SYSTEM"
  VISIBLE
PCTFREE 10
INITRANS 2
STORAGE (
  INITIAL 65536 
  NEXT 1048576 
  MINEXTENTS 1
  MAXEXTENTS 2147483645
  FREELISTS 1
  FREELIST GROUPS 1
  BUFFER_POOL DEFAULT
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值