大三东软暑期实训-SSM整合篇

Posted Fire king

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大三东软暑期实训-SSM整合篇相关的知识,希望对你有一定的参考价值。

  • mybatis.xml已经整合到spring.xml中
  • 诸如
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp-api.version}</version>
      <scope>provided</scope>
    </dependency>

中有provided说明仅在开发中使用,部署到服务器服务器会提供。

  • bug:
    在这里插入图片描述
    在这里插入图片描述

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>
  • 数据库设计中文字段用utf8
  • web.xml与spring.xml和springmvc.xml绑定,spring.xml与sql映射文件绑定
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置实体类别名  默认的别名就是类的类名-->
        <property name="typeAliasesPackage" value="edu.xlh.pojo"></property>
        <!--指定 mapper 的sql映射文件   -->
        <property name="mapperLocations" value="classpath:mappers/*.xml" />
    </bean>
  • 表字段与实体类属性名不一致要起别名或者用resultMap
  • 业务层返回的数据类型取决于controller层要什么,controller需要什么取决于页面,所以业务层返回的数据类型最终取决于页面需要什么
  • 类似中${o.doorName}在页面获取不到值的解决:
<c:forEach items="${doorList}" var="o" varStatus="i">
            <tr>
                <td align="center">${i.index+1}</td>
                <td>${o.doorName}</td>
                <td>${o.doorTel}</td>

            </tr>
        </c:forEach>

加上<%@ page isELIgnored="false" %>

  • 数据库获取不到连接页面返回异常
    在这里插入图片描述

在这里插入图片描述
解决:
导入<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatDate value="${each.lastTime}" pattern="yyyy-MM-dd HH:mm:ss"/>

例子:

 <td><fmt:formatDate value="${o.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
                <td><fmt:formatDate value="${o.modifyTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>

  • 内部重定向再项目根路径下访问新路径
    demo1:
@RequestMapping("/add")
    public String add(){
        Door door  = new Door();
        door.setDoorName("冒菜店");
        door.setDoorTel("1234");
        int rows = doorService.addDoorInfo(door);
        return "redirect:/findAllList";
    }

demo2:

  @RequestMapping("/deleteById")
    public void deleteById(Integer id,HttpServletResponse response) throws IOException {
        doorService.deleteById(id);
        response.sendRedirect("/findAllList");
    }

demo3:

 @RequestMapping("/deleteById")
    public void deleteById(Integer id,HttpServletResponse response) throws IOException {
        doorService.deleteById(id);
        response.sendRedirect("/findAllList");
    }

总结:请求到达服务器controller后处理只能进行一次转发走视图解析器返回jsp,不能够再服务器内部转发到某个controller的某个方法,但重定向可以实现,因为此刻重定向就已经不再走视图解析器。

  • 后端写前端弹窗代码:
 response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<script>alert('删除失败');location.href='/findAllList';</script>");
        writer.close();
  • bug:出现了一系列创建bean失败,到spring.xml文件中找错,找跟扫包有关的标签。
  • @DateTimeFormat(pattern="yyyy-MM-dd")的使用
    springmvc默认时间参数为yyyy/MM/dd类型(会将前端传过来的string类型转成date类型封装到对象),使用yyyy-MM-dd类型作为url参数(即使是string类型也不会转换)会报错,这时就引出了@DateTimeFormat(pattern="yyyy-MM-dd")注解。
    同时,错误往往在controller层方法参数那里,方法体内使用try catch捕获不到错误。
    注意:用在实体类util时间类型
    在这里插入图片描述

在这里插入图片描述

  • <fmt:formatDate value="${o.modifyTime}" pattern="yyyy-MM-dd HH:mm:ss"/>嵌套再input标签
