java開發案例
⑴ java實現攔截HTTP請求的幾種方式
在Java的服務端開發當中,攔截器是很常見的業務場景,這里對Java開發當中幾種常見的攔截器的實現方式進行記錄和分析。案例說明基於Spring Boot環境。
一:實現javax.servlet.Filter介面(使用過濾器方式攔截請求)
import org.springframework.stereotype.Component;import javax.servlet.*;import java.io.IOException;import java.util.Date;@Componentpublic class TimeInterceptor implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("time filter init");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("time filter start");long start = new Date().getTime();filterChain.doFilter(servletRequest, servletResponse);System.out.println("time filter 耗時:"+(new Date().getTime()-start));System.out.println("time filter finish");}@Overridepublic void destroy() {System.out.println("time filter destroy");}}
如使用@Compent註解聲明不需要加入其它配置即可使得攔截器生效,但是默認攔截/*,會攔截所有請求。
二:使用@Bean注入自定義攔截器,依然上面的代碼,去掉@Compent註解,創建TimeWebConfig配置類:
import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.ArrayList;import java.util.List;@Configurationpublic class TimeWebConfig {@Beanpublic FilterRegistrationBean timeFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();TimeInterceptor interceptor = new TimeInterceptor();registrationBean.setFilter(interceptor);List<String> urls = new ArrayList<>();urls.add("/user/*");registrationBean.setUrlPatterns(urls);return registrationBean;}}
上面這兩種攔截請求的實現是基於JavaEE提供的Filter介面實現的,缺點在於,該攔截器實際上是一個過濾器,執行代碼的方法doFilter只提供了request,response等參數,當請求進入被過濾器攔截的時候,我們並不知道這個請求是由哪個控制器的哪個方法來執行的。
三:使用springMVC提供的攔截器,實現org.springframework.web.servlet.HandlerInterceptor介面:
創建自定義的攔截器:
import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Date;@Componentpublic class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {System.out.println("preHandler");System.out.println(((HandlerMethod) handler).getBean().getClass().getName());System.out.println(((HandlerMethod) handler).getMethod().getName());httpServletRequest.setAttribute("start", new Date().getTime());return true;}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandler");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗時:"+(new Date().getTime()-start));}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗時:"+(new Date().getTime()-start));System.out.println("ex is:"+e);}}
創建配置類:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter {@Autowiredprivate MyInterceptor interceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(interceptor).addPathPatterns("/user/*").excludePathPatterns("/blog/*");}}
此種方式的攔截器當中我們能夠獲取攔截的請求對應的類和方法的相關信息,缺點在於該handler對象無法獲取具體執行方法的參數信息。
四:利用Spring的切面(AOP)實現攔截器:
引入jar包:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
創建切片類:
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;import java.util.Date;@Aspect@Componentpublic class TimeAspect {@Around("execution(* com.qinker.controller.UserController.*(..))")public Object handlerControllerMethod(ProceedingJoinPoint point) throws Throwable {System.out.println("time aspect start");long start = new Date().getTime();Object[] args = point.getArgs();for (Object obj : args) {System.out.println("arg is:"+obj);}Object obj = point.proceed();//具體方法的返回值System.out.println("aspect 耗時:"+(new Date().getTime()-start));System.out.println("time aspect end");return obj;}}
aspectj基於AOP實現的攔截器功能十分強大,具體詳解請參考spring官網網站的文檔。
⑵ java經典編程案例有哪些
java編程的記事本:
import java.util.*;
public class JieChengExample
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n,sum;
Jiecheng jie=new Jiecheng();
System.out.print("輸入n的值:");//輸入有幾個階乘相加
n=input.nextInt();
sum=0;
for(int i=1;i<=n;i++)
{
sum=sum+jie.jiecheng(i);//這是n個階乘相加
}
System.out.println("1!+2!+3!+....+n!的和是:"+sum);
}
}
class Jiecheng
{
public int jiecheng(int temp)//算階乘的方法
{
int sum=1;
for(int i=1;i<=temp;i++)
{
sum=sum*i; //計算階乘
}
return sum;//將一個階乘返回
}
}
2.java賽馬游戲:
import java.util.Random;
public class Test {
public static void main(String[] args) {
Competition c = new Competition();
Thread T = new Thread(c);
T.start();
}
}
class Competition implements Runnable{
int red = 0;
int green = 0;
int Speed [] = new int [2];
Competition(){
}
public void run(){
Random r = new Random();
for(int a= 0;a<500;a++){
for(int j = 0;j<2;j++){
Speed[j] = r.nextInt(2);
red = red + Speed[j];
Speed[j] = r.nextInt(2);
green = green + Speed[j];
}
System.out.println("red的速度為"+red);
System.out.println("green的速度為"+green);
while(red >=500 || green>=500){
if(red >=500){
System.out.println("red先抵達終點線");
}
if(green >= 500){
System.out.println("green先抵達終點線");
}
if(green ==500 && red ==500 ){
System.out.println("兩個同時到達");
}
return;
}
}
/* if(red >green){
System.out.println("Redwin"+red);
}
if(red<green){
S...import java.util.Random;
public class Test {
public static void main(String[] args) {
Competition c = new Competition();
Thread T = new Thread(c);
T.start();
}
}
class Competition implements Runnable{
int red = 0;
int green = 0;
int Speed [] = new int [2];
Competition(){
}
public void run(){
Random r = new Random();
for(int a= 0;a<500;a++){
for(int j = 0;j<2;j++){
Speed[j] = r.nextInt(2);
red = red + Speed[j];
Speed[j] = r.nextInt(2);
green = green + Speed[j];
}
System.out.println("red的速度為"+red);
System.out.println("green的速度為"+green);
while(red >=500 || green>=500){
if(red >=500){
System.out.println("red先抵達終點線");
}
if(green >= 500){
System.out.println("green先抵達終點線");
}
if(green ==500 && red ==500 ){
System.out.println("兩個同時到達");
}
return;
}
}
/* if(red >green){
System.out.println("Redwin"+red);
}
if(red<green){
System.out.println("Greenwin"+green);
}
if(red == green){
System.out.println("equal");*/
JAVA的介紹:
Java是一種可以撰寫跨平台應用程序的面向對象的程序設計語言。Java技術具有卓越的通用性、高效性、平台移植性和安全性,廣泛應用於PC、數據中心、游戲控制台、科學超級計算機、行動電話和互聯網,同時擁有全球最大的開發者專業社群。
⑶ 昌平北大青鳥培訓班java項目開發案例分享
昌平北大青鳥作為中國高端職業教育第一品牌,擁有著頂尖的java教學團隊和高端的java課程,更有著豐富的java實訓項目,下面簡單介紹一下在昌平北大青鳥java培訓過程中所實訓洞賀的java項目有哪些?
1.開班前5天訓練營將完成「捕魚達人」游戲項銷敗目
2.開班2周內,貫穿著Java語言基礎及Java面向對象的學習,學員將完成專業版的俄羅斯方塊項目(Tetris)
3.開班一個半月內,貫穿JavaSE及資料庫的學習,將完成T-DMS數據採集系統項目
整個系統由DMS採集端、DMS伺服器端和NetCTOSS伺服器端三部分組成。DMS採集端的主要任務是採集、解析、匹配和保存並發送登錄數據。DMS採集端程序採集、解析獲得數據後,將處理好的數據發送到DMS伺服器端。DMS伺服器端接收到日誌數據,將日誌數據備份保存為文件數據,並存入資料庫。
4.在學習第3個月內,貫穿Web前端技術和Servlet/JSP的學習,將完成T-NetCTOSS項目
NetCTOSS系統的主要任務是提供對於數據的計費查詢和管理功能。
5.開班4個月內,學員將完成「航空訂票」真納斗派實項目