SSM前后端分离/不分离对比Demo

之前某些原因,整理了一个小的Demo,用于演示。个人认为在SSM前后端不分离的基础上在前端处理上比较麻烦一点之后就是注解的使用。总结一些对比,仅是自己掌握的,不够严谨,不足之处请大佬批评指正.

路由控制:前后端分离的情况后端在任何都会返回一个json数据,不涉及路由处理,即页面跳转全是由前端自己完成.不分离的情况,路由跳转一般由后端完成,而且携带数据,通过重定向或请求转发实现,依赖Servlet中的内置对象.

返回数据:前后端分离的情况后端返回的整体划分上只有执行逻辑响应的消息实体类和对应的需要展示的数据分页类对应的JSON.不分离后端返回的是经过视图解析器处理前的字符串.

分离:

package com.liruilong.model;

/**
 * @Description :返回消息的实体类
 * @Author: Liruilong
 * @Date: 2019/12/19 17:34
 */
public class RespBean {
    private Integer status;
    private String msg;
    private Object obj;

    public static RespBean ok(String msg){
        return new RespBean(200, msg, null);
    }
    public static RespBean ok(String msg, Object obj){
        return new RespBean(200, msg, obj);
    }
    public static RespBean error(String msg){
        return new RespBean(500, msg, null);
    }
    public static RespBean error(String msg, Object obj){
        return new RespBean(200, msg, obj);
    }
    private RespBean() {
    }
    private RespBean(Integer status, String msg, Object obj) {
        this.status = status;
        this.msg = msg;
        this.obj = obj;
    }

    public static RespBean build() {
        return new RespBean();
    }

  //getter.setter方法省略
package com.liruilong.model;

import java.util.List;

/**
 * @Description : 分页
 * @Author: Liruilong
 * @Date: 2019/12/31 11:20
 */
public class RespPageBean {
    /*总记录树*/
    private Long total;
    /*分页数据*/
    private List<?> data;
    public RespPageBean() {
    }
    public RespPageBean(Long total, List<?> data) {
        this.total = total;
        this.data = data;
    }

//getter.setter方法省略 }
  @GetMapping("/")
    public RespPageBean getEmploteeByPge(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size,Employee employee, Date[] beginDateScope) {
        return employeeService.getEmploteeByPge(page, size, employee, beginDateScope);

    }

