搭建自己的服务器
1.解压tomcatPluginV331压缩包,把里面的文件拷贝到eclipse的目录下示例(D:\eclipse-jee-mars-R-win32\eclipse\plugins),然后启动eclipse,在上方出现小猫
2.解压apache-tomcat-7.0.63-windows-x64,然后放到自己想放的目录,然后在windows下的prefer下的tomcat填入tomcat的目录,ok
3.在右上角点击 j2ee,然后创建工程,选web下dynamic– web创建工程
创建一个Html文件,nihao,然后run on server
4.创建一个新包com.web.test,然后创建一个sevlet,然后去tomcat下用build path导入sevlet-api.jar
注意在网页中访问时添加@WebServlet(“/webproject”)引号中的内容
在网页中传入内容的方法http://localhost:8080/MySeverTest/webproject?username=zhansan
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request为网页传入服务器的内容,respose从服务器传递给客户端
System.out.println(request.getParameter("username"));
response.getWriter().append("Served at: ").append(request.getContextPath());
}
得到String username的编码格式为8859-1
先使用8859-1转化成字节数组,
再使用utf-8编码格式把字节数组转化成字符串
//自己添加的转换类
import java.io.UnsupportedEncodingException;
public class Encoding {
public static String doEncoding(String string){
try {
byte [] array=string.getBytes("ISO-8859-1");
string=new String(array,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
//在servlet中的使用
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String str=request.getParameter("username");
str=Encoding.doEncoding(str);
System.out.println(str+"");
response.getWriter().append("Served at: ").append(request.getContextPath());
}
//在网页中的提交数据
http://localhost:8080/MySeverTest/webproject?username=张三
"返回数据以中文格式显示则添加"
response.setHeader("Content-type","text/html;charset=UTF-8");
response.getWriter().append("我收到了: ").append(request.getContextPath());
在eclipse下创建自己的服务器
- 调节右上角的按钮进入到JavaEE环境下,然后点击File->new->Dynamic Web Project
- 然后在创建好的工程下的Java Resources下创建new->Servlet->创建包名和类名,然后点击运行在服务器检测是否可用,注意上面提到的路径名问题。
想要在服务器中存取东西,然后供他人下载时,把所要下载的文件直接WebContent下,也可以在下面建立直属的文件夹,在文件夹下下载。
doget与dopost的区别
- 当服务器创建servlet对象后,该对象会调用init方法初始化自己,以后每当服务器再接收到一个servlet请求时,就会产生一个新线程,在这个线程中让servlet对象调用service对象检查HTTP请求类型(get,post),并在service方法中根据请求类型对应的调用doGet ,doPost方法。
-
如果不论用户请求类型是get还是post,服务器处理过程完全相同,那么可只在doPost中编写处理过程,在doGet中调用doPost就行了,反之也可以doGet中处理,doPost中调用doGet。如果根据请求类型不同而需要不同的处理,就需要在两个方法中编写不同的处理过程。get请求的东西(你页面输入的信息)会在地址栏显示所以不安全,post不显示,会好一点。一般用于表单的传递。