JavaEE学习笔记 2024-1-18 --模块化Controller层、AJAX与JSON

发布时间:2024年01月18日

? 上一篇

个人整理非商业用途,欢迎探讨与指正!!



11.模块化Controller层

将对应模块的Servlet写入到一个指定的模块中,模块化编程

使用switch方式

package com.qf.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import sun.rmi.transport.proxy.HttpReceiveSocket;

/**
 * Servlet implementation class EmpServlet
 */
@WebServlet("/emp/*")
public class EmpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		请求的url
		String requestURL = request.getRequestURL().toString();
		System.out.println(requestURL);
		String[] split = requestURL.split("/");
//		System.out.println(Arrays.toString(split));
//		获取到需要执行得Servlet方法
		String method = split[split.length-1];
		switch (method) {
		case "insert":
			insert(request,response);
			break;
		case "delete":
			delete(request,response);
			break;
		default:
			return;
		}
	}

	public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("我是删除方法");
	}

	public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("我是添加方法");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

使用反射

@WebServlet("/dept/*")
public class DeptServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public DeptServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURL().toString();
		String[] split = requestURL.split("/");
		String method = split[split.length-1];
		
//		当前类对象
		Class<? extends DeptServlet> clazz = this.getClass();
//		获取当前对象的方法
		try {
//			获取需要执行的方法
			Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);
//			启动暴力反射
			declaredMethod.setAccessible(true);
//			方法的反向执行
			declaredMethod.invoke(this, request, response);
		} catch (Exception e) {
			System.out.println("没有对应的方法");
		}
	}
	
	public void insert(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException  {
		System.out.println("添加方法");
	}

	private void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException  {
		System.out.println("删除方法");
	}
	
	private void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException  {
		System.out.println("修改方法");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

12.AJAX

异步的JS与XML技术,可以实现JS和服务器之间的异步交互
异步交互:在不刷新网页的前提下,局部代码与服务器进行交互
AJAX不是新技术,也不是编程语言,就是一个使用JS和后端进行交互的技术

AJAX的优点:用户体验非常好;缺点:开发改错困难,不可回退

12.1使用场景

场景1:AJAX验证用户名是否重复

package com.qf.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CheckNameServlet
 */
@WebServlet("/check")
public class CheckNameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public CheckNameServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
//		模拟从数据库中获取数据
		ArrayList<String> list = new ArrayList<>();
		list.add("张三");
		list.add("李四");
		list.add("王五");
		list.add("tom");
		list.add("jack");
		list.add("rose");
		
//		何如判断name在list中
		boolean contains = list.contains(name);
//		false是可用 true是不可用
//		System.out.println(contains);
//		0不可用 1可用
		response.getWriter().print(contains?0:1);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="text" id="username">
		<span id="msg"></span>
		<script>
			window.onload = function(){
				let username = document.querySelector("#username");
				let msg = document.querySelector("#msg");
				
				username.onblur = function(){
					// 发送ajax请求
					// 1.创建AJAX对象
					let xhr = new XMLHttpRequest();
					
					// 2.封装AJAX的请求数据(形式为:xxxxServlet?xxxx=xxxx&xxx=xxx)
					xhr.open("GET","check?name="+username.value);
					
					// 3.发送请求
					xhr.send();
					
					// 4.AJAX的请求状态判断
					// readyState
						// 0:ajax创建但未初始化
						// 1:ajax创建完成但未发送请求
						// 2:ajax发送请求到服务器端
						// 3:ajax请求正在被处理
						// 4:ajax请求处理完成,可以使用ajax获取服务器响应的数据
					xhr.onreadystatechange = function(){
						if(xhr.status == 200 && xhr.readyState == 4){
							// 5.获取响应的数据
							let result = xhr.responseText;
							if(result == 0){
								msg.innerHTML = '用户名已存在';
								msg.style.color = 'red';
							}else{
								msg.innerHTML = '√';
								msg.style.color = 'green';
							}
						}
					}
				}
			}
		</script>
	</body>
</html>

13.JSON

配合AJAX进行分离式开发中,数据的交互形式之一
JSON可以实现不同系统,不同语言之间的数据交互
JSON是一种数据格式,类似于JS中的{}对象

语法:
??{
???“key”:“value”,
???“key”:“value”,
???…
??}

数据体量小,可以做为数据传入的载体

13.1如何使用后端发送JSON数据

使用第三方工具(jar、依赖)
Gson
?谷歌发布
Jackson
?Springn内置的
FastJson
?阿里发布的

package com.qf.test;

import java.util.ArrayList;
import java.util.HashMap;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

public class TestJSON {

	@Test
	public void test01() {
		System.out.println("helloworld");
	}
	
	@Test
	public void test02() {
		Gson gson = new Gson();
		
		String json = gson.toJson("helloworld");
		System.out.println(json);
	}
	
	@Test
	public void test03() {
		Gson gson = new Gson();
		
		String json = gson.toJson(new Dog(1,"李四"));
		System.out.println(json);
	}
	
	@Test
	public void test04() {
		ArrayList<Dog> dogs = new ArrayList<>();
		dogs.add(new Dog(1,"1"));
		dogs.add(new Dog(2,"2"));
		dogs.add(new Dog(3,"3"));
		dogs.add(new Dog(4,"4"));
		
		String json = new Gson().toJson(dogs);
		System.out.println(json);
	}
	
	@Test
	public void test05() {
		ArrayList<Dog> dogs = new ArrayList<>();
		dogs.add(new Dog(1,"1"));
		dogs.add(new Dog(2,"2"));
		dogs.add(new Dog(3,"3"));
		dogs.add(new Dog(4,"4"));
		
		int currPage = 10;
		
		HashMap<String,Object> map = new HashMap<>();
		map.put("dogs", dogs);
		map.put("page", currPage);
		
		String json = new Gson().toJson(map);
		System.out.println(json);
	}
	
	@Test
	public void test06() throws Exception {
		Dog dog = new Dog(1,"1");
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(dog);
		System.out.println(json);
	}
}
文章来源:https://blog.csdn.net/CHiN_951/article/details/135683550
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。