    @DeleteMapping("/{id}")
    public RespBean deleteEmpByEid(@PathVariable Integer id) {
        if (employeeService.deleteEmpByEid(id) == 1) {
            return RespBean.ok("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

不分离:

  //初始化添加商品
    @RequestMapping("toAddGoods")
    public String toAddGoods(Model model) throws Exception {
        adminGoodsServiceimpl.toAddGoods(model);
        adminTypeServiceimpl.listGoodsType(model);
        return "admin/addGoods";
    }
    //处理添加商品
    @RequestMapping("addGoods")
    public String addGoods(@ModelAttribute("goods") Goods goods, Model model, HttpServletRequest request) throws Exception {
        adminGoodsServiceimpl.addGoods(goods, model, request);
        if (request.getParameter("updateAct").equals("update")) {
            return "forward:/adminGoods/selectGoods.do?act=updateSelect";
        } else {
            return "forward:/adminGoods/selectGoods.do?act=main";
        }

请求方式:前后端分离的情况我只知道以Rest风格的方式处理,当执行增删改查对应http请求方法POST,DELEE,PUT,GET,一般以异步请求为主,不分离情况一般同步异步结合。请求上以GET和POST为主。

分离:

    //传递json的post请求
export const postRequest = (url, params) => {
        return axios({
            method: ‘POST‘,
            url: `${base}${url}`,
            data: params,
        })
    }
    // put请求封装
export const putRequest = (url, params) => {
        return axios({
            method: ‘put‘,
            url: `${base}${url}`,
            data: params,
        })
    }
    // get请求封装
export const getRequest = (url, params) => {
        return axios({
            method: ‘get‘,
            url: `${base}${url}`,
            data: params,
        })
    }
    // delete请求封装
export const deleteRequest = (url, params) => {
    return axios({
        method: ‘delete‘,
        url: `${base}${url}`,
        data: params,
    })

不分离:

<script type="text/javascript">
        function submitorder(total) {
            if (window.confirm("是否真的提交订单,提交后不可再修改订单信息!")) {
                window.location.href = "${pageContext.request.contextPath}/order/orderSubmit.do?amount=" + total;
                return true;
            }
            return false;
        }
    </script>
  <form action="order/pay.do" method="post" name="payForm">
                <input type="hidden" name="ordersn" value="${ordersn}"/>
                <input type="image" src="images/before/Chinapay_logo.jpg" onclick="gogo()"/>
            </form>
$.ajax({
                                    type: "POST",// 请求方式
                                    url: "http://localhost:8083/addDemo_war_exploded/system/log/",// 发送请求地址
                                    dataType: "json",
                                    async: true,
                                    contentType: "application/json;charsetset=UTF-8",//必须
                                    data: JSON.stringify({
                                        "operate": operate.val(),
                                        "hrname": hrname.val()
                                    }),
                                    success: function (mainQueryList) {
                                        init();
                                    }
                                }
                            )

注解使用:前后端分离,接收的数据是Json时需要@RequestBody作用在方法参数上.用于将POST请求数据转化为实体类.返回数据时使用@ResponseBody,作用在方法上,当然对于全局的也可以使用@RespController注解.前后端不分离一般使用@RequestMapping,请求方式不用管。

分离:

package com.liruilong.hros.controller.emp;

import com.liruilong.hros.model.*;
import com.liruilong.hros.service.*;
import com.liruilong.hros.service.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Description :
 * @Author: Liruilong
 * @Date: 2019/12/31 11:19
 */

@RestController
@RequestMapping("/employee/basic")
public class EmpBasicController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    NationService nationService;
    @Autowired
    PoliticsstatusService politicsstatusService;
    @Autowired
    JobLevelService jobLevelService;
    @Autowired
    PositionService positionService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    EmployeeecService employeeecService;

    @GetMapping("/")
    public RespPageBean getEmploteeByPge(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size,Employee employee, Date[] beginDateScope) {
        return employeeService.getEmploteeByPge(page, size, employee, beginDateScope);

    }

    @DeleteMapping("/{id}")
    public RespBean deleteEmpByEid(@PathVariable Integer id) {
        if (employeeService.deleteEmpByEid(id) == 1) {
            return RespBean.ok("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

    @DeleteMapping("/many/")
    public RespBean deleteEmpByEids(Integer[] ids) {
        if (employeeService.deleteEmpByEids(ids) == ids.length) {
            return RespBean.ok("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee) {
        if (employeeService.addEmp(employee) == 1) {
            return RespBean.ok("添加成功!");
        }
        return RespBean.error("添加失败!");
    }

    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateEmp(employee) == 1) {
            return RespBean.ok("更新成功!");
        }
        return RespBean.error("更新失败!");
    }

    @GetMapping("/nations")
    public List<Nation> getAllNations() {
        return nationService.getAllNations();
    }

    @GetMapping("/politicsstatus")
    public List<Politicsstatus> getAllPoliticsstatus() {
        return politicsstatusService.getAllPoliticsstatus();
    }

    @GetMapping("/joblevels")
    public List<JobLevel> getAllJobLevels() {
        return jobLevelService.getAllJobLevels();
    }

    @GetMapping("/positions")
    public List<Position> getAllPositions() {
        return positionService.getAllPositions();
    }

    @GetMapping("/deps")
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartments();
    }

    @GetMapping("/maxWorkID")
    public RespBean maxWorkID() {
        RespBean respBean = RespBean.build().setStatus(200)
                .setObj(String.format("%08d", employeeService.maxWorkID() + 1));
        return respBean;
    }

/**
 * @Author Liruilong
 * @Description  文件下载
 * @Date 19:04 2020/1/1
 * @Param []
 * @return org.springframework.http.ResponseEntity<byte[]>
 **/

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportData() {
        List<Employee> list = (List<Employee>) employeeService.getEmploteeByPge(null, null, null,null).getData();
        return POIUtils.employee2Excel(list);
    }

    /**
     * @Author Liruilong
     * @Description 文件导出
     * @Date 19:48 2020/1/1
     * @Param [file]
     * @return com.liruilong.hros.model.RespBean
     **/

    @PostMapping("/import")
    public RespBean importData(MultipartFile file) throws IOException {
        List<Employee> list = POIUtils.excel2Employee(file, nationService.getAllNations(), politicsstatusService.getAllPoliticsstatus()
                , departmentService.getAllDepartmentsWithOutChildren(), positionService.getAllPositions(), jobLevelService.getAllJobLevels());
        if (employeeService.addEmps(list) == list.size()) {
            return RespBean.ok("上传成功");
        }
        return RespBean.error("上传失败");
    }
}

不分离:

package com.qst.controller.admin;

import com.qst.pojo.Auser;
import com.qst.service.admin.AdminServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminServiceimpl adminService;
    /*
    初始化登录页面
     */
    @RequestMapping("login")
    public String login(@ModelAttribute("auser") Auser auser) {
        return "admin/login";
    }
    /*
    处理登录页面
     */
    @RequestMapping("tologin")
    public String tologin(@ModelAttribute Auser auser, Model model, HttpSession session) throws Exception {

        return adminService.login(auser, model, session) ? "admin/main" : "admin/login";

    }
    /*
    退出系统
     */
    @RequestMapping("exit")
    public String exit(@ModelAttribute Auser auser, HttpSession session) {
        session.invalidate();
        return "admin/login";
    }
}

原文地址:https://www.cnblogs.com/liruilong/p/12244925.html

时间: 2024-07-29 18:59:18

SSM前后端分离/不分离对比Demo的相关文章

前后端要不要分离以及如何做

前后端分离要不要搞?这个我觉得按照康威定律办就好了, 前后端如果是两拨人, 不要多想一定要分离, 如果是一拨人, 确定前后端是否要分离需要算账 , 收益是它会强制我们按照服务的理念指导系统设计, 将来的微服务也就顺理成章, 代价就是架构复杂了, 开发和运维都有些成本. 下面假定我们确定前后端要分离, 就要考虑实现的方案/技术选型/常见问题处理. =============================前后端分离的几种实现思路=============================思路1: 前

前后端分离及React的一些研究

前言 在对英才网企业线前端不断的完善过程中,我们尝试进行了前后端分离,引入Node环境.以及在使用React的过程中,自行开发DOM渲染框架,解决React兼容低版本IE的问题,在这个过程中,我们有了一些经验和体会,希望本文对您有所帮助. 为什么前后端分离 原有架构下,后端系统基于Java语言实现,通过Velocity模板实现服务器端渲染,前端同学维护静态资源,在维护页面状态时,还需要模板和脚本互传参数,模板中还会有很多UI逻辑,等等,前后端耦合很深,这种模式下开发效率非常低,联调成本非常高,同

前后端分离实践(一)

前言 最近这一段时间由于Nodejs的逐渐成熟和日趋稳定,越来越多的公司中的前端团队开始尝试使用Nodejs来练一下手,尝一尝鲜. 一般的做法都是将原本属于后端的一部分相对于业务不是很重要的功能迁移到Nodejs上面来,也有一些公司将NodeJS作为前后端分离的一个解决方案去施行.而像淘宝网这类的大型网站也很早的完成了前后端的分离,给我们这样的后来者提供了宝贵的经验. 同样,我们的大网盘团队也早在去年早早就开始了紧锣密布的准备工作,这目前工作也做的差不多了,现在我就来总结一下在过程中遇到的坑点以

浅谈前后端分离与不分离

前后端的分离与不分离 随着不同终端的兴起,对开发人员的要求越来越高,纯浏览器端的响应式已经不能满足用户体验的高要求,我们往往需要针对不同的终端开发定制的版本,为了提升开发效率,前后端分离的需求越来越被重视,前端主要负责页面的展现和交互逻辑,后端主要负责业务和数据接口,同一份数据接口,我们可以定制开发多个版本. 前后端不分离: 在之前的开发方法,php代码写在HTML中,不存在纯粹的PHP文件和HTML文件,这就是前后端的不分离,也就是php和HTML你中有我我中有你,而在前后端不分离的应用模式中

架构设计:前后端分离之Web前端架构设计

在前面的文章里我谈到了前后端分离的一些看法,这个看法是从宏观的角度来思考的,没有具体的落地实现,今天我将延续上篇文章的主题,从纯前端的架构设计角度谈谈前后端分离的一种具体实现方案,该方案和我原来设想有了很大的变化,但是核心思想没变,就是控制层是属于Web前端的. 在以前文章里我说道前后端分离的核心在于把mvc的控制层归为前端的一部分,原方案的构想在实际的生产开发里很难做到,我觉得核心还是控制层和视图层的技术异构性,这样后果使得系统改造牵涉面太大,导致在项目团队里,沟通.协调以及管理成本相对较高,

为什么要进行前后端分离?

一.认识前后端分离 可能很多人会有误解,认为web应用的开发期进行了前后端开发工作的分工就是前后端分离.但其实前后端分离并不只是开发模式,而是web应用的一种架构模式.在开发阶段,前后端工程师约定好数据交互接口,实现并行开发和测试:在运行阶段前后端分离模式需要对web应用进行分离部署,前后端之前使用HTTP或者其他协议进行交互请求. 二.为什么要进行前后端分离 在以前传统的网站开发中,前端一般扮演的只是切图的工作,只是简单地将UI设计师提供的原型图实现成静态的HTML页面,而具体的页面交互逻辑,

你是如何看待前后端分离的?

首先看看前后端分离是什么? "前端"通常指的是,相对来说更接近用户的一端,例如:APP,网页.桌面程序等,在现实开发中大部分情况可以理解为"客户端": "后端"相对来说就更泛化了,可以理解为是为前端提供服务的一端. "分离"顾名思义就是将"前端"和"后端进行分开",但是这里的分开主要从下面几个纬度进行分离 1:架构分离,前端不需要依赖后端架构同时后端也不需要知道前端使用何种架构 2:人员

nginx反向代理前后端分离项目(后端多台)

目前软件架构都比较流行前后端分离,前后端的分离也实现了前后端架构的分离,带来的好处 —— 整个项目的开发权重往前移,实现真正的前后端解耦,动态资源和静态资源分离,提高了性能和扩展性. 通常SpringBoot与vue 进行前后端分离,主要有两种方式: 1.打包(npm run build命令)vue项目出来的dist文件夹拷贝到springboot项目的static文件目录,部署到tomcat即可. 2.利用nginx的反向代理. 本文主要讲解第二种 首先打包前端项目到指定目录:E:\fjgh\

Web系统开发构架再思考-前后端的完全分离

前言 前后端完全分离其实一直是Web开发人员的梦想,也一直是我的梦想,遥想当年,无论是直接在代码里面输出HTML,还是在HTML里面嵌入各种代码,都不能让人感到满意.期间的痛苦和纠结,我想所有Web开发人员都深有感触. 由于最近几年一直在MS平台,从Web Form到MVC,MS平台虽然易用好学,但整合度太高而灵活性不足,一直没有找到很好的前后端分离的思路. (Java平台的兄弟如果已经有非常成熟的平台和思路,最好能简单留个言给个帖子地址或者技术名称,不胜感激). ASP.NET的MVC模式的确