【Springboot】个人的一些知识总结

【Springboot】个人的一些知识总结

(1)Controller类对form进行预处理
方法上使用注解@ModelAttribute(name = Form.KEY),然后对form中的属性进行提前赋值,最后返回return form;

(2)Controller类的初期表示
把上面预处理过的form、拿来接着进行操作

public ModelAndView index(@ModelAttribute(Form.KEY) MT0003V01Form form) {
	ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(Form.KEY, form);
    modelAndView.setViewName(MT301_VIEW);
	return modelAndView;
}

(3)检索操作,并对表单进行校验

	@RequestMapping(value = "/search", params = "page", method = RequestMethod.GET)
    public ModelAndView search(@Validated @ModelAttribute(Form.KEY) MT0003V01Form form, BindingResult result,
        ModelAndView modelAndView) throws Exception {

		//把处理完的form加到modelAndView里
        modelAndView.addObject(Form.KEY, form);
		//给modelAndView
        modelAndView.setViewName(MT301_VIEW);

        checkCreateDate(form, result);
        if (result.hasErrors()) {
            return modelAndView;
        }

        int searchCount = service.count(form);

        if (searchCount < 1) {
            result.reject("ECM00045");
            return modelAndView;
        }

        PaginationForm pageForm = paginationService.create("MT0003V01", form.getPage(), searchCount);
        form.setPageInfo(pageForm);

        form.setSearchResult(service.search(form));
        return modelAndView;
    }

(4)前台往后台传参

  • th:object="${form}":从modelAndView里取出后台的放进去的数据form
  • c21:action="@{/master/shop/search}":表示表单submit提交时的请求路径
  • method=“get”:提交的方法是get还是post,get方法会吧请求数据显示在路径中,不安全;post不会显示,更加安全
<form class="needs-validation" th:object="${form}" c21:action="@{/master/shop/search}" method="get" id="searchForm" novalidate>

(5)thymeleaf的判断语句
当if后面的值为true时,div中的内容才会显示

<div th:if="${#authentication.principal.headQuarter}">

(6)input组件传参

  • th:field="*{companyCd}":是th:name和th:value的合体,name的意思是表单提交时,输入框里的内容提交给companyCd这个属性字段
  • th:value="*{companyCd}"
<input type="text" class="form-control companyCd" th:field="*{companyCd}"
    th:value="*{companyCd}" th:errorclass="is-invalid" /> <span
    class="invalid-feedback"
    th:if="${#fields.hasErrors('companyCd')}"
    th:errors="*{companyCd}" id="companyCd"></span>

(7)多选框组件显示和传参

  • th:each=“shopTypeSelect,type:${form.shopTypeSelect}”:遍历form中的HashMap(shopTypeSelect),type是下标用来放置index等,shopTypeSelect是内容用来放置key、value等值
  • type=“checkbox”:多选框的类型的checkbox
  • th:name=“shopType”:当选框被选中时,会有返回值,这个值就返回给name指定的属性
  • th:value="${shopTypeSelect.key}":value就表示选框选中时要返回值的内容,其中具体值为shopTypeSelect的key值
  • th:text="${shopTypeSelect.value}":text表示要显示在画面上的值
<div class="form-check-inline"
    th:each="shopTypeSelect,type:${form.shopTypeSelect}"
    th:object="${shopTypeSelect}"
    th:if="${not #maps.isEmpty(form.shopTypeSelect)  && shopTypeSelect.key != ''}">
    <input type="checkbox" class="form-check-input"
            th:id="'shopType'+${type.index}" th:name="shopType"
            th:value="${shopTypeSelect.key}"
            th:checked="${form.shopType==null}?'false':${#lists.contains(form.shopType,shopTypeSelect.key)}" />
			<label class="form-check-label" th:for="'shopType'+${type.index}"
			th:text="${shopTypeSelect.value}"></label>
    </div>

(8)单选框组件的显示和传参

<div class="form-check-inline"
	th:each="mdfyMthdSelect,method:${searchResult.mdfyMthdSelect}"
	th:object="${mdfyMthdSelect}"
	th:if="${not #maps.isEmpty(searchResult.mdfyMthdSelect)  && mdfyMthdSelect.key != ''}">
	<input type="radio" class="form-check-input"
		th:id="'mdfyMthd'+${method.index}" th:name="mdfyMthd"
		th:value="${mdfyMthdSelect.key}"
		th:checked="${mdfyMthdSelect.key=='1'}" /> <label
		class="form-radio-label" th:for="'mdfyMthd'+${method.index}"
		th:text="${mdfyMthdSelect.value}"></label>

		<!-- <input type="radio" name="changeMethod" class="form-check-input"
            id="distributeRadio" checked="checked" value="1"/> <label
            class="form-check-label" for="smbc" >振分</label>
        <input type="radio" name="changeMethod" class="form-check-input"
            id="changeRado" value="2"/> <label class="form-check-label"
            for="mizuho">変更</label> -->
