Summary of Blind Points in SSM Small demo

Keywords: Java Spring xml JSP Database

Conversion between Date and String:

1. Global Converter(Recommended use)
    1. Create class implementations Converter Interface,Realization Convert Method
        public class StringToDateConvert implements Converter<String, Date> {
            @Override
            public Date convert(String resource) {
                if(resource == null){
                    throw new RuntimeException("Please enter a value");
                }
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date parse = df.parse(resource);
                    return parse;
                } catch (ParseException e) {
                    throw new RuntimeException("Data format conversion exception");
                }
            }
        }
    2. stay SpringMVC Configuration converter in configuration file
         <!--Configure custom Date Converter-->
        <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <bean class="cn.wzlove.utils.StringToDateConvert"/>
                </set>
            </property>
        </bean>
        <!--open MVC Annotation driven(Loading processor mappers and processor adapters)-->
        <mvc:annotation-driven conversion-service="conversionService">
        </mvc:annotation-driven>
        
2. Attribute Converter
    //Conversion using annotations:
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
    private Date departureTime;
    

For the display of dates on the page (get method needs attention)

Consider using strings for displaying dates on pages,Create one more String attribute,Use this string property when presenting in the foreground,Just remember the conversion type..

//Entity class:
     private Date departureTime;
     private String departureTimeStr;
     
     public String getDepartureTimeStr() {
        if(departureTime != null){
            departureTimeStr = DateFromatUtils.date2String(departureTime,"yyyy-MM-dd HH:mm");
        }
        return departureTimeStr;
    }
DateFromatUtils:
    public class DateFromatUtils {
        /**
         * Date to time
         * @param date
         * @param patt
         * @return
         */
        public static String date2String(Date date, String patt){
            SimpleDateFormat sdf = new SimpleDateFormat(patt);
            String format = sdf.format(date);
            return format;
        }
    
    
        /**
         * String Return Date
         * @param time
         * @param patt
         * @return
         */
        public static Date string2Date(String time, String patt){
            SimpleDateFormat sdf = new SimpleDateFormat(patt);
            try {
                Date date = sdf.parse(time);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("Date conversion exception");
            }
        }
    }

Display special tag attributes on the page (get method needs attention)

Similar to date,Create additional fields for presentation
     /**
     * State 0 Close 1 Open
     */
    private Integer productStatus;

    /**
     * String description of state
     */
    private String productStatusStr;
    
     public String getProductStatusStr() {
        if(null != productStatus){
            if(productStatus == 0){
                productStatusStr = "Close";
            } else if(productStatus == 1){
                productStatusStr = "open";
            }
        }
        return productStatusStr;
    }
    

One-to-one and many-to-many reviews of Mybatis:

One-on-one:
    @Select("select * from orders")
    @Results({
            @Result(id = true,property = "id", column = "ID"),
            @Result(property = "orderNum",column = "ORDERNUM"),
            @Result(property = "orderTime",column = "ORDERTIME"),
            @Result(property = "orderStatus",column = "ORDERSTATUS"),
            @Result(property = "peopleCount",column = "PEOPLECOUNT"),
            @Result(property = "payType",column = "PAYTYPE"),
            @Result(property = "orderDesc",column = "ORDERDESC"),
            @Result(property = "product",column = "PRODUCTID",javaType = Product.class,
            one = @One(select = "cn.wzlove.mapper.ProductMapper.findProductById"))
    })
