基于socket实现一个简单的servlet

正文


这篇博文主要记录以及分享下基于ServerSocket实现一个简单的Servlet容器

首先目录结构如下图所示

web.properties


web.properties用来记录servlet类的路径

程序执行步骤


1、创建一个ServerSocket对象
2、调用ServerSocket对象的accept()方法,等待连接。连接成功返回一个socket对象
3、以该socket对象对参数创建HttpServletRequest和HttpServletResponse对象
4、通过获取request对象的url得到对应的classname,反射创建servlet
5、处理响应,调用对应的Get()方法
6、关闭socket对象

源代码

ServletTest.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.hyf.mServlets;
import java.io.PrintWriter;
import com.hyf.servlet.HttpServlet;
import com.hyf.servlet.HttpServletRequest;
import com.hyf.servlet.HttpServletResponse;
public class ServletTest extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
// TODO Auto-generated method stub
String username = req.getParameter("username");
//System.out.println(username);
String html = "<html><head></head><body><h2>Test:"+username+
"</h2></body></html>";
PrintWriter pw = res.getWriter();
pw.println(html);
pw.flush();
pw.close();
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) {
// TODO Auto-generated method stub
this.doGet(req, res);
}
}

Service.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.hyf.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Properties;
import com.hyf.servlet.HttpServlet;
import com.hyf.servlet.HttpServletRequest;
import com.hyf.servlet.HttpServletResponse;
public class Service {
@SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
HashMap<String, HttpServlet> map = new HashMap<String, HttpServlet>();
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src/web.properties"));
server = new ServerSocket(22221);
while (true) {
Socket client = server.accept();
HttpServletRequest req = new HttpServletRequest(client);
HttpServletResponse res = new HttpServletResponse(client);
String url = req.getUrlPattern();
System.out.println(url);
String className = prop.getProperty(url);// 获取servlet类名
System.out.println(className);
if (className != null) {
HttpServlet servlet = map.get(className);
if (servlet == null) {
servlet = (HttpServlet) Class.forName(className)
.newInstance();
map.put(className, servlet);
}
servlet.service(req, res);
}
client.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

HttpServlet.java


1

HttpServletRequest.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.hyf.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.swing.text.html.HTMLDocument.Iterator;
public class HttpServletRequest {
private String method;
private Socket socket;
private String urlPattern;
private Map<String,String> params;
public HttpServletRequest(Socket socket){
this.socket = socket;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));//获取输入流
String str = br.readLine();
System.out.println(str);
String[] items = str.split(" ");
// for(String s : items){
// System.out.println(s);
// }
method = items[0];//获取方法
int index = items[1].indexOf("?");
// System.out.println(index);
if(index!=-1){//获取Url
urlPattern = items[1].substring(0, index);
params = new HashMap<String, String>();//实例化params
String parameter = items[1].substring(index+1);
// System.out.println(parameter);
String[] parameters = parameter.split("&");
for(int i=0;i< parameters.length;i++){
String[] ss = parameters[i].split("=");
params.put(ss[0], ss[1]);
}
//HashMap遍历
// for(String key:params.keySet()){
// System.out.println(key);
// System.out.println(params.get(key));
// }
}else{
urlPattern = items[1];
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getMethod() {
// TODO Auto-generated method stub
return method;
}
public String getParameter(String string) {
// TODO Auto-generated method stub
return params.get(string);
}
public String getUrlPattern(){
return urlPattern;
}
}

HttpServletResponse.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.hyf.servlet;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class HttpServletResponse {
private Socket socket;
public HttpServletResponse(Socket socket){
this.socket = socket;
}
public PrintWriter getWriter() {
// TODO Auto-generated method stub
try {
return new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}