申明:教材来于百战程序员
1文件目录
![]()
文件目录
2 源文件
Dispatcher.java---分发器
/**
* 分发器
* @author 60341
*
*/
public class Dispatcher implements Runnable{private Socket client;
private Response response;
private Request request;
public Dispatcher(Socket client) {
this.client = client;
try {
//获取请求协议
//获取响应协议
this.request = new Request(client);
this.response = new Response(client);
} catch (IOException e) {
e.printStackTrace();
this.release();
}
}
@Override
public void run() {
try {
//无地址则加载首页
if(null==request.getUrl()||"".equals(request.getUrl()) ){
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("index.html");
byte[] aa= new byte[1024*1024];
int len = is.read(aa);
String mString = new String(aa,0,len).trim();
response.println(mString);
response.pushToBrowser(200);
is.close();
return;
}
Servlet servlet = WebApp.getServletFormUrl(request.getUrl());
if (null!=servlet) {
servlet.service(request, response);
//关注状态码
response.pushToBrowser(200);
}else{
//错误……
//加载404页面
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("error.html");
byte[] aa= new byte[1024*1024];
int len = is.read(aa);
String mString = new String(aa,0,len).trim();
response.println(mString);
response.pushToBrowser(404);
is.close();
}
} catch (IOException e) {
try {
response.pushToBrowser(505);
} catch (IOException e1) {
e1.printStackTrace();
}
}
release();//释放资源,否则线程等待--短链接,可提高性能;用完就释放
}
/**
* 释放资源
*/
private void release(){
try {
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}}
Entity.java
public class Entity {
private String name;
private String clz;
public Entity(){
}
public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}
public void setClz(String clz) {
this.clz = clz;
}
public String getClz() {
return clz;
}
}
Mapping.java
public class Mapping {
private String name;
Set<String> patterns = new HashSet<String>();;
public Mapping(){
}
public String getName() {
return name;
}public void setName(String name) {
this.name = name;
}public void setPatterns(Set<String> patterns) {
this.patterns = patterns;
}public Set<String> getPatterns() {
return patterns;
}
public void add(String pattern) {
this.patterns.add(pattern);
}
}
Request.java
public class Request {
private String requestInfo;
private String url;
private String method;
//请求参数
private String queryStr;
//存储参数
private Map<String, List<String>> parameterMap;
private final String CRLF = "\r\n";
public Request(Socket client) throws IOException {
this(client.getInputStream());
}
public Request(InputStream is) {
parameterMap = new HashMap<String, List<String>>();
byte[] datas = new byte[1024*1024];
int len;
try {
len = is.read(datas);
this.requestInfo = new String(datas, 0, len);
} catch (IOException e) {
e.printStackTrace();
return;
};
parseRequestInfo();
convertMap();
}
private void parseRequestInfo() {
System.out.println("--");
this.method =this.requestInfo.substring(0, this.requestInfo.indexOf("/")).toLowerCase();
this.method = this.method.trim();
int startIdx = this.requestInfo.indexOf("/")+1;
int endIdx = this.requestInfo.indexOf("HTTP/");
this.url = this.requestInfo.substring(startIdx, endIdx).trim();
int queryIdx = this.requestInfo.indexOf("?");
if(queryIdx>=0){//表示请求存在参数
String[] urlArray = this.url.split("\\?");
this.url = urlArray[0];
queryStr = urlArray[1];
}
if (method.equals("post")) {
String qStr = this.requestInfo.substring(this.requestInfo.lastIndexOf(CRLF)).trim();
if(null==queryStr){
queryStr = qStr;
}else {
queryStr += "&" + qStr;
}
}
queryStr = null ==queryStr?"":queryStr;
//装成map
}
//处理请求参数为map
private void convertMap() {
String[] keyValues = this.queryStr.split("&");
for(String query:keyValues){
String[] kv = query.split("=");
kv = Arrays.copyOf(kv, 2);//防止没值
String key =kv[0];
String value =kv[1]==null?null:decode(kv[1],"utf-8");;
if(!parameterMap.containsKey(key)){
parameterMap.put(key, new ArrayList<String>());
}
parameterMap.get(key).add(value);
}
}
/**
* 处理中文
* @param value
* @param enc
* @return
*/
private String decode(String value,String enc){
try {
return java.net.URLDecoder.decode(value, enc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 同过name获取对应的值
* @param key
* @return
*/
public String[] getParameterValues(String key) {
List<String> values = this.parameterMap.get(key);
if (null==values||values.size()<1) {
return null;
}
return values.toArray(new String[0]);
}
/**
* 同过name获取对应的一个值
* @param key
* @return
*/
public String getParameter(String key) {
String[] values = getParameterValues(key);
return values==null?null:values[0];
}
public String getUrl() {
return url;
}public String getMethod() {
return method;
}public String getQueryStr() {
return queryStr;
}
}
Response.java
public class Response {
private BufferedWriter bw;
/*private Socket client;*/
//正文
private StringBuilder content;
//协议头(状态行和请求头 回车)信息
private StringBuilder headInfo;
private final String BLACK = " ";
private final String CRLF = "\r\n";
//正文字节数
private int len;
public Response(){
content = new StringBuilder();
headInfo = new StringBuilder();
len = 0;
}
public Response(Socket client){
this();
try {
bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
headInfo = null;
}
}
public Response(OutputStream os){
this();
bw = new BufferedWriter(new OutputStreamWriter(os));
}
//动态添加内容
public Response print(String info) {
content.append(info);
len += info.getBytes().length;
return this;
}
//动态添加内容
public Response println(String info) {
content.append(info).append(CRLF);
len += (info+CRLF).getBytes().length;
return this;
}
//推送响应信息
public void pushToBrowser(int code) throws IOException{
if (null == headInfo) {
code = 505;
}
createHeadInfo(code);
bw.append(headInfo);
bw.append(content);
bw.flush();
}
//构建头信息
public void createHeadInfo(int code){
//1 响应行:HTTP/1.1 200 OK
headInfo.append("HTTP/1.1").append(BLACK).append(code).append(BLACK);
switch(code){
case 200:
headInfo.append("OK").append(CRLF);
break;
case 404:
headInfo.append("NOT FOUND").append(CRLF);
break;
case 505:
headInfo.append("SERVER ERROR").append(CRLF);
break;
}
//2 响应头(最后一行是空行):字节数大小
headInfo.append("Date:").append(new Date()).append(CRLF);
headInfo.append("Server:").append("shsxt Server/0.0.1;charset=GBK").append(CRLF);
headInfo.append("Content-Type:text/html").append(CRLF);
headInfo.append("Content-Length:").append(len).append(CRLF);
headInfo.append(CRLF);
}
}
Server.java
/**
* 目标:处理404 505页面
* @author 60341
*
*/
public class Server {
private ServerSocket serverSocket;
private boolean isRunning;
public static void main(String[] args) {
Server server = new Server();
server.start();
}
public void start(){
try {
isRunning =true;
serverSocket = new ServerSocket(8888);
receive();
} catch (IOException e) {
System.out.println("服务启动失败...");
e.printStackTrace();
stop();
}
}public void receive(){
//多线程循环
while(isRunning){
try {
Socket client = serverSocket.accept();
System.out.println("一个客户端建立连接...");
//多线程处理
new Thread(new Dispatcher(client)).start();
} catch (IOException e) {
System.out.println("客户端错误...");
e.printStackTrace();
}
}
}
public void stop(){
isRunning = false;
try {
this.serverSocket.close();
System.out.println("服务器已停止!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Servlet.java
/**
* 服务器小脚本接口
* @author 60341
*
*/
public interface Servlet {
void service(Request request,Response response);
//void doGet(Request request,Response response);
//void doPost(Request request,Response response);
}
WebApp.java
public class WebApp {
private static WebContext webContext =null;
static{
try {
//Sax解析:固定套路
//1获取解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
//2从解析工厂获取解析器
SAXParser parser = factory.newSAXParser();
//3编写处理器
//4加载文档Document注册处理器
WebHandler handler = new WebHandler();
//5解析
parser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("web.xml"),handler);
//获取数据
webContext = new WebContext(handler.getEntitys(), handler.getMappings());
} catch (Exception e) {
System.out.println("解析配置文件错误!");
}
}
/**
* 通过url获取配置文件对应的servlet
* @param url
* @return
*/
public static Servlet getServletFormUrl(String url){
String className = webContext.getClz("/" +url);
Class clz;
try {
clz = Class.forName(className);
Servlet servlet = (Servlet)clz.getConstructor().newInstance();
return servlet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
WebContext.java
public class WebContext {
private List<Entity> entitys = null;
private List<Mapping> mappings = null;
private Map<String, String> entitysMap = new HashMap<String, String>();
private Map<String, String> mappingsMap = new HashMap<String, String>();
public WebContext(List<Entity> entitys, List<Mapping> mappings){
this.entitys = entitys;
this.mappings = mappings;
for(Entity entity: entitys){
entitysMap.put(entity.getName(), entity.getClz());
}
for(Mapping mapping: mappings){
for(String pattern: mapping.getPatterns()){
mappingsMap.put(pattern, mapping.getName());
}
}
}
public String getClz(String pattern){
String name = mappingsMap.get(pattern);
return entitysMap.get(name);
}}
WebHandler.java
/**
* 处理器
* @author 60341
*
*/
public class WebHandler extends DefaultHandler{
private List<Entity> entitys;
private List<Mapping> mappings;
private Entity entity;
private Mapping mapping;
private String tag; //存储操作的
private boolean isMapping = false;
@Override
public void startDocument() throws SAXException {
entitys = new ArrayList<Entity>();
mappings = new ArrayList<Mapping>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("<"+ qName +">标签解析");
if (null!=qName) {
tag = qName;
if (qName.equals("servlet")) {
entity = new Entity();
isMapping = false;
}else if (qName.equals("servlet-mapping")) {
mapping = new Mapping();
isMapping = true;
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("</"+qName+">解析结束");
if (null!=qName) {
if (qName.equals("servlet")) {
entitys.add(entity);
}else if (qName.equals("servlet-mapping")) {
mappings.add(mapping);
}
}
tag=null;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String contents = new String(ch,start,length).trim();
System.out.println(tag +"内容为:"+contents);
if(isMapping){//操作servlet-Mapping
if (null!=tag) {
if (tag.equals("servlet-name")) {
mapping.setName(contents);
}
if (tag.equals("url-pattern")) {
mapping.add(contents);
}
}
}else{//操作servlet
if (null!=tag) {
if (tag.equals("servlet-name")) {
entity.setName(contents);
}else if(tag.equals("servlet-class")){
entity.setClz(contents);;
}
}
}
}
public List<Entity> getEntitys() {
return entitys;
}
public List<Mapping> getMappings() {
return mappings;
}}
LoginServlet.java
public class LoginServlet implements Servlet {
@Override
public void service(Request request,Response response){
response.print("<html>");
response.print("<head>");
response.print("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
response.print("<title>");
response.print("第一个servlet");
response.print("</title>");
response.print("</head>");
response.print("<body>");
response.print("回来了" + request.getParameter("uname"));
response.print("</body>");
response.print("</html>");
}
}
RegisterServlet.java
public class RegisterServlet implements Servlet {
@Override
public void service(Request request,Response response){
//关注业务逻辑
String uname = request.getParameter("uname");
String[] favs = request.getParameterValues("fav");
//返回 说明:servlet中写页面 后期改善为jsp
response.print("<html>");
response.print("<head>");
response.print("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
response.print("<title>");
response.print("注册成功");
response.print("</title>");
response.print("</head>");
response.print("<body>");
response.println("你注册的信息为:"+uname);
response.println("你喜欢的类型为:");
for(String fav : favs){
switch(fav){
case "0" :
response.print("萝莉");
break;
case "1":
response.print("豪放");
break;
case "2":
response.print("经济节约");
break;
}
}
response.print("</body>");
response.print("</html>");
}}
TestServlet.java
public class TestServlet implements Servlet{
@Override
public void service(Request request, Response response) {
response.print("<html>");
response.print("<head>");
response.print("<title>");
response.print("测试web.xml配置servlet");
response.print("</title>");
response.print("</head>");
response.print("<body>");
response.print("测试成功");
response.print("</body>");
response.print("</html>");
}}
error.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>404页面</title>
</head>
<body>
<h2>带你去旅行</h2>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>首页</title>
</head>
<body>
<h2>欢迎使用简易版服务器</h2>
</body>
</html>
login.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>第一个html登录</title>
</head>
<body>
<h1>表单的使用</h1>
<form method="post" action="http://localhost:8888/login">
用户名:<input type="text" name="uname" id="uname"/>
密码:<input type="password" name="pwd" id="pwd"/>
<input type="submit" value="登录"/>
</form>
</body>
reg.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>欢迎注册</title>
</head>
<body>
<h1></h1>
<form method="post" action="http://localhost:8888/r">
用户名:<input type="text" name="uname" id="uname"/>
你心中的女神:<input type="checkbox" name="fav" value="0"/>萝莉
<input type="checkbox" name="fav" value="1"/>豪放
<input type="checkbox" name="fav" value="2"/>经济节约
<input type="submit" value="登录"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.shsxt.user.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>com.shsxt.user.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.shsxt.user.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/r</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/testPage</url-pattern>
</servlet-mapping>
</web-app>