</div>

(9)前台遍历数据
searchResult是form里的List,泛型为内部类,放置sql的检索结果

<div th:each="item : ${form.searchResult}" class="list-group">

(10)前台显示数据
判断内容是否为空,如果不为空就显示内容,如果为空就显示-

<h5 class="card-title flex-grow-1" th:text="${item.rsltShopNo !=null and item.rsltShopName != null} ? ${item.rsltShopNo}+' '+${item.rsltShopName} : '-'"></h5>

(11)编辑的链接

<a href="input/modify/"
    c21:href="@{/master/shop/edit(shopNo=${item.rsltShopNo},startDate=${item.rsltStartDate})}"
    class="btn btn-outline-primary">編集</a>

(12)HashMap根据key值取出value值
重点:item.rsltShopType是key值,shopTypeSelect是HashMap,KaTeX parse error: Expected group after '_' at position 22: …shopTypeSelect[_̲_{item.rsltShopType}__]就是HashMap根据key值取出value值

<div class="row">
    <label class="col-sm-2 col-xs-4">有効開始日</label> <span
        class="col-sm-4 col-xs-8"
        th:text="${item.rsltStartDate != null}? ${item.rsltStartDate} : '-'"></span>
    <label class="col-sm-2 col-xs-4">加盟店種別</label> <span
        class="col-sm-4 col-xs-8"
        th:text="${form.shopTypeSelect[__${item.rsltShopType}__] != null}? ${form.shopTypeSelect[__${item.rsltShopType}__]} : '-'"></span>
</div>

(13)用HashMap来代替modelAndView传值

	@RequestMapping(value = "/search", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> searchByStationName(
        @Valid @NotBlank @RequestParam("cmLineModalStationName") String cmLineModalStationName,
        @Validated CM0002V02Form form, BindingResult result) throws ValidationException {

        Map<String, Object> searchResult = new HashMap<>();
        List<CM0002V02Form> dataList = new ArrayList<CM0002V02Form>();
        if (result.hasErrors()) {
            throw new ValidationException(result);
        } else {
            form.setCmLineModalStationName(cmLineModalStationName);
            dataList = service.searchByStationName(form);
            int searchCount = dataList.size();
            int pageCnt = service.getPageCnt("CM0002V02");
            if (searchCount < 1) {
                result.reject("ECM00045", messageSource.getMessage("ECM00045", null, Locale.JAPAN));
                throw new ValidationException(result);
            } else if (pageCnt < searchCount) {
                result.reject("modalRrrors", messageSource.getMessage("WCM00069", new Object[] {
                    pageCnt
                }, Locale.JAPAN));
                dataList = dataList.subList(0, pageCnt);
                searchResult.put("errorMsg", messageSource.getMessage("WCM00069", new Object[] {
                    pageCnt
                }, Locale.JAPAN));
            }
        }
        searchResult.put("dataList", dataList);
        return searchResult;
    }

(14)ajax的案例
1)用class选择器从组件里面去除属性
$("#chooseStation").removeAttr(“data-dismiss”);

