Library management system (micro letter, background, web client) summary

Web courses Technical Summary

Front page

The basic framework

view

1, the value of storage problems

Need to change the property when (update), you need to get the properties (GET) , there needs to be set to null value on the server when returning, in updating the need to adopt selective approach , updateSelective () . Into the session when the need to empty the password to ensure update time will not be updated to a null value.

2, storage case value

get

@RequestMapping("/getBookAdmin")
public AjaxResult A12(HttpServletRequest request) {
    BookAdmin bookAdmin = bookAdminService.getBookAdmin(request);
    bookAdmin.setAdpassword(null);
    return GENERATE_SUCCESS_RESULT(bookAdmin);
}

update

//SysAdminController.java
@RequestMapping("/getSysAdmin")
public AjaxResult A12(HttpServletRequest request) {
        return GENERATE_SUCCESS_RESULT(userService.getSysAdmin(request));
    }

//BookAdminService.java
public void update(BookAdmin bookAdmin) {
    bookAdminMapper.updateByPrimaryKeySelective(bookAdmin);
}

3, when the difference between the front and rear ends of traditional values, the value when the value PageHelper with paging and

Micro-channel front end

1, the value of storage problems

Specific issues and similar vue

2, data used

I.e. able Page ({}) value of the direct access scope required by this object this.data.is positioned in the form of

3, the use of global variables

Global variables are as defined in the micro-channel app.js the root directory , the App({})next thing is belonging comprising global

App({
  global: {
 }
}
)

By using a method other pages with var app = getApp()the introduction can be carried out using

