会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题

问题:request类空指针异常

image.png

代码:

package cn.ww.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 对服务器请求的类
 * */
public class Request {
	private final static String CRLF = "\r\n";
	private final static String BLANK =" ";
	private InputStream is;//输入流
	private String requestInfo;//存放请求信息
	private String method;//请求的方式
	private String url;//请求的url
	private Map<String,List<String>> parameterValues;//存放参数
	
	public Request() {
		method="";
		url="";
		requestInfo="";
		Map<String,List<String>> parameterValues =new HashMap<String,List<String>>();
	}

	public Request(InputStream is) throws IOException {
		this();
		this.is=is;
		byte [] b =new byte[20480];
		int len = is.read(b);
		requestInfo =new String(b,0,len);
		
		this.parseRequestInfo();
	}
	//分析请求信息,提取方法及url
	private void parseRequestInfo() {
		//第一行,从头到第一个换行位置
		String firstLine=requestInfo.substring(0, requestInfo.indexOf(CRLF)).trim();
		//获取请求方式,第一个 / 之前
		this.method=firstLine.substring(0, firstLine.indexOf("/")).trim();
		//获取url,/ 到HTTP/ 之间
		String urlString= firstLine.substring(firstLine.indexOf("/"),firstLine.indexOf("HTTP/")).trim();
		String paraString="";//存储请求参数
		//判断get或post方法获取url
		if("get".equalsIgnoreCase(this.method)){  
			if (urlString.contains("?")) {
				String [] urlArray=urlString.split("\\?");
				this.url=urlArray[0];
				paraString=urlArray[1];
			}else{
				this.url=urlString;
			}
		}else{//post
			this.url=urlString;
			paraString=requestInfo.substring(requestInfo.lastIndexOf(CRLF)).trim();
		}
		if (paraString.equals("")) {
			return;
		}
		this.parseParam(paraString);
	}
	//将参数分解出来
	private void parseParam(String paraString) {
		String [] token=paraString.split("&");
		for(int i=0;i<token.length;i++){
			String keyValues=token[i];
			String [] kv=keyValues.split("=");
				if(kv.length==1) {
					kv=Arrays.copyOf(kv, 2);
					kv[1]=null;
				}
				//将分解出的参数存储到Map中
				String key=kv[0].trim();
				String value=kv[1]==null?null:decode(kv[1].trim(), "utf-8");
				if(!parameterValues.containsKey(key)) {
					parameterValues.put(key, new ArrayList<String>());
				}
				List<String> values=parameterValues.get(key);
				values.add(value);	
		}

	}
	//根据表单元素的name获取多个值
	private String [] getParamterValues(String name){
		//根据key获取value
		List<String> values=parameterValues.get(name);
		if (values==null) {
			return null;
		}else{
			return values.toArray(new String [0] );
		}
		
	}
	public String getParamter(String name){
		//调用本类中根据name获取多个值的方法
		String [] values=this.getParamterValues(name);
		if (values==null) {
			return null;
		}else{
			return values[0];
		}
	}
		
		//处理中文,进行解码
	private String decode(String value,String code){
		try {
			return URLDecoder.decode(value, code);
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		return null;
	}

	public String getUrl() {
		return url;
	}

	//测试
	public static void main(String[] args) {
		Request req=new Request();
		//调用分解参数的方法
		req.parseParam("username=us");
		System.out.println(req.parameterValues);
		
		//调用获取单个值的方法
		System.out.println(req.getParamter("pwd"));
	}


	

}

请老师帮忙看看,为什么 parameterValues传不进去值?

JAVA 全系列/第二阶段:JAVA 基础深化和提高/手写服务器项目(旧) 3946楼
推荐

老师,您好,我在这里遇到了问题,问题如下

问题描述:在进行Reseponse封装后,服务器能启动起来,但在html文档里面输入内容后服务器反馈异常。

相关代码:

package com.like.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.like.util.IOCloseUtil;

public class Response {//响应
	private StringBuilder headInfo;//响应头
	private StringBuilder content;//响应内容
	private int length;//响应内容长度
	//流
	private BufferedWriter bw;
	
	//两个常量,换行和空格
	private static final String CRLF="\r\n";
	private static final String BLANK=" ";
	
	//构造方法
	public Response() {
		headInfo=new StringBuilder();
		content=new StringBuilder();
	}
	public Response(OutputStream os) {
		this();//调用本类的无参构造方法
		try {
			bw=new BufferedWriter(new OutputStreamWriter(os,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			headInfo=null;
		}
	}
	
	//构造正文部分
	public Response print(String info) {//不换行的
		content.append(info);
		try {
			length+=info.getBytes("utf-8").length;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this;
	}
	
	public Response println(String info) {//换行的
		content.append(info).append(CRLF);
		try {
			length+=info.getBytes("utf-8").length;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this;
	}
	
	//构造响应头
	private void createHeadInfo(int code) {
		headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
		switch(code) {
		case 200:
			headInfo.append("OK");
			break;
		case 500:
			headInfo.append("SERVER ERROR");
			break;
		default:
			headInfo.append("NOT FOUND");
			break;
		}
		headInfo.append(CRLF);
		headInfo.append("Content-Type:text/html;charse=utf-8").append(CRLF);
		headInfo.append("Content-Length:"+length).append(CRLF);
		headInfo.append(CRLF);
	}
	
	public void pushToClient(int code) {
		if(headInfo==null) {
			code=500;
		}
		try {
			//调用本类中的响应头
			this.createHeadInfo(code);
			bw.write(headInfo.toString());
			bw.write(content.toString());
			bw.flush();
			this.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void close() {
		IOCloseUtil.closeAll(bw);
	}
}

Server:

public class Server {//服务器,用于启动和停止服务器
	private ServerSocket server;
	public static void main(String[] args) {
		Server server=new Server();
		server.start();
	}
	public void start() {
		this.start(8888);
	}
	public void start(int port) {
		try {
			server=new ServerSocket(port);
			this.receive();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void receive() {
		//监听
		try {
			Socket client=server.accept();
			/*
			//获取用户的请求
			InputStream is=client.getInputStream();
			byte[] buf=new byte[20480];
			int len=is.read(buf);
			System.out.println(new String(buf,0,len));*/
			//封装请求信息
			Request req=new Request(client.getInputStream());
			req.show();
			
			Response rep=new Response(client.getOutputStream());
			Servlet servlet=WebApp.getServlet(req.getUrl());
			int code=200;
			if(servlet==null) {
				code=404;
			}
			//调用Servlet中的服务方法
			try {
				servlet.service(req,rep);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rep.pushToClient(code);
			IOCloseUtil.closeAll(client);
			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void stop() {}
}

HTML

<html>
	<head>
		<title>我是第一个html</title>
	</head>
	<body>
		<h1>hello world!</h1>
		<form action="http://localhost:8888/log" method="get">
			<p>用户名:<input type="text" id="uname" name="username" /></p>
			<p>密&nbsp&nbsp码:<input type="password" id="pwd" name="password" /></p>
			<p>兴趣爱好:<input type="checkbox" name="hobby" value="ball"/>球
			<input type="checkbox" name="hobby" value="read"/>读书
			<input type="checkbox" name="hobby" value="paint"/>画画</p>
			<p><input type="submit" value="登录"/></p>
		</form>
	</body>
</html>

异常截图如下:

blob.png

在这之前的检测都是正常的。

源代码:

http_server6.zip


JAVA 全系列/第二阶段:JAVA 基础深化和提高/手写服务器项目(旧) 3948楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 3949楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器(旧) 3950楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/手写服务器项目(旧) 3951楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/XML 技术(旧) 3953楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637