//Many-to-many:
    @Select("select * from orders where id = #{ordersId}")
    @Results({
            @Result(id = true,property = "id", column = "ID"),
            @Result(property = "orderNum",column = "ORDERNUM"),
            @Result(property = "orderTime",column = "ORDERTIME"),
            @Result(property = "orderStatus",column = "ORDERSTATUS"),
            @Result(property = "peopleCount",column = "PEOPLECOUNT"),
            @Result(property = "payType",column = "PAYTYPE"),
            @Result(property = "orderDesc",column = "ORDERDESC"),
            @Result(property = "product",column = "PRODUCTID",javaType = Product.class,
                    one = @One(select = "cn.wzlove.mapper.ProductMapper.findProductById")),
            @Result(property = "member",column = "MEMBERID",javaType = Member.class,
                    one = @One(select = "cn.wzlove.mapper.MemberMapper.findMemberById")),
            @Result(property = "travellers",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.wzlove.mapper.TravellerMapper.findTravelByOrderId"))
    })
    

Use of PageHelper:

1. Import dependency
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.2</version>
    </dependency>
2. Configuration
     <!--To configure sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="cn.wzlove.domain"/>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            <prop key="helperDialect">oracle</prop>
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
3. Use
     @RequestMapping("findAll.do")
    public ModelAndView findOrdersAll(@RequestParam(name = "page",required = true,defaultValue = "1") Integer page,
                                      @RequestParam(name = "size",required = true,defaultValue = "4") Integer size){
        ModelAndView mv = new ModelAndView();
        PageHelper.startPage(page,size);
        List<Orders> allOrders = ordersService.findAllOrders();
        PageInfo<Orders> pageInfo = new PageInfo<>(allOrders);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("orders-list");
        return mv;
    }
4. about PageInfo Consider looking at the source code to see the encapsulated paging information,List commonly used
     //Current page
    private int pageNum;
    //Number of pages per page
    private int pageSize;
    //Number of current pages
    private int size;

    //Since startRow and endRow are not commonly used, here's a specific usage
    //You can "display startRow to endRow total size data" in the page

    //The line number of the first element of the current page in the database
    private int startRow;
    //The line number of the last element of the current page in the database
    private int endRow;
    //Total number of records
    private long total;
    //PageCount
    private int pages;
    //Result Set
    private List<T> list;

    //next page before
    private int prePage;
    //next page
    private int nextPage;
    

Permission management (use of Srping security)

1. Srping security Use: Security framework(Authentication and Authorization)
    1. Import dependency
        spring-security-web
        spring-security-config
    2. web.xml Configure filters
        ContextLoaderListener----------> Load spring-Security.xml Configuration file
        DelegatingFilterProxt----------> Principal Filter Agent Class-----> springSecurityFilterChain(Names can't be changed)
    3. spring-security Configuration of Core Profiles
        1. Which resources are accessible without login,That's filtering.
            <security:http pattern="" security="none" >
        2. Authentication Manager
            <security:authentication-manager>
        3. Configuring Interception Rules
             <security:http auto-config="true" use-expressions="false">
//The code is as follows:
    2. web.xml Configuration:
        <filter>
            <filter-name>springSecurityFilterChain</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <!--
                classpath and classpath*Differences
                    //The former represents loading configuration files under the classpath of the current project
                    //The latter represents loading from the classpath of the current project and the classpath of the jar package
            -->
            <param-value>
                classpath*:applicationContext.xml,
                classpath*:spring-security.xml
            </param-value>
        </context-param>
    3. spring-security.xml Configuration:
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:security="http://www.springframework.org/schema/security"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security.xsd">
        
            <!-- Configuration of non-intercepted resources -->
            <security:http pattern="/login.jsp" security="none"/>
            <security:http pattern="/failer.jsp" security="none"/>
            <security:http pattern="/css/**" security="none"/>
            <security:http pattern="/img/**" security="none"/>
            <security:http pattern="/plugins/**" security="none"/>
        
            <!--
                //Configure specific rules
                auto-config="true"  Instead of writing your own login page, the framework provides the default login page
                use-expressions="false" Whether to use SPEL Expressions (not learned)
            -->
            <!-- Configure specific interception rules pattern="Rules for Request Path" access="The person who accesses the system must have ROLE_USER Role" -->
            <security:http auto-config="true" use-expressions="false">
                <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
        
                <!-- Define specific pages for jumps -->
                <security:form-login
                        login-page="/login.jsp"
                        login-processing-url="/login"
                        default-target-url="/index.jsp"
                        authentication-failure-url="/failer.jsp"
                        authentication-success-forward-url="/pages/main.jsp"
                />
        
                <!-- Close cross-domain requests -->
                <security:csrf disabled="true"/>
        
                <!-- Sign out -->
                <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/login.jsp" />
        
            </security:http>
        
            <!-- Switch to username and password in database -->
            <security:authentication-manager>
                <security:authentication-provider user-service-ref="userService">
                    <!-- How to configure encryption(Initially because the password was not encrypted,So this should be commented out first.,Wait until the password is encrypted before you let it go.) -->
                    <security:password-encoder ref="passwordEncoder"/>
                </security:authentication-provider>
            </security:authentication-manager>
        
            <!-- Configuring encryption classes -->
            <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
        
            <!-- Provides a way to get started by storing usernames and passwords in memory
            <security:authentication-manager>
                <security:authentication-provider>
                    <security:user-service>
                        <security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
                    </security:user-service>
                </security:authentication-provider>
            </security:authentication-manager>
            -->
            <!--If the password is not encrypted,Then the password needs to be added before{noop}-->
        </beans>
        

Privilege Control of Spring Security

Server privilege control
1. JSR250 Annotation Configuration
    1. Introducing dependencies into pom.xml
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>
    2. Open annotation switch in spring-security.xml configuration file
         <security:global-method-security  jsr250-annotations="enabled"></security:global-method-security>
    3. Use annotations in methods (generally on Controller annotations)
        Roles Allowed ({"ADMIN", "USER"}) ====> must have an ADMIN or USER role to access this method
        PermitAll====> Allows all roles to access
        DenyAll ===> All roles are inaccessible
         
2. Use the @Secured annotation
    1. Open annotation switch in spring-security.xml configuration file
        <security:global-method-security secured-annotations="enabled"></security:global-method-security>
    2. Use annotations
        Secured ("ROLE_ADMIN") ====> Users with ADMIN roles are accessible and must have ROLE_
3. Expression-based
    1. Turn on the comment switch in the configuration file
        <security:global-method-security pre-post-annotations="enabled" ></security:global-method-security>
    2. @PreAuthorize ("hasRole ('ROLE_ADMIN')") ====> If the expression returns true, the method can be accessed. Because spel expressions are used, the configuration files need to be changed (on the original basis, modify use-expressions and access):
        <security:http auto-config="true" use-expressions="true">
    <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
    
     PreAuthorize ("authentication. principal. username =='wzlove') means that only wzlove users can access it.
Front-end privilege control
1. stay pom.xml Introducing dependency
     <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
2. stay jsp Page Introducing Label Library:
    <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
3. Use of labels:
    1. Get the current logged-in username
        <security:authentication property="principal.username"/>
    2. Hide labels according to permissions(Have ADMIN The role can display the label)
        <security:authorize access="hasRole('ADMIN')">
            <li id="system-setting"><a
                href="${pageContext.request.contextPath}/user/findAll"> <i
                    class="fa fa-circle-o"></i> user management
            </a></li>
        </security:authorize>
        

Logging control of Spring AOP (storing data in a database)

1. Create the table structure of the database:
    CREATE TABLE sysLog(
        id VARCHAR2(32) default SYS_GUID() PRIMARY KEY,
        visitTime timestamp,
        username VARCHAR2(50),
        ip VARCHAR2(30),
        url VARCHAR2(50),
        executionTime int,
        method VARCHAR2(200)
    )
2. Create log entities:
    public class SysLog {

        /**
         * Primary key uuid
         */
        private String id;
        /**
         * Access time
         */
        private Date visitTime;
        /**
         * Visit Time Front Desk Show
         */
        private String visitTimeStr;
        /**
         * Operator
         */
        private String username;
        /**
         * Operator ip
         */
        private String ip;
        /**
         * The URL of the operation
         */
        private String url;
        /**
         * Length of execution
         */
        private Long executionTime;
        /**
         * Access methods
         */
        private String method;
        
        setter and getter
    }
4. Establish mapper:
    @Mapper
    public interface SysLogMapper {
    
    
        @Insert("insert into syslog(visitTime,username,ip,url,executionTime,method) values(#{visitTime},#{username},#{ip},#{url},#{executionTime},#{method})")
        void saveSysLog(SysLog sysLog);
    
        @Select("select * from syslog")
        List<SysLog> findAll();
    
    }
5. AOP control:
    @Component
    @Aspect
    public class LogAop {
    
        @Autowired
        private HttpServletRequest request;
    
        @Autowired
        private SysLogService sysLogService;
    
        @Around("execution(* cn.wzlove.controller.*.*(..))")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
    
            Object proceed = null;
            // Access methods (get classes and methods separately, then splice)
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            // Controller ignoring the log itself
            if("cn.wzlove.controller.SysLogController".equals(className)){
                // Getting parameters
                Object[] args = pjp.getArgs();
                // Execute the original method (release)
                proceed = pjp.proceed(args);
            } else{
                // Encapsulate SysLog to get the properties of SysLog
                // Access time
                Date visitDate = new Date();
                // Operator
                String loginName = SecurityContextHolder.getContext().getAuthentication().getName();
                // Operator ip
                String remoteAddr = request.getRemoteAddr();
                // The URL of the operation
                String requestURI = request.getRequestURI();
    
    
    
                // Length of execution
                Long startTime = System.currentTimeMillis();
                // Getting parameters
                Object[] args = pjp.getArgs();
                // Execute the original method (release)
                proceed = pjp.proceed(args);
    
                // Ending time
                Long endTime = System.currentTimeMillis();
                Long executeTime = endTime - startTime;
    
                // Encapsulating SysLog
                SysLog sysLog = new SysLog();
                sysLog.setIp(remoteAddr);
                sysLog.setExecutionTime(executeTime);
                sysLog.setMethod(className+"."+methodName);
                sysLog.setUsername(loginName);
                sysLog.setVisitTime(visitDate);
                sysLog.setUrl(requestURI);
    
                // Insert operation
                sysLogService.saveSysLog(sysLog);
            }
    
    
    
            return proceed;
        }
    
    
    }
6. Logged Controller
    @Controller
    @RequestMapping("sysLog")
    public class SysLogController {
    
    
        @Autowired
        private SysLogService sysLogService;
    
        @RequestMapping("findAll")
        public ModelAndView findAll(){
            ModelAndView mv = new ModelAndView();
            List<SysLog> all = sysLogService.findAll();
            mv.addObject("sysLogs",all);
            mv.setViewName("syslog-list");
            return mv;
        }
    
    }

Posted by jimmyborofan on Fri, 25 Jan 2019 00:24:13 -0800