日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

Java Web之三大利器

發(fā)布時(shí)間:2023/12/20 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java Web之三大利器 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Java Web 三大利器主要有:

  • 1.過濾器。
  • 2.攔截器。
  • 3.監(jiān)聽器。

一、過濾器

1.什么是過濾器?

過濾器是JavaWeb的三大組件之一。

過濾器它是 JavaEE 的規(guī)范,可以在瀏覽器以及目標(biāo)資源之間起到一個(gè)過濾的作用,它的作用是:攔截請(qǐng)求,過濾響應(yīng)。

Web中的過濾器:當(dāng)訪問服務(wù)器的資源時(shí),過濾器可以將請(qǐng)求攔截下來,完成一些特殊的功能。

2.過濾器的應(yīng)用場(chǎng)景有哪些?

  • (1)登錄驗(yàn)證。
  • (2)權(quán)限檢查。
  • (3)事務(wù)管理。
  • (4)統(tǒng)一編碼處理。
  • (5)敏感字符處理。

3.過濾器的生命周期是什么?

  • (1)服務(wù)器啟動(dòng),首先執(zhí)行構(gòu)造方法和init方法(這兩個(gè)方法只執(zhí)行一次)
  • (2)當(dāng)有匹配過濾條件的請(qǐng)求時(shí)執(zhí)行doFilter方法(該方法可以執(zhí)行多次)
  • (3)服務(wù)器正常關(guān)閉的時(shí)候,或者該Filter類重新加載的時(shí)候會(huì)執(zhí)行destroy方法(該方法只執(zhí)行一次)

4.過濾器權(quán)限校驗(yàn)代碼該怎么寫?

@Component public class FilterPerm implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("init......");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;System.out.println("FilterPerm," + request.getRequestURI());RespVO vo = new RespVO();PrintWriter out = null;response.setCharacterEncoding("UTF-8");response.setContentType("application/json; charset=utf-8");try {String token = request.getParameter("token") == null ? null : request.getParameter("token");if (token == null || token == "") {vo.setCode(400);vo.setMsg("未攜帶Token");}if (token != null && "abcdef".equals(token)) {filterChain.doFilter(servletRequest, servletResponse);System.out.println("通過");}if (token != null && !"abcdef".equals(token)) {vo.setCode(403);vo.setMsg("訪問未授權(quán)");}} catch (Exception e) {e.printStackTrace();vo.setCode(500);vo.setMsg("Server Error");}out = response.getWriter();String json = JSONUtil.toJsonPrettyStr(vo);// 返回json信息給前端out.append(json);out.flush();}@Overridepublic void destroy() {System.out.println("destroy......");} }

二、攔截器

1.什么是攔截器?

Java里的攔截器是動(dòng)態(tài)攔截Action調(diào)用的對(duì)象,它提供了一種機(jī)制可以使開發(fā)者在一個(gè)Action執(zhí)行的前后執(zhí)行一段代碼,也可以在一個(gè)Action執(zhí)行前阻止其執(zhí)行,同時(shí)也提供了一種可以提取Action中可重用部分代碼的方式。

2.攔截器的應(yīng)用場(chǎng)景有哪些?

  • (1)權(quán)限控制。
  • (2)日志打印。
  • (3)參數(shù)校驗(yàn)。

3.攔截器如何實(shí)現(xiàn)對(duì)權(quán)限的控制?

核心代碼:

AuthInterceptor.java