Global variables can be used as a temporary variable between pages of memory that is similar to the jump page two ends jsp的传值通过the session 而不是request` to achieve

4, wx applet request

The micro-channel wx.requestis not with what state variables, simply by sending an http request stateless, where stateless means he does not carry information other than the specified information. For example session.

For java server daemon with the permission verification, storing information in the form of part of the session, you will need to save the session itself and the end value of the micro-channel achieved by each transmission request carries Header . By saving session value to a global variable described earlier, each band corresponding to the transmission request header can.

//全局作用域中添加Header变量
App({
  global: {
    header:{
      'Cookie':''
    }
  }
})
//在登陆或者初始化请求时进行获取session值
 wx.request({
        url: "http://localhost:8080/login",
        method: 'post',
        data: e.detail.value,
        success: function(value) {
          if (that.parseInfo(value)) {
            //存储用户信息
            app.global.user = value.data.data;
            app.global.header.Cookie = value.cookies[0];
 })

//在发送请求时携带Header
wx.request({
      url: 'http://localhost:8080/user/updateUser',
      method: 'post',
      data: e.detail.value,
      header: app.global.header,
      success:function(res){
        console.log(res);
      }
});

Front and rear ends by value

1, will be used as JSON front and rear ends pass value

Using the value passed in the front end of application/jsonthe form is traditional values, and guarantees vueand wxconsistency

2, the return value package

Use AjaxResult method returns the correct value the package, wherein the main portion is used to carry the correct AjaxResult or error code, returns the corresponding information correctly or if an error

@Data
public class AjaxResult<T> implements Serializable {
    private T data = null;
    private String url = null;
    private String message = null;
    private short resultCode;
}

rear end

1, lombok use

2, PageHelper perfect

The following code pageHelp generateCheck

public static PageHelper generateCheckedHelper(int count, PageHelper pageHelper) {
        if (pageHelper == null)
            return pageHelper;
        pageHelper.setCount(count);

        if (pageHelper.getPageSize() == null || pageHelper.getPageSize() <= 1)
            pageHelper.setPageSize(10);
        pageHelper.setTotalPage(pageHelper.getTotalPage());

    //判断当前页面是否为空
        if (pageHelper.getCurrentPage() == null || pageHelper.getCurrentPage() <= 0)
            pageHelper.setCurrentPage(1);
        if (pageHelper.currentPage > pageHelper.totalPage)
            pageHelper.setCurrentPage(pageHelper.totalPage);
        if (pageHelper.getCurrentPage() == null || pageHelper.getCurrentPage() <= 0)
            pageHelper.setCurrentPage(1);
        return pageHelper;

    }

The following flowchart pageHelper

flow
en=>end: 返回pageHelper
st=>start: 开始
setCount=>operation: setCount
pageHelperIsNull=>condition: pageHelper为空
pageSizeIsNullOrLow=>condition: pageSize==null||pageSize<=1
setPageSize=>operation: setPageSize(10)
setTotalPageSize=>operation: setTotalPage(totalPage);

curPageIsNullOrLow1=>condition: curPage==null||curPage<=0
setCurPage21=>operation: setCurrentPage(1);

curPageBigTotalPage=>condition:currentPage>totalPage
setCurPage2TotalPage=>operation:setCurrentPage(totalPage)

curPageIsNullOrLow2=>condition: curPage==null||curPage<=0
setCurPage22=>operation: setCurrentPage(1);

st->pageHelperIsNull
pageHelperIsNull(yes)->pageSizeIsNullOrLow
pageHelperIsNull(no)->setCount
setCount->pageSizeIsNullOrLow

pageSizeIsNullOrLow(yes)->setPageSize
setPageSize->setTotalPageSize
pageSizeIsNullOrLow(no)->setTotalPageSize

setTotalPageSize->curPageIsNullOrLow1

curPageIsNullOrLow1(yes)->setCurPage21
setCurPage21->curPageBigTotalPage
curPageIsNullOrLow1(no)->curPageBigTotalPage

curPageBigTotalPage(yes)->setCurPage2TotalPage
setCurPage2TotalPage->curPageIsNullOrLow2
curPageBigTotalPage(no)->curPageIsNullOrLow2

curPageIsNullOrLow2(yes)->setCurPage22
curPageIsNullOrLow2(no)->en
setCurPage22->en

3, DTO, BeanUtil, Objects, StringUtil use

BeanUtil

BeanUtil commonly used method copyPropertiesfor assigning attribute values, but set to the corresponding set and get property methods

/*将source中所有属性复制到target中,实现时通过获取source中的每个属性get方法,并获取值。当某个属性没有get方法时会出错*/
public static void copyProperties(Object source, Object target) throws BeansException {
    copyProperties(source, target, (Class)null, (String[])null);
}

public static void copyProperties(Object source, Object target, Class<?> editable) throws BeansException {
    copyProperties(source, target, editable, (String[])null);
}
/*将source中所有属性复制到target中并忽略其中提到的ignoreProperties,实现时通过获取source中的每个属性get方法,并获取值。当某个属性没有get方法时会出错*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
    copyProperties(source, target, (Class)null, ignoreProperties);
}

Objects

package java.util;

public final class Objects {
    //对于两个对象,这个也不错
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
    //获取hash值
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
    //对于数组
    public static boolean deepEquals(Object a, Object b) {
        if (a == b)
            return true;
        else if (a == null || b == null)
            return false;
        else
            return Arrays.deepEquals0(a, b);
    }
    //必须为非空,这个挺好用的
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
}

4, permission interceptors and regular expressions

In this experiment, a total of three roles, permissions need to address the three judges

  • /sysAdmin/**
  • /bookAdmin/**
  • /user/**
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
    
public void addInterceptors(InterceptorRegistry registry) {
    //这里参数是一个实现了HandlerInterceptor接口的拦截器
    registry.addInterceptor(reThis())
            .addPathPatterns("/sysAdmin/**")//需要拦截的请求
            .addPathPatterns("/bookAdmin/**")
            .addPathPatterns("/user/**")
            .excludePathPatterns("/*");
}
        //    @Bean
public MyInterceptor reThis() {
        return new MyInterceptor();
}
    
}

Interceptor interceptor used in regular expressions to determine if the address of the current roles and access it through the match, otherwise jump and intercept, to note that the value of boolean type preHandler returned, if it is false that represents the current interceptor processing all information is no longer backward pass information.

@Configuration
public class MyInterceptor implements HandlerInterceptor {
    //将bean注册到容器中
    @Bean
    public MyInterceptor retrunMy() {
        return new MyInterceptor();
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean acc = false;
        String url = request.getRequestURI();
        Object user = request.getSession().getAttribute("user");
        String patternForSysAdmin = "/sysAdmin/.*";
        String patternForBookAdmin = "/bookAdmin/.*";
        String patterForUser = "/user/.*";

        if (user == null)
            acc = false;
        else if (user instanceof User) {
            acc = Pattern.matches(patterForUser, url);
        } else if (user instanceof SysAdmin) {
            acc = Pattern.matches(patternForSysAdmin, url);
        } else if (user instanceof BookAdmin)
            acc = Pattern.matches(patternForBookAdmin, url);
        System.out.println(String.format("###拦截器  请求的地址: %s , user值:%s , 不拦截?: %s", request.getRequestURI(), request.getSession().getAttribute("user"), acc));
        if (!acc)
            response.sendRedirect("/");
        return acc;
    }
}

One thing to note is .addPathPatterns and Pattern.matches in the regular expression is not the same specification

5, exception handling, and the global exception handler

@ControllerAdviceThe method to intercept processing

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NullOrEmptyException.class)
    @ResponseBody
    public AjaxResult hanleNull(HttpServletRequest request, Exception exception) throws Exception {
        System.out.println(String.format("接受到来自request: %s 的错误请求  , message: %s , localizedMessage : %s", request.getRequestURI(), exception.getMessage(), exception.getLocalizedMessage()));
        exception.printStackTrace();
        return ResultGenerator.GENERATE_FAILED_MESSAGE(exception.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public AjaxResult hanleNullP(HttpServletRequest request, Exception exception) throws Exception {
        System.out.println(String.format("接受到来自request: %s 的错误请求  , message: %s , localizedMessage : %s", request.getRequestURI(), exception.getMessage(), exception.getLocalizedMessage()));
        exception.printStackTrace();
        return ResultGenerator.GENERATE_FAILED_MESSAGE("参数不能为空");
    }

    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public AjaxResult handlePK(HttpServletRequest request, Exception exception) throws Exception {
        System.out.println(String.format("错误请求:MySQL异常,接受到来自request: %s 的错误请求  , message: %s , localizedMessage : %s", request.getRequestURI(), exception.getMessage(), exception.getLocalizedMessage()));
        exception.printStackTrace();
        return ResultGenerator.GENERATE_FAILED_MESSAGE("id不能重复");
    }
}

Doubt, intercept less than SQLException

6, efficient use of view-controller

WebMvcConfigurerAdapter by the addViewControllers(ViewControllerRegistry registry)method of adding viewControllerdirectly urlmapped to the address /template/**below template pages. Rather than for each templateare built with one pair ofmapping

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //为模板/template/world.html设置一个名为/world的访问路径,因为设置了template的后缀为.html,当在现有的@RequestMapping中找不到/helloworld时就会跳到/template/world.html上
        
        registry.addViewController("/world").setViewName("/helloworld");
    }
}

7, session store user information

When the session by storing user information, please sensitive information like passwords or saltsuch information is set to null instead of the empty string "" If set to an empty string may cause some user information is lost off the original time information updates .

((User) userDB).setPassword(null);

database

{} Is used PraparedStatement, by way of direct injection of set values, checks belonging DBMS, the value obtained by adding a direct injection""

update TABLEA set a=${A};

} $ {String concatenation method is used, can not be directly injected through the injection values. After the addition, for String A = "123"the added value is

update TABLEA set a=123;

But $ # {} {} and can be mixed

<when test="criterion.noValue">and ${criterion.condition}</when>

Guess you like

Origin www.cnblogs.com/Heliner/p/10960899.html