2)如果组件里面该属性没有定义,那就给他加上这个data-dismiss属性,并且值为modal
效果为data-dismiss=“modal”
if(typeof($("#chooseStation").attr(“data-dismiss”))==“undefined”){
$("#chooseStation").attr(“data-dismiss”,“modal”);
$("#chooseStation").on(“click”);

            <script type="text/javascript">
            var stationLineCd;
            var stationLineName;
            $("#searchStation").click(
                    function() {
                        $("#industoryGroupCd").html("");
                        $.ajaxGet("common/station/search", "searchForm", function(data) {
                            if(data.errorMsg){
                                $.showMessage([ data.errorMsg ], null, "message-area-modal-station");
                            }
                            valid = true;
                            if (data != undefined || data != null || data != "") {
                                var str = '';
                                var strStationLineName = '';
                                $.each(data.dataList, function(n, value) {
                                    strStationLineName = value.cmLineModalStationName + "/"
                                            + value.cmLineModalStationLineName;
                                    strStationLineCd = value.cmLineModalStaCd + "/" + value.cmLineModalArlnCd + "/" + value.cmLineModalBlkCd
                                     + "/" + value.cmLineModalStationAbbreviation + "/" + value.cmLineModalLineAbbreviation;
                                    str += "<option value=" + strStationLineCd + ">"
                                            + strStationLineName + "</option>";
                                })
                                $("#industoryGroupCd").html(str);
                            }
                        }, false, $._ajaxError, "message-area-modal-station");
                    });

            $("#chooseStation").click(function() {
                $('.invalid-feedback').remove();
                $('.is-invalid').removeClass('is-invalid');
                $("#message-area-modal-station").html("");
                $(".moda-listContent").html("");
                
                stationLineCd = $("#industoryGroupCd option:selected").val();
                stationLineName = $("#industoryGroupCd option:selected").text();
                
                $.ajax({
                    url : '/hq/common/station/chooseCheck',
                    type : 'GET',
                    dataType : 'json',
                    traditional : true,
                    async : false,
                    contentType : 'application/json;charset=UTF-8',
                    data : {
                        "stationLineName" : stationLineName
                    },
                    success : function(result) {
                        if(result.errorMsg){
                            $.showMessage([ result.errorMsg ], null, "message-area-modal-station");
                            $("#chooseStation").removeAttr("data-dismiss");
                        } else{
                            if(typeof($("#chooseStation").attr("data-dismiss"))=="undefined"){
                                $("#chooseStation").attr("data-dismiss","modal");
                               $("#chooseStation").on("click");
                            }
                            $("#cmLineModalStationName").val("");
                            $("#industoryGroupCd").html("");
                            var stationLineCdStr = stationLineCd.split("/");
                            var stationLineNameStr = stationLineName.split("/");
                            var stationName = stationLineNameStr[0];
                            var lineName = stationLineNameStr[1];
                            var stationCd = stationLineCdStr[0];
                            var lineCd = stationLineCdStr[1];
                            var blkCd = stationLineCdStr[2];
                            var stationAbbreviation = stationLineCdStr[3];
                            var lineAbbreviation = stationLineCdStr[4];
                            $("#stationStr").html(stationName);
                            $("#lineStr").html(lineName);
                            addLineStation();
                        }
                    }
                });
            })
            function addLineStation() {
                var station = {
                    lineName : stationLineName.split("/")[1],
                    stationName : stationLineName.split("/")[0],
                    lineAbbreviation: stationLineCd.split("/")[4],
                    stationAbbreviation: stationLineCd.split("/")[3],
                    blkCd: stationLineCd.split("/")[2],
                    lineCd : stationLineCd.split("/")[1],
                    stationCd: stationLineCd.split("/")[0],
                    busTime : '',
                    walkTime : '',
                };
                STATION_LIST.push(station);
                setStationDiv(STATION_LIST);
            }

            $(".close").click(function() {
                $('.invalid-feedback').remove();
                $('.is-invalid').removeClass('is-invalid');
                $("#message-area-modal-station").html("");
                $(".moda-listContent").html("");
                $("#cmLineModalStationName").val("");
                $("#industoryGroupCd").html("");
            });
            </script>

(15)表格数据传参和显示

						<table class="table table-bordered" id="tab">
							<thead>
								<tr class="table-info">
									<th>加盟店</th>
									<th>預り金残高</th>
									<th>振分金額</th>
									<th>変更後預り金残高</th>
								</tr>
							</thead>
							<tbody>
								<tr th:each="result ,item : ${searchResult.relatedShopResult}"
									id="srchRslt">
									<td style="text-align: left;" id="shopResult"
										th:text="${result.shopNoResult}+' '+${result.shopNameResult}"></td>
									<td style="text-align: right;" id="dpstBalResult"
										th:text="${result.dpstBalResult}"></td>
									<td style="text-align: right; width: 167px;" id="distributeAmt"><input
										type="text" class="number form-control"
										th:value="${result.dpstResult}" style="text-align: right;"
										id="distributeAmtInput"
										th:name="'relatedShopResult['+${item.index}+'].dpstResult'" /></td>
									<td style="text-align: right;" id="modifyDpstBalResultTd"
										th:text="${result.modifyDpstBalResult}"></td>
								</tr>
							</tbody>
						</table>

如何传送参数到后台(下一个隐藏的input,然后使用th:name把值通过form提交过去)

<div class="form-group row"
	th:each="result ,item : ${searchResult.relatedShopResult}"
	id="srchRslt">
	<input type="hidden" class="number form-control"
		th:value="${result.shopNoResult}" style="text-align: left;"
		id="'shopResult'+${item.index}"
		th:name="'relatedShopResult['+${item.index}+'].shopNoResult'" />
	<input type="hidden" class="number form-control"
		th:value="${result.dpstBalResult}" style="text-align: right;"
		id="'dpstBalResult'+${item.index}"
		th:name="'relatedShopResult['+${item.index}+'].dpstBalResult'" />
	<input type="hidden" class="number form-control"
		th:value="${result.modifyDpstBalResult}"
		style="text-align: right;"
		id="'modifyDpstBalResult'+${item.index}"
		th:name="'relatedShopResult['+${item.index}+'].modifyDpstBalResult'" />
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值