OA后端項目的總結
項目架構:springboot+jpa
第一、全局異常的處理
1.首先理解什么是全局異常:第發送http的請求的是否方法出現異常所以我們要進行全局異常處理
2.如何處理全局異常
第一步:添加注解在類上面 @ControllerAdvice
第二步:繼承ResponseEntityExceptionHandler
第三步:重寫ResopnseEntity<Object> handleExceptionInternal(Exception ex,Object body,HttpHeaders headers,WebRequest request){
return new ResponseEntity(“worng”,HttpStatus.NOT_EXTENDED)
}
第四步:@ExceptionHandler(value=Exception.class)
@ResponseBody
判斷session
第二、日志的處理使用注解
1.在這個項目中我為什么使用注解對日志:aop配置日志代理,用于對日志的基本信息進行記錄
2.怎么使用
第一步:在類上面添加注解
@Configuration
@Aspect
第二步:攔截注解 自定義方法
@Around(“@annotation(注解所在路徑)”)
public ResultData check(ProceedingJoinPoint point){
ResultData resultData = null;
MethodSignature signature = signature.getMethod().getAnnotations();
//獲取該方法上面的注解
Annotation[] annotation = signature.getMethod().getAnnotations();
for(int i = 0 ; I < annotation.length;i++){
if(annotation[i] instanceof 自定義注解的信息){
獲取直接的信息
}
}
try{
resultData = (ResultData)point.proceed();
}catch(Exception e) {
//處理方法的異常的信息
}
//獲取http請求過來的參數,就是為了獲取到session對象
for(Object obj :point.getArgs){
if(!(arg instanceof HttpServletRequest))
}
}
如何自定義注解
在類上面添加@Target(ElementType.METHOD)\
@Retention(RetentionPolicy.RUNTIME)
注解的類 public @interface 注解的名字
定義注解的 方法 String success() default “”
第三、攔截器的使用
HandlerInterceptor
主要作用是 在方法前面執行在方法后面執行 在頁面渲染執行
在方法之前執行:這個方法的作用主要是對象session的攔截
怎么將連接器注冊到spring容器中
第一種方式通過:@Component
第二種方式通過
第一步:繼承WebMvcConfigurerAdapter
第二步:重寫方法
addInterceptors(InterceptorRegister register){
registery.addInterceptor(創建攔截器對象).addPathPatterns(“/**”)
super.addInterceptors(register )
}
第四、定時任務的的使用
什么是定時任務,在定義方法指定時間對業務進行處理我們叫定時任務
怎么做:
第一步:定義一個類在類上面添加注解@Component
第二步: 在類里面添加方法 在方法上面添加注解 @Scheduled
使用cron表達式:下面我介紹一下cron表達式
第一位是表示秒 0-59
第二位是表示分 0-59
第三位是表示時 0-23
第四位是表示天 1-31
第五位是表示月份 1-12
第六位是表示星期 1-7
第七位是表示年份
第五、cache的使用
第一步:定義一個ehcache.xml
<?xml version=”1.0” encoding=”utf-8”>
<ehcache>
<defaultCache
maxEntriesLocalHeap=”100”
eternal=”false”
timeToIdleSeconds = “120”
maxEntriesLocalDisk=”100000”
diskExpiryThreadIntervalSeconds=”120”
memoryStoreEvictionPolicy=”LRU”
>
<persistence strategy=”localTempSwap”>
</defalutCache>
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
</ehcache>
第二步:導入依賴
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency>
第三步: @Configuration
@PropertySource(value={“classpath:application.properties”},encoding=”utf-8”)
定義一個類 在類里面添加一個方法
@Bean
Public CacheManger getCacheManger(){
ClassPathResource classPathResource = new ClassPathResource(“ehcache,xml”)
Try{
cacheManger = CacheManger.create(classPathResource.getInputStream)
}catch(Exception e){
}
return cacheManger
}
第四步: //封裝cache方法
// 1. 創建緩存管理器
CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
// 2. 獲取緩存對象
Cache cache = cacheManager.getCache("HelloWorldCache");
// 3. 創建元素
Element element = new Element("key1", "value1");
// 4. 將元素添加到緩存
cache.put(element);
// 5. 獲取緩存
Element value = cache.get("key1");
System.out.println(value);
System.out.println(value.getObjectValue());
// 6. 刪除元素
cache.remove("key1");
Dog dog = new Dog(1L, "taidi", (short)2);
Element element2 = new Element("taidi", dog);
cache.put(element2);
Element value2 = cache.get("taidi");
Dog dog2 = (Dog) value2.getObjectValue();
System.out.println(dog2);
System.out.println(cache.getSize());
// 7. 刷新緩存
cache.flush();
// 8. 關閉緩存管理器
cacheManager.shutdown();
第六、springboot跨域的處理
第一步:在main方法所在的類中寄存WebMvcConfigurerAdapte
第二步:重寫 addCorsMappings(CorsRegistry register){
register.addMappper(“/**”).allowedHeaders(“*”).addowedMethod(“*”).allowedOrigins(
“*”)
}
第七.加密與解密
1.為什么出現加密的過程: 就是因為防止信息被一些手段進行破解
2.如何自定義對信息進行加密處理
2.1借助于sun包
2.2 static{
Try{
KeyGenerator generator = KeyGenerator.getInstance(“DES”)
Generator.init(new SecureRandom(Key_STR.getBytes()))
Key = generator.geneartekey();
generator =null
}catch(Exceptipon o){
Throw new RuntimeException()
}
}
//加密的方法
public static String getEncryptString(String str){
BASE64Encodeer base64Encoder = new BASE64Encoder();
try{
byte[] strbytes = str.getBytes(“UTF-8”)
Cipjer cipher = Cipher.getInstance(“DES”)
cipjer.init(Cipher.ENCRYPT_MODE,key)
byte[] encryptStrBytes =cipher.doFinal()
return base64Encoder.encode(encryptStrBytes)
}catch(Exception e){
Throw new RuntimeException();
}
}
//解密的方法
public static String getDecryptString(String str){
BASE64Decoder base64Decoder = new BASE64Decoder();
Try{
byte[] strBytes = base64Decoder.decodeBuffer(str)
Cipher cipher = Cipher.getInstance(“DES”)
cipher.init(Cipher.DECRYPT_MODE,key)
byte[] decryptStrBytes = cipher.doFinal(strBytes)
return new String(decryptStrBytes,”UTF-8”)
}catch(Exception e){
}
}
第八、怎么解析xml
第一步:根據文件名字找到文件所在文件的類路徑
private String getFile(String fileName){
String path = null;
try{
path = this.getClass().getClassLoader().getResource(fileName).getPath();
logger.info("parse success");
}catch (Exception e){
logger.error("parse error");
}
return path;
}
第二步:解析文件方法指定的容器內
public static void parse(File file,List<Bean> contaier)throws Exception{
if(file.isDirectory()){
SAXReader reader = new SAXReader();
File[] listFiles =file.listFiles();
for(int i = 0;i < listFiles.length;i++){
if(listFiles[i].getName().endsWith(".xml")) {
Document document = reader.read(listFiles[i]);
parseXmlDatas(document.getRootElement().elements(), contaier, "user-permission-grade");
}else{
continue;
}
}
}
}
詳細解析
首先判斷該文件傳入過來是否是文件夾,如果是文件夾,建立解析器,通過文件夾獲取到下面的文件,然后遍歷文件(首先判斷該文件的后綴名是否已.xml),如果是已.xml結束,解析文件里面的內容 通過文檔對象拉到文檔對象(其實文檔對象就是xml里面的內容),然后解析文件里面的內容
第三步:解析文件里面的內容
public static void parseXmlDatas(List<Element> elementList,List container,String firstElements){
for(Element dataElement: elementList){
if(dataElement.getName().equals(firstElements)){
List<Element> dataList = dataElement.elements();
parseXmlData(dataElement.elements(),container);
}
}
}
詳細解析
拿到文件對象,第一步遍歷標簽,判斷該根元素是否已指定的元素開始,如果是解析根元素下面的子元素,然后解析數據
public static void parseXmlData(List<Element> elementsList,List<Bean> container){
Bean bean = new Bean();
for(Element data:elementsList){
String name = data.getName();
if("name".equalsIgnoreCase(name)){
bean.setName((String)data.getData());
}else if("value".equalsIgnoreCase(name)){
System.out.println(name);
bean.setValue(Integer.parseInt((String)data.getData()));
} //獲取屬性 //data.attgit ributeValue("id")
}
container.add(bean);
}
詳細解析
遍歷元素,獲取元素所在文件中的標簽的名字,然后對標簽里面的內容進行封裝成類對象。
第九、如何根據數據庫的信息自動生成實體類
第十,如何根據實體類自動生成數據庫的類信息
第十一、JPA詳解
1. 在類上面
@Entity:表示該類是一個實體類對象
@Table 指定生成數據庫的表的名字
?
注解里面的屬性指定
name:指定生成數據庫表的名字
2. 在屬性上面
@Id: 表示該屬性是主鍵
@GeneraterValue(strategy = GenerationType.IDENTITY)
兩個配合使用,表示該主鍵是自增長
@Column(name=””)
表示指定生成數據中每個字段的名字
一對一
這個會在指定類中生成一個外鍵
@OneToOne(fetch = Fetch.lazy,cascade = CascadeType.All)
@JoinColumn(name=“”)
name=””表示指定的名字
一對多
這個會在多的一方生成外鍵
@OneToMany(fetch = Fetch.lazy,cascade = CascadeType.All)
@ JoinColumn(name=“”)
@Fetch(FetchMode.SUBSELECT)=
多對多的
@ManyToMany(fetch = Fetch.lazy,cascade = CascadeType.All)
@JoinTable(name=“”,joinColums={@JoinColumn(name=””)}
,inverseJoinColumns ={@JoinColumn(name=””)}
)
該類所對應的菜單類的信息
List<Menu> menu ;
3. 在方法上面
@JsonBackReference