上一小节已经实现了对图片的传输,接下来就是判断文件是否为js,css,png等格式。我们增加一个函数用于判断格式
1 int WebServer::get_filetype(char *type,char *path)//用于判断该url指向文件的后缀 2 { 3 if(strstr(path,".html")) 4 strcpy(type,"text/html"); 5 else if(strstr(path,".gif")) 6 strcpy(type,"image/gif"); 7 else if(strstr(path,".jpg")) 8 strcpy(type,"image/jpeg"); 9 else if(strstr(path,".png")) 10 strcpy(type,"image/png"); 11 else if(strstr(path,".ico")) 12 strcpy(type,"image/x-icon"); 13 else if(strstr(path,".js")) 14 strcpy(type,"text/javascript"); 15 else if(strstr(path,".json")) 16 strcpy(type,"application/json"); 17 else if(strstr(path,".css")) 18 strcpy(type,"text/css"); 19 else 20 strcpy(type,"text/plain"); 21 return 0; 22 }
然后修改一下主页index.html的文件
1 <html> 2 <head> 3 <title>Test</title> 4 <meta http-equiv="Content-Type" content="text/html ; charset=utf-8"> 5 <link rel="stylesheet" href="style.css" type="text/css"/> 6 <script language="javascript" src="javascript.js"></script> 7 </head> 8 9 <body> 10 <div class="ceshi">图片</div><img src="ab.jpg"></img> 11 <input name="button" type="button" value="Click!" onclick=hi();></input> 12 </body> 13 </html>
两个外部文件如下
1 [myuser@bogon www]$ cat style.css 2 .ceshi {font-size:20px; color:#ff0000;} 3 [myuser@bogon www]$ cat javascript.js 4 function hi() 5 { 6 alert("js 调用,你单机了按钮"); 7 } 8 [myuser@bogon www]$
下面这个是运行的结果图
用chrome浏览器的F12调试工具获取到的状态,可以看到,该网页可以获取到index.html,然后浏览器会根据这个页面再发送index.html文件所需要的外部文件的请求,从上面可以看出请求了style.css,javascript.js和ab.jpg图片。然后显示网页,我单击了那个button也是可以调用js脚本的。
接下来就是判断一个提交是get还是post,网页index.html的源代码
1 <body> 2 <div class="ceshi">图片</div><img src="ab.jpg"></img> 3 <input name="button" type="button" value="Click!" onclick=hi();></input> 4 5 <hr> 6 <br>使用post方式<br> 7 <form method="post" name="frm1"> 8 <label>用户名:</label> 9 <input type="text" name="username" /> 10 <br> 11 <label>密码:</label> 12 <input type="password" name="password" /> 13 <br> 14 <input type="submit" name="commit" value="登陆"/> 15 <br> 16 </form> 17 <hr> 18 <br>使用get方式<br> 19 <form method="get" name="frm1" action="index.html"> 20 <label>用户名:</label> 21 <input type="text" name="username" /> 22 <br> 23 <label>密码:</label> 24 <input type="password" name="password" /> 25 <br> 26 <input type="submit" name="commit" value="登陆"/> 27 <br> 28 </form> 29 </body>
修改后的ServerRequest函数
1 int WebServer::ServerRequest(int cli_fd) 2 { 3 char buf[1024]; 4 int size=1024; 5 int i,j; 6 char method[255];//用于保存请求方式 7 char url[512]; 8 char path[1024]; 9 char args[1024]; 10 struct stat st; 11 int cgi;//cgi 为0 表示get普通方法 1表示get带参方法 2表示post方法 12 pid_t pid; 13 memset(buf,0,sizeof(buf)); 14 cgi=0; 15 //获取第一行请求信息 一般格式为: GET / HTTP/1.1 16 // POST / HTTP/1.1 17 size=get_line(cli_fd,buf,sizeof(buf)); 18 //cout<<" "<<buf<<endl; 19 i=0,j=0; 20 //截取第一个单词 21 while(!isspace(buf[j]) && (i<sizeof(method)-1)) 22 { 23 method[i]=buf[j]; 24 i++;j++; 25 } 26 method[i]='