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";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM