主頁 > 後端開發 > 寫ssm專案的注意點

寫ssm專案的注意點

2020-10-28 06:10:44 後端開發

目錄
  • 注意事項:
    • 輸出臺亂碼
    • a鏈接以post提交
    • 表單提交前驗證
    • 跳轉前確認
    • c:if 判斷
    • jsr303驗證表單
    • Ajax
    • shiro
      • shiro注解
      • jsp中Shiro使用的標簽
      • shiro使用
    • 日期轉換
    • json亂碼
    • 重置按鈕
    • 路徑跳轉問題:
    • PageHelper使用

注意事項:

輸出臺亂碼

1587649720639

a鏈接以post提交

1587631225911

表單提交前驗證

onsubmit 屬性在提交表單時觸發,

onsubmit 屬性只在

中使用,

<form action="/demo/demo_form.asp" onsubmit="checkForm()">
姓:<input type="text" name="lname"><br>
名:<input type="text" name="fname"><br>
<input type="submit" value="https://www.cnblogs.com/jklixin/p/提交">
    
<script>
    function checkForm()
    {
    	alert("表單已提交!");
    }
</script>

跳轉前確認

在跳轉鏈接前,需要判斷該用戶是否有權限打開頁面,沒有權限的彈出一個確認框提示“沒有權限”,有權限的則直接跳轉頁面,

參考資料一:
http://jingyan.baidu.com/article/425e69e6d043bebe15fc16db.html

a標簽點擊時跳出確認框
方法一:

<a href="http://www.baidu.com" onClick="return confirm('確定洗掉?');">[洗掉]</a>

方法二:

<a onclick="confirm(‘確定要跳轉嗎?')?location.href='https://www.cnblogs.com/jklixin/p/www.baidu.com':''" href="javascript:;">百度</a>

參考資料二:
http://blog.csdn.net/wujiangwei567/article/details/40352689

①在html標簽中出現提示

<a href="http://www.baidu.com" onclick="if(confirm('確認百度嗎?')==false)return false;">百度</a>

②在js函式中呼叫

function foo(){
if(confirm("確認百度嗎?")){
return true;
}
return false;
}

對應的標簽改為:

<a href="http://www.baidu.com" onclick="return foo();">百度</a>

注意事項:

以上參考資料總結:

1.跳轉的方法:

1>. 把連接放在a元素的href屬性中進行頁面跳轉

2>. 使用location.href進行頁面跳轉

c:if 判斷

字串與域中的字串是否相等

1、<c:if test="${student.sex eq '男'}我是空格"></c:if>,注意是${student.sex eq '男'}后面的空格

2、<c:if test="${student.sex eq '男'}"></c:if>

注意不要有多余的空格,判斷相等用eq關鍵字

jsr303驗證表單

