今天闲来无事,将入门的Java Web过程写一下
第一步:建立一个JavaWeb的工程文件,在此项目下面新建servlet,建好后的项目如下图:
第二步:
和Servlet交互,打开TestServlet_1.java文件,写入自己的代码,一个简单的示例如下:
该示例的功能是当在浏览器地址栏输入给Servlet的地址,并带上name的参数,如果name 是tom,则返回OK,否则返回HELLO,源代码如下:
package cn.my.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/TestServlet_1")
public class TestServlet_1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServlet_1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
if("tom".equals(name)){
response.getWriter().print("OK");
}else{
response.getWriter().print("HELLO");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
代码写完后将项目部署到自己的Tomact里面,启动servers,在自己的浏览器里面输入请求地址,结果如下