<input type="text" name="modifyTime" value="<fmt:formatDate value="${door.modifyTime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/>
  • form表单中隐藏input标签
 <input type="hidden" name="doorId" value="${door.doorId}">
  • 出现一堆bean创建不了的bug,可能是spring.xml文件有问题,注意扫包有没有正确
  • Http协议异常状态码:
    404 再服务器找不到指定路径
    405 请求类型不匹配
    500 服务端代码错误(包括访问数据库错误),jsp爆500可能是jsp错误,jsp编译成.java文件,服务端代码错误
    400 前端传入的参数类型和服务端接受的参数类型不匹配
    typeMismatch参数类型不匹配
DEBUG [http-bio-8067-exec-7] - Resolving exception from handler [public java.lang.String edu.xlh.controller.DoorController.toUpdate(edu.xlh.pojo.Door,org.springframework.ui.Model)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'door' on field 'createTime': rejected value [2021-06-07 00:00:00 ]; codes [typeMismatch.door.createTime,typeMismatch.createTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [door.createTime,createTime]; arguments []; default message [createTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-06-07 00:00:00 '; nested exception is java.lang.IllegalArgumentException]
Field error in object 'door' on field 'modifyTime': rejected value [2021-06-08 00:00:00]; codes [typeMismatch.door.modifyTime,typeMismatch.modifyTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [door.modifyTime,modifyTime]; arguments []; default message [modifyTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'modifyTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-06-08 00:00:00'; nested exception is java.lang.IllegalArgumentException]

  • 表单封装可以将部分属性封装成实体类,另一部分属性传参使用(属性名不能与实体类属性名一样)
  • 前端input标签中type="datetime-local"的使用:
    <td><input type="datetime-local" step="1" name="createTime1" value=""/></td>要与step="1"连用,显示秒数
    后端接受
@RequestMapping("/addOrder")
    public String addOrder(Order order,String created1,String updated2,String createTime1,String endTime1) throws ParseException {
        int index = created1.indexOf('T');
        String str1 = created1.substring(0,index);
        String str2 = created1.substring(index+1);
        String time = str1+" "+str2;
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date created = sd.parse(time);
        order.setCreated(created);

        index = updated2.indexOf('T');
        str1 = updated2.substring(0,index);
        str2 = updated2.substring(index+1);
        time = str1+" "+str2;
        sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date updated = sd.parse(time);
        order.setUpdated(updated);

        index = createTime1.indexOf('T');
        str1 = createTime1.substring(0,index);
        str2 = createTime1.substring(index+1);
        time = str1+" "+str2;
        sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sd.parse(time);
        order.setCreateTime(createTime);

        index = endTime1.indexOf('T');
        str1 = endTime1.substring(0,index);
        str2 = endTime1.substring(index+1);
        time = str1+" "+str2;
        sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endTime = sd.parse(time);
        order.setEndTime(endTime);



        orderService.addOrder(order);
        return "redirect:/findAllOrders";
    }

实体类:

package edu.xlh.pojo;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Order {

    Integer orderId;
    Integer dId;
    String orderNo;
    String orderType;
    String cashier;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    Date createTime;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    Date endTime;
    String paymentType;
    Double price;
    //@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    Date created;
    //@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    Date updated;

    public Integer getOrderId() {
        return orderId;
    }

    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public String getOrderType() {
        return orderType;
    }

    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }

    public String getCashier() {
        return cashier;
    }

    public void setCashier(String cashier) {
        this.cashier = cashier;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public String getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(String paymentType) {
        this.paymentType = paymentType;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", dId=" + dId +
                ", orderNo='" + orderNo + '\\'' +
                ", orderType='" + orderType + '\\'' +
                ", cashier='" + cashier + '\\'' +
                ", createTime=" + createTime +
                ", endTime=" + endTime +
                ", paymentType='" + paymentType + '\\'' +
                ", price=" + price +
                ", created=" + created +
                ", updated=" + updated +
                '}';
    }
}

<fmt:formatDate value="${order.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>与实体类配合使用@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")同时注意:@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")只有在前后端交互中前端封装为实体类属性才会生效,不必关心在java代码中Set实体类属性时会使用到

  • 不使用插件的分页
    下一页跳转初始化。查询第一页。
@RequestMapping("/toLimitPage")
    public String toLimitPage(@RequestParam(name="currentPage",defaultValue = "1") Integer currentPage,Model model){
    //当前页
    currentPage = currentPage+=1;
    Integer pageSize=2;
//获取中记录数
    int totalSize = orderService.getCountTotal();
    Integer totalPage = totalSize%pageSize!=0? totalSize/pageSize+1:totalSize/pageSize;
    if(currentPage>=totalPage){
        currentPage=totalPage;
    }
    if(currentPage<=1){
        currentPage=1;
    }
//偏移量 每页显示的条数
    Integer offSet=(currentPage-1)*pageSize;
    List<Order> list = orderService.findOrdersByPage(offSet, pageSize);
    model.addAttribute("totalPage",totalPage);
    model.addAttribute("orderList",list);
//当前页
    model.addAttribute("currentPage",currentPage);
    return "orderList";
    }

查询上一页:

@RequestMapping("/toUpPage")
    public String toUpPage(@RequestParam(name="currentPage",defaultValue = "1") Integer currentPage,Model model){
        int totalSize = orderService.getCountTotal();
        Integer pageSize=2;
        Integer totalPage = totalSize%pageSize!=0?totalSize/pageSize+1:totalSize/pageSize;
        if(currentPage!=1) {
            currentPage = currentPage - 1;
        }
        Integer offSet = (currentPage-1)*pageSize;
        List<Order> orderList = orderService.findOrdersByPage(offSet,pageSize);
        model.addAttribute("orderList",orderList);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("currentPage",currentPage);
        return "orderList";
    }

前端:

<p style="text-align: center"><a href="toUpPage?currentPage=${currentPage}">上一页</a>&nbsp;&nbsp;|<a href="toLimitPage?currentPage=${currentPage}">下一页</a>|&nbsp;&nbsp;总页数:<span>${totalPage}</span>页|&nbsp;&nbsp;当前页:<span>${currentPage}</span>大三东软暑期实训-springboot整合篇

大三东软暑期实训-spring篇2

大三东软暑期实训-spring篇1

大三东软暑期实训-springmvc篇

大三东软暑期实训-mybatis篇

大三后端暑期实习面经总结——SSM&微服务框架篇