@PostMapping("/editStudent")
    public String editStudentUI(@Valid @ModelAttribute Student student , BindingResult result, Model model){
        if (!bindResult(result, model)){
            return "error";
        }
        try {
            studentServiceImpl.update(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/showStudent";
    }
    
    
     public boolean bindResult(BindingResult result, Model model){
        if (result.hasErrors()){
            List<String> errors=new ArrayList<>();
            List<ObjectError> errorList = result.getAllErrors();
            for(ObjectError error : errorList){
                errors.add(error.getDefaultMessage());
            }
            model.addAttribute("error",errors);
            return false;
        } else{
            return true;
        }

    }
package com.system.pojo.base;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.NotNull;
import java.util.Date;

public class Student {
    private Integer userid;

    @NotBlank(message = "姓名不能為空")
    private String username;

    private String sex;

    private Date birthyear;

    private Date grade;

    private Integer collegeid;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public Date getBirthyear() {
        return birthyear;
    }

    public void setBirthyear(Date birthyear) {
        this.birthyear = birthyear;
    }

    public Date getGrade() {
        return grade;
    }

    public void setGrade(Date grade) {
        this.grade = grade;
    }

    public Integer getCollegeid() {
        return collegeid;
    }

    public void setCollegeid(Integer collegeid) {
        this.collegeid = collegeid;
    }

    @Override
    public String toString() {
        return "Student{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthyear=" + birthyear +
                ", grade=" + grade +
                ", collegeid=" + collegeid +
                '}';
    }
}

Ajax

引數:

? url: 請求地址

? type: 請求方式 (默認是get請求)

? headers:

? data: 待發送的引數資料key/value

? success:成功之后的回呼函式

? dataType: 將服務器端回傳的資料轉成指定型別("xml","json","text","html","jsonp"...)

$.post

shiro

shiro注解

Shiro的常用注解

@RequiresPermissions :要求當前Subject在執行被注解的方法時具備一個或多個對應的權限,
@RequiresRoles("xxx") :要求當前Subject在執行被注解的方法時具備所有的角色,否則將拋出AuthorizationException例外,
@RequiresAuthentication:要求在訪問或呼叫被注解的類/實體/方法時,Subject在當前的session中已經被驗證,

1584880103271

jsp中Shiro使用的標簽

需要在jsp頁面中引入標簽
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
標簽:
shiro:authenticated 認證且不是記住我
shiro:notAuthenticated 未身份認證,包括記住我自動登錄
shiro:guest 用戶沒有認證在沒有RememberMe時
shiro:user 用戶認證且在RememberMe時
<shiro:hasAnyRoles name="abc,123" > 在有abc或者123角色時
<shiro:hasRole name="abc"> 擁有角色abc
<shiro:lacksRole name="abc"> 沒有角色abc
<shiro:hasPermission name="abc"> 擁有權限資源abc <shiro:lacksPermission name="abc"> 沒有abc權限資源
shiro:principal 顯示用戶身份名稱
<shiro:principal property="username"/> 顯示用戶身份中的屬性值

shiro使用

Subject:相當于用戶

SecurityManager:相當于DispatcherServlet

Realm:相等于DataSource

  • 匯入依賴

    <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.2.3</version>
            </dependency>
    ....
    //– shiro-all-1.3.2.jar 
    //– log4j-1.2.15.jar 
    //– slf4j-api-1.6.1.jar 
    //– slf4j-log4j12-1.6.1.jar
    
  • web.xml

    <!-- name要和 applicationContext.xml中的對應的bean的id一致 -->
        <!--Shiro攔截器 shiro入口-->
       <filter>
            <filter-name>shiroFilter</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
            <init-param>
                <!-- 該值預設為false,表示生命周期由SpringApplicationContext管理,設定為true則表示由ServletContainer管理 -->
                <param-name>targetFilterLifecycle</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
    
        <filter-mapping>
            <filter-name>shiroFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
  • 組態檔

    1. 配置自定義的realm類、(或者自動掃描)--》創建realm物件,如:myRealm
    2. 配置DefaultWebSecurityManager,需要用到realm物件--》創建DefaultWebSecurityManager,如:securityManager
    3. 配置ShiroFilterFactoryBean,需要用到DefaultWebSecurityManager物件---》創建ShiroFilterFactoryBean,如:shiroFilter(與web.xml中過濾器名字配置的一致)

    URL 權限采取第一次匹配優先的方式

    1584878199086
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring-beans.xsd
    	http://www.springframework.org/schema/context
    	http://www.springframework.org/schema/context/spring-context.xsd
    	">
    
        <!--配置自定義realm類-->
       <!-- <bean id="myRealm" >
            <property name="credentialsMatcher">
                <bean >
                    <property name="hashAlgorithmName" value="https://www.cnblogs.com/jklixin/p/MD5"></property>
                    <property name="hashIterations" value="https://www.cnblogs.com/jklixin/p/1024"></property>
                </bean>
            </property>
        </bean>-->
    
        <context:component-scan base-package="com.system.realm" />
    
        <!--安全管理器-->
        <bean id="securityManager" >
            <property name="realm" ref="myRealm"/>
        </bean>
    
    
         <!--與web.xml中過濾器名稱一致-->
        <bean id="shiroFilter" >
            <!-- Shiro的核心安全介面,這個屬性是必須的 -->
            <property name="securityManager" ref="securityManager"/>
            <!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->
            <!-- 要求登錄時的鏈接(登錄頁面地址),非必須的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
            <!--<property name="loginUrl" value="https://www.cnblogs.com/login.jsp"/>
            <property name="successUrl" value="https://www.cnblogs.com/index.jsp"/>-->
            <!-- 權限認證失敗,則跳轉到指定頁面 -->
            <!--<property name="unauthorizedUrl" value="https://www.cnblogs.com/login.htmls"/>-->
            <!-- Shiro連接約束配置,即過濾鏈的定義 -->
            <property name="filterChainDefinitions">
                <value>
                    <!--anon 表示匿名訪問,不需要認證以及授權-->
                    <!--authc表示需要認證 沒有進行身份認證是不能進行訪問的-->
    
                    <!--當訪問login時,不用進行認證-->
                    /login = anon
    
                    <!--配置靜態資源可以匿名訪問-->
                    /css/** = anon
                    /dist/** = anon
                    /js/** = anon
                    /fonts/** = anon
    
                    /admin/** = authc,roles[admin]
                    /teacher/** = authc,roles[teacher]
                    /student/** = authc,roles[student]
    
    
                    /logout = logout
    
                    <!--只有登陸界面可以匿名訪問,其他路徑都需要登錄認證才能訪問,沒有登陸訪問其他路徑回跳轉登陸頁面-->
                    /**=authc
    
                </value>
            </property>
    
        </bean>
    
        <!-- 生命周期 -->
        <bean id="lifecycleBeanPostProcessor"  />
    
    
        <!-- 啟用shiro注解 -->
        <bean  depends-on="lifecycleBeanPostProcessor"/>
        <bean >
            <property name="securityManager" ref="securityManager"/>
        </bean>
    
    </beans>
    
    
  • 自定義realm

    package com.system.realm;
    
    import com.system.pojo.base.Role;
    import com.system.pojo.base.User;
    import com.system.service.RoleService;
    import com.system.service.UserLoginService;
    import org.apache.shiro.authc.*;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * @Description: 自定義的Realm
     * @Date 2020/3/21
     **/
    @Component
    public class MyRealm extends AuthorizingRealm {
    
        @Autowired
        private UserLoginService userLoginServiceImpl;
    
        @Autowired
        private RoleService roleServiceImpl;
    
        /**
         * @Description: 權限驗證,獲取身份資訊
         * @Param0: principalCollection
         * @Return: org.apache.shiro.authz.AuthorizationInfo
         **/
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            //1、獲取當前用戶名
            String  username = (String) getAvailablePrincipal(principalCollection);
    
            Role role = null;
    
            //2、通過當前用戶名從資料庫中獲取用戶資訊
            try {
                User user = userLoginServiceImpl.findByName(username);
                //3、獲取角色資訊
                role=roleServiceImpl.findById(user.getRole());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //4、為當前用戶設定角色和權限
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //用來存放角色碼的集合
            Set<String> r = new HashSet<String>();
            if (role != null) {
                r.add(role.getRolename());
                //5、把用戶角色碼交給shiro
                info.setRoles(r);
            }
    
            return info;
        }
    
        /**
         * @Description: 身份驗證,login時呼叫
         * @Param0: authenticationToken
         * @Return: org.apache.shiro.authc.AuthenticationInfo
         **/
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            //用戶名
            String username = (String) token.getPrincipal();
            //密碼
            String password = new String((char[])token.getCredentials());
    
            //獲取用戶資訊
            User user=null;
            try {
               user = userLoginServiceImpl.findByName(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //
            if (user == null) {
                //沒有該用戶名
                throw new UnknownAccountException();
            } else if (!password.equals(user.getPassword())) {
                //密碼錯誤
                throw new IncorrectCredentialsException();
            }
    
           /* ByteSource salt = ByteSource.Util.bytes(user.getSalt());//鹽值
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(),
                    user.getPassWord(),salt,getName());*/
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
    
            return authenticationInfo;
        }
    }
    
    
  • controller中身份驗證

    1. 封裝用戶名,密碼
    2. 呼叫Subject.login方法進行登錄,不匹配會出現 AuthenticationException 例外
    3. 自定義的realm類,重寫doGetAuthenticationInfo() 方法
  • controller中獲取登錄資訊

    1. SecurityUtils.getSubject()獲取subject
    2. subject.getPrincipal()
  • controller中獲取授權資訊

    1. subject.hasRole("xxx"),角色碼集合中的值
    2. 或者subject.isPermitted()
  • controller代碼實體:

    @RequestMapping(value = "https://www.cnblogs.com/login", method = {RequestMethod.POST})
    public String login(User user,Model model) throws Exception{
    
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),
                                                                user.getPassword());
        //應用代碼直接互動的物件是 Subject,Subject 代表了當前“用戶”
        Subject subject = SecurityUtils.getSubject();
    
        subject.login(token);
        //如果獲取不到用戶名就是登錄失敗,但登錄失敗的話,會直接拋出例外
        if (subject.hasRole("admin")) {
            return "redirect:/admin/showStudent";
        } else if (subject.hasRole("teacher")) {
            return "redirect:/teacher/showCourse";
        } else if (subject.hasRole("student")) {
            return "redirect:/student/showCourse";
        }
    
        return "redirect:/login";
    }
    
     //獲取登錄者資訊
    
        public User getUserInfo(){
            Subject subject = SecurityUtils.getSubject();
            String username= (String) subject.getPrincipal();
            User user=null;
            try {
                user= userLoginServiceImpl.findByName(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return user;
        }
    

日期轉換

pojo 類的 日期欄位 上,添加注解 @DateTimeFormat(pattern="yyyy/MM/dd") 根據自己情況,寫具體的日期格式;

上面的僅僅對一個 po 類有效,如果你有很多 pojo 類,都有日期,則直接寫一個日期轉換類,然后注冊到 springMvc 的組態檔里面,一勞永逸 ;

轉換類如下:

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 完成日期系結,全域的 ,替換掉  @DateTimeFormat(pattern = "yyyy/MM/dd")
 */
public class DateConverter implements Converter<String, Date> {
    /**
     * 日期轉換類
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String source) {
        try {
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        轉換失敗,就回傳 null  ;
        return null;
    }

}



注冊到組態檔中

<!--配置 自定義 引數系結(日期轉換)-->
    <bean  id="conversionService">
        <!--寫上自定義的轉換器-->
        <property name="converters">
            <list>
                <!--日期 轉換 -->
                <bean />
            </list>
        </property>
    </bean>

 <!--添加到 MVC 注解里面-->
<mvc:annotation-driven validator="validator" conversion-service="conversionService">

在使用 @Request 進行 JSON 資料引數系結的時候,對日期,需要另作操作;

否則就會報 400 bad request,請求也不會進后臺方法;

pojo 類的 日期欄位的get方法 上 添加 @JsonFormat(pattern="yyyy/MM/dd")

json亂碼

解決輸出JSON亂碼的問題

我們發現即使,我們在 web.xml 中配置了解決亂碼的攔截器,但是輸出JSON 到前臺的時候,JSON 中的中文還會亂碼 ;

這與我們配置的過濾器無關了,我 猜測 是在JSON轉換器內部,它默認了ISO-8859編碼,導致過濾器在拿到資料的時候,就已經是亂碼的資料了,它再使用UTF8編碼,最終也還是亂碼,除非它能智能的先ISO-8859解碼,再UTF8編碼,

為了解決這個問題,我們需要在springMvc.xml 中的 MVC 注解標簽中配置JSON轉換器,制定編碼為UTF8

<mvc:annotation-driven validator="validator" conversion-service="conversionService">
        <mvc:message-converters>
            <!-- 處理請求回傳json字串的中文亂碼問題 -->
            <bean >
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean />
        </mvc:message-converters>
    </mvc:annotation-driven>

注意哦,對日期進行系結的時候,JSON是在 欄位 get 方法上添加注解,表單是在 欄位 上添加注解!

上面的方法,都是前臺傳來 JSON ,然后轉成物件,指定 JSON 中的日期格式,以便正確的轉換日期物件;

如果反過來呢,物件轉成JSON,直接轉換的話 date 型別,就會被轉成 183138913131 這樣long 型別的一串數字,我們也可以指定轉成 JSON 串中 date 的格式:@JSONField(format = "yyyy-MM-dd")

  /**
     * JSON -> 物件,指定JSON 中日期格式,以便轉成物件
     */
    @DateTimeFormat(pattern = "yyyy/MM/dd")
    /**
     * 物件 -》 JSON 指定轉換以后的字串中日期物件的格式
     */
    @JSONField(format = "yyyy-MM-dd")
    private Date newsTime;

重置按鈕

需要指定為:reset ,默認submit

1584875121755

路徑跳轉問題:

controller跳轉

  • redirect:/xxx 跳轉到根路徑/**,(如果根路徑為/,則跳轉之后路徑為localhost/xxx
  • redirect:xxx 跳轉到同級路徑請求、即:在同一個controller里面跳轉(假設:不同的controller類有不同的請求映射注解@RequestMapping("/abc")....,跳轉之后路徑localhost/abc/xxx,不能實作controller之間的跳轉,因為controller類請求路徑(abc)不同
  • forward:同redirect

頁面跳轉

先配置視圖決議器:

<bean >
     <!--拼接視圖地址的前綴和后綴 -->
     <property name="prefix" value="https://www.cnblogs.com/WEB-INF/jsp/" />
     <property name="suffix" value="https://www.cnblogs.com/jklixin/p/.jsp" />
</bean>

return "(想要跳轉jsp路徑)xxx"

跳轉路徑:localhost/xxx

如:return "student/showCourse"; 前面沒有斜杠,視圖決議器里面已經加了

實際jsp所在 D:\ideaFiles\Examination\src\main\webapp\WEB-INF\jsp\student\showCourse.jsp

PageHelper使用

  1. 依賴

     <!-- MyBatis分頁插件 -->
     <dependency>
         <groupId>com.github.pagehelper</groupId>
         <artifactId>pagehelper</artifactId>
         <version>5.1.2</version>
     </dependency>
    
  2. 配置(5.x.x版本)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- config params as the following -->
                <property name="helperDialect" value="https://www.cnblogs.com/jklixin/p/mysql"/>
            </plugin>
        </plugins>
    </configuration>
    
  3. 實作,sql陳述句不用更改

    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
    		
    		// 1.呼叫PageHelper的靜態方法開啟分頁功能
    		// 這里充分體現了PageHelper的“非侵入式”設計:原本要做的查詢不必有任何修改
    		PageHelper.startPage(pageNum, pageSize);
    		
    		// 2.執行查詢
    		List<Admin> list = adminMapper.selectAdminByKeyword(keyword);
    		// 3.封裝到PageInfo物件中
    		PageInfo<Admin> adminPageInfo = new PageInfo<>(list);
    		return adminPageInfo;
    }
    

    ? controller條用service回傳pageinfo物件,存盤到model中

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/194755.html

標籤:Java

上一篇:可能是把 Java 介面講得最通俗的一篇文章

下一篇:centos7-linux下docker安裝Gitlab中文社區版

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more