@Component public class AuthInterceptor implements HandlerInterceptor {/*** 忽略攔截的url*/private String urls[] = {"/xxnet/token"};/*** 進(jìn)入controller層之前攔截請(qǐng)求** @param httpServletRequest* @param httpServletResponse* @param o* @return* @throws Exception*/@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {String url = httpServletRequest.getRequestURI();String username = httpServletRequest.getHeader("username");String password = httpServletRequest.getHeader("password");// 遍歷需要忽略攔截的路徑for (String item : this.urls) {if (item.equals(url)) {return true;}}if (username == null || password == null) {httpServletResponse.setCharacterEncoding("UTF-8");httpServletResponse.setContentType("application/json; charset=utf-8");PrintWriter out = null;ResultBody res = new ResultBody(ResultCode.TOKEN_ERROR.getCode(), ResultCode.TOKEN_ERROR.getMsg());res.setMsg("用戶名或密碼不能為空");res.setCode("400");String json = JSONUtil.toJsonPrettyStr(res);httpServletResponse.setContentType("application/json");out = httpServletResponse.getWriter();// 返回json信息給前端out.append(json);out.flush();return false;}if (username != null && password != null) {httpServletResponse.setCharacterEncoding("UTF-8");httpServletResponse.setContentType("application/json; charset=utf-8");PrintWriter out = null;try {//獲取用戶名和密碼Props props = new Props("auth.properties");String userName = props.get(CommonConstant.USERNAME).toString();String pwd = props.get(CommonConstant.USERNAME).toString();if (userName.equals(userName) && pwd.equals(password)) {return true;} else if (!userName.equals(userName) || !pwd.equals(password)) {ResultBody res = new ResultBody();res.setMsg("用戶名或密碼錯(cuò)誤");res.setCode("500");String json = JSONUtil.toJsonPrettyStr(res);httpServletResponse.setContentType("application/json");out = httpServletResponse.getWriter();// 返回json信息給前端out.append(json);out.flush();return false;} else {ResultBody res = new ResultBody();res.setMsg("未登錄,暫無權(quán)限");res.setCode("500");String json = JSONUtil.toJsonPrettyStr(res);httpServletResponse.setContentType("application/json");out = httpServletResponse.getWriter();// 返回json信息給前端out.append(json);out.flush();return false;}} catch (Exception e) {e.printStackTrace();httpServletResponse.sendError(500);return false;}}return true;}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {// System.out.println("視圖渲染之后的操作");}}

WebConfig.java

@Configuration public class WebConfig implements WebMvcConfigurer {@Autowiredprivate AuthInterceptor authInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(authInterceptor).addPathPatterns("/**")//攔截所有的路徑.excludePathPatterns( //添加不攔截路徑"/favicon.ico","/swagger-resources/**", //js靜態(tài)資源"/webjars/**", //css靜態(tài)資源"/api-doc/**","/doc.html","/v2/api-docs/**");} }

三、監(jiān)聽器

1.什么是監(jiān)聽器?

監(jiān)聽器,字面上的理解就是監(jiān)聽觀察某個(gè)事件(程序)的發(fā)生情況,當(dāng)被監(jiān)聽的事件真的發(fā)生了的時(shí)候,事件發(fā)生者(事件源) 就會(huì)給注冊(cè)該事件的監(jiān)聽者(監(jiān)聽器)發(fā)送消息,告訴監(jiān)聽者某些信息,同時(shí)監(jiān)聽者也可以獲得一份事件對(duì)象,根據(jù)這個(gè)對(duì)象可以獲得相關(guān)屬性和執(zhí)行相關(guān)操作。

2.監(jiān)聽器的應(yīng)用場(chǎng)景有哪些?

  • (1)網(wǎng)站初始化。
  • (2)統(tǒng)計(jì)在線人數(shù)。
  • (3)統(tǒng)計(jì)網(wǎng)站訪問量。
  • (4)實(shí)現(xiàn)訪問監(jiān)控。

3.以統(tǒng)計(jì)在線人數(shù),對(duì)應(yīng)的監(jiān)聽器代碼該如何編寫?

UserHttpSessionListener.java

/*** 使用HttpSessionListener統(tǒng)計(jì)在線用戶數(shù)的監(jiān)聽器*/ @Component public class UserHttpSessionListener implements HttpSessionListener {private static final Logger logger = LoggerFactory.getLogger(UserHttpSessionListener.class);/*** 記錄在線的用戶數(shù)量*/public Integer count = 0;@Overridepublic synchronized void sessionCreated(HttpSessionEvent httpSessionEvent) {logger.info("新用戶上線了");count++;httpSessionEvent.getSession().getServletContext().setAttribute("count", count);}@Overridepublic synchronized void sessionDestroyed(HttpSessionEvent httpSessionEvent) {logger.info("用戶下線了");count--;httpSessionEvent.getSession().getServletContext().setAttribute("count", count);} }

TestController.java

@RestController @RequestMapping("/listener") public class TestController {GetMapping("/total") public String getTotalUser(HttpServletRequest request, HttpServletResponse response) {Cookie cookie;try {// 把sessionId記錄在瀏覽器中cookie = new Cookie("JSESSIONID", URLEncoder.encode(request.getSession().getId(), "utf-8"));cookie.setPath("/");//設(shè)置cookie有效期為2天,設(shè)置長(zhǎng)一點(diǎn)cookie.setMaxAge( 48*60 * 60);response.addCookie(cookie);} catch (UnsupportedEncodingException e) {e.printStackTrace();}Integer count = (Integer) request.getSession().getServletContext().getAttribute("count");return "當(dāng)前在線人數(shù):" + count; }}

總結(jié)

以上是生活随笔為你收集整理的Java Web之三大利器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。