JAVA小白进阶day22

这篇博客详细介绍了JAVA Web开发的学习过程,包括添加登录和注册页面,定义业务逻辑控制器,实现Servlet的反射机制,读取配置文件,处理POST请求,以及如何展示和更新数据。内容涵盖LoginServlet和RegServlet的实现,ServletContext的初始化,反射在创建Servlet中的应用,HttpRequest的post请求解析,以及doGet和doPost方法的使用。
摘要由CSDN通过智能技术生成

第十个任务:登录
1.添加登录页面 ,成功和失败的页面

public class WebServer {
	ServerSocket server;

	public WebServer() {
		try {
			server = new ServerSocket(8888);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void start() {
		while (true) {
			Socket socket;
			try {
				while (true) {
					System.out.println("等待客户端的请求");
					socket = server.accept();
					new Thread(new ClientHandler(socket)).start();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class ClientHandler implements Runnable {
		Socket socket;
		public ClientHandler() {
		}
		public ClientHandler(Socket socket) {
			this.socket = socket;
		}
		@Override
		public void run() {
			// \r\n ASCⅡ 13 10
			System.out.println("接收客户端请求");
			// 获取请求状态行
			try {
				InputStream in = socket.getInputStream();
				OutputStream out = socket.getOutputStream();
				HttpRequest request = new HttpRequest(in);
				HttpResponse response = new HttpResponse(out);
				// 测试获取请求头信息
//				System.out.println(request.getHeads());
				if ("/myweb/register".equals(request.getRequestUrl())) {
					String username = request.getParameter("name");
					String pw = request.getParameter("pw");
					System.out.println(username + "," + pw);
					// 保存数据,使用数据文件
					PrintWriter printwriter = new PrintWriter(new FileOutputStream("user.txt", true));
					printwriter.println(username + "&" + pw);
					printwriter.flush();
					printwriter.close();	
					fileResponse("/myweb/registerOK.html", response);
				} else {
					fileResponse(request.getUrl(), response);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
	public void fileResponse(String uri, HttpResponse response) {
		File file = new File("webapps" + uri);
		// 设置文档长度
		response.setContentLength((int) file.length());
		// 设置文档类型
		int index = file.getName().indexOf(".");
		String name = file.getName().substring(index + 1);
		response.setContentType(HttpContext.getMimeType(name));
		// 响应页面
		response.setEntity(file);
		// 响应的文档内容
		response.flush();
	}
	public static void main(String[] args) {
		new WebServer().start();
	}
}

public class HttpContext {
	public static final int CR = 13;
	public static final int LF = 10;
	private static Map<String, String> map;

	static {
		// HttpContext加载的时候开始初始化
		init();
	}
	private static void initMimeType() {
		map = new HashMap<String, String>();
		/*
		 * 解析conf/web.xml文档 将根标签中所有的<mime-mapping>标签读取出来 将其中的子标签<extension>中的内容作为key
		 * 将其中的子标签<mime-type>中的内容作为value 存入到mimeTypeMapping中即可
		 */
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(new File("config/web.xml"));
			Element rootElement = document.getRootElement();
			Iterator<Element> it1 = rootElement.elementIterator();
			while (it1.hasNext()) {
				Element element = it1.next();
				if (element.getName().equals("mime-mapping")) {
					Iterator<Element> it2 = element.elementIterator();
					String key = "";
					String value = "";
					while (it2.hasNext()) {
						Element element2 = it2.next();
						if (element2.getName().equals("extension")) {
							key = element2.getText();
						}
						if (element2.getName().equals("mime-type")) {
							value = element2.getText();
						}
					}
					map.put(key, value);
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String getMimeType(String key) {
		return map.get(key);
	}
	public static void init() {
		initMimeType();
	}
}

public class HttpRequest {
	public String method;
	public String url;
	public String protocol;
	private Map<String ,String> header = new HashMap<>();
	private String requestUrl;
	private Map<String,String> params = new HashMap<String,String>();
	public HttpRequest() {}
	public HttpRequest(InputStream in) {
		try {
			parseRequestLine(in);
			parseRequestHeaders(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//解析url,封装请求参数
	public void parseUrl() {
		//判断是否有?
		int index = this.url.indexOf("?");
		if(index == -1) {
			this.requestUrl = url;
		}else {
			//1、?前 this.request = url
			this.requestUrl = url.substring(0,index);
			//2、?后 map
			String parameters = url.substring(index+1);
			String[] values = parameters.split("&");
			for(String str : values) {
				//name = admin   pw=123456
				String[] data = str.split("=");
				if(data.length == 2) {
					params.put(data[0], data[1]);
				}else {
					params.put(data[0],"");
				}
			}
		}
	}
	public String getMethod() {
		return method;
	}
	public String getUrl() {
		return url;
	}
	public String getProtocol() {
		return protocol;
	}
	public void parseRequestHeaders(InputStream in)  throws IOException {
		while(true) {
			String str = this.readLine(in);
			if("".equals(str)) {
				break;
			}
			String[] data = str.split(": ");
			header.put(data[0],data[1]);
		}
	}
	public void parseRequestLine(InputStream in) throws IOException {
		String[] data = this.readLine(in).split(" ");
		if(data.length == 3) {
			this.method = data[0];//获取请求方式get
			this.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值