随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
package com.lovo;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
public static boolean isRun = true;
public WebServer() {
try {
ServerSocket server = new ServerSocket(8088); // 开启服务器并开放8088端口
while (isRun) {
// 监听端口,一旦有客户端连接到服务器,就将客户端的信息封装成socket对象
Socket socket = server.accept();
new DisposeSocket(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new WebServer();
}
}
package com.lovo;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import com.lovo.service.ServiceFactory;
import com.lovo.service.Servlet;
public class DisposeSocket extends Thread {
private Socket socket;
public DisposeSocket(Socket socket) {
this.socket = socket;
this.start();
}
public void run() {
try {
InputStream in = socket.getInputStream();// 从socket中得到读取流,用于接收数据
Request request = new Request(in);// 将读取流封装成请求对象
System.out.println(request);
OutputStream out = socket.getOutputStream();// 从socket中得到写入流,用于发送数据
Response response = new Response(out);// 将写入流封装成Response响应对象
String url = request.getUrl();// 得到URL
Servlet s = ServiceFactory.getServlet(url);// 调用工厂类,得到Servlet接口对象
if (s != null) {// 请求的是业务组件
s.service(request, response);// 调用service方法,完成业务方法的调用
} else {// 请求的是文件
response.sendFile(url);
}
out.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.lovo;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
* 封装socket读取流的请求对象
*
* @author Administrator
*
*/
public class Request {
private InputStream in;
/** 用户请求的路径 */
private String url;
/** 请求参数的Map集合 */
private Map<String, String> paramMap = new HashMap<String, String>();
public Request(InputStream in) {
this.in = in;
try {
byte[] by = new byte[1024];
in.read(by);// 将客户端读取的数据放在by中
String str = new String(by).trim();// 将字节数组封装成字符串
System.out.println(str);
if (str.startsWith("GET")) {// 处理get请求
this.pressGet(str);
} else if (str.startsWith("POST")) {
this.pressPost(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理GET请求
*
* @param str
* 请求参数
*/
private void pressGet(String str) {
String[] sts = str.split("\\s+");
if (sts[1].indexOf("?") != -1) {// 请求的业务组建
String[] temp = sts[1].split("[?]");// 按?拆分,第一个元素是URL,第二个是请求元素
this.url = temp[0].substring(1);// 得到url
this.fullMap(temp[1]);
} else {// 请求的是文件
this.url = sts[1].substring(1);// 得到url
}
}
/**
* 处理POST请求
*
* @param str
* 请求参数
*/
private void pressPost(String str) {
String[] temp = str.split("\\s+");
this.url = temp[1].substring(1);
this.fullMap(temp[temp.length - 1]);
}
/**
* 将请求字符串封装成Map集合
*
* @param str
*/
private void fullMap(String str) {
try {
str = URLDecoder.decode(str, "gbk");// 解码,将ISO8859-1解码为中文字
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] temp = str.split("&");
for (String s : temp) {
String[] p = s.split("=");
if (p.length == 2) {
this.paramMap.put(p[0], p[1]);// 将键值对加入集合
} else if (p.length == 1) {
this.paramMap.put(p[0], "");
}
}
}
public String getUrl() {
return url;
}
/**
*
* @param key
* @return
*/
public String getParameter(String key) {
return this.paramMap.get(key);
}
public String toString() {
return "url:" + url + " " + "请求参数:" + this.paramMap;
}
}
package com.lovo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 向客户端发送信息的响应对象
*
* @author Administrator
*
*/
public class Response {
/** 从socket中得到的写入流 */
private OutputStream out;
public Response(OutputStream out) {
this.out = out;
}
/**
* 向客户端发送文本消息
*
* @param str
*/
public void sendMessage(String str) {
try {
out.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向客户端发送文件消息
*
* @param filePath
* 文件路径
*/
public void sendFile(String filePath) {
File f = new File(filePath);
if (!f.exists()) {
return;
}
InputStream fin = null;
try {
fin = new FileInputStream(filePath);
// 从文件中读取数据,写入到out中,由于out是从socket中得到的,输出的地点就是客户端
byte[] by = new byte[1024];
int len = 0;
while ((len = fin.read(by)) != -1) {
out.write(by, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.lovo.service;
import com.lovo.Request;
import com.lovo.Response;
public interface Servlet {
/**
* 业务方法
*
* @param request
* 请求对象
* @param response
* 响应对象
*/
public void service(Request request, Response response);
}
package com.lovo.service;
import com.lovo.Request;
import com.lovo.Response;
import com.lovo.bean.UserBean;
import com.lovo.dao.IUserDao;
import com.lovo.dao.impl.UserDaoImpl;
/**
* 登陆的业务组件
*
* @author Administrator
*
*/
public class LoginService implements Servlet {
IUserDao dao = new UserDaoImpl();
/**
* 业务方法
*
* @param request
* 请求对象
* @param response
* 响应对象
*/
public void service(Request request, Response response) {
//实体类,dao层,省略
UserBean bean = dao.login(request.getParameter("userName"),
request.getParameter("pwd"));
if (bean != null) {// 登陆成功
response.sendFile("index.html");
} else {// 登陆失败
response.sendFile("loginError.html");
}
}
}
package com.lovo.service;
import com.lovo.Request;
import com.lovo.Response;
import com.lovo.bean.UserBean;
import com.lovo.dao.IUserDao;
import com.lovo.dao.impl.UserDaoImpl;
/**
* 注册业务组件
*
* @author Administrator
*
*/
public class RegisterService implements Servlet {
/** 持久化业务组件 */
private IUserDao dao = new UserDaoImpl();
/**
* 注册业务方法
*
* @param request
* 请求对象
* @param response
* 响应对象
*/
public void service(Request request, Response response) {
String pwd = request.getParameter("pwd");
String rePwd = request.getParameter("repwd");
if (!pwd.equals(rePwd)) {
response.sendMessage("两次密码不一致</br>");
response.sendMessage("<a href='register.html'> 重新注册</a>");
return;
}
// 创建实体类,封装页面数据
UserBean bean = new UserBean();
bean.setUserName(request.getParameter("userName"));
bean.setPwd(pwd);
bean.setSex(request.getParameter("sex"));
bean.setEdu(request.getParameter("edu"));
dao.add(bean);
response.sendMessage("注册成功</br>");
response.sendMessage("<a href='1.html'> 重新登陆</a>");
}
}
package com.lovo.service;
import java.io.FileReader;
import java.util.Properties;
/**
* 业务组件工厂类
*
* @author Administrator
*
*/
public class ServiceFactory {
private static Properties pro = new Properties();
static {
try {
pro.load(new FileReader("web.txt"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据URL,得到处理该URL的业务组件
*
* @param url
* @return
*/
public static Servlet getServlet(String url) {
String className = pro.getProperty(url); // 根据键,得到值
if (className == null) {
return null;
}
try {
Class c = Class.forName(className);// 加载类得到了类模板
Object obj = c.newInstance();// 产生该类的对象
return (Servlet) obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}