JSP学习笔记(第0次):Eclipse j2ee+tomcat 7+servlet 3.0搭建

时间:2020-12-24 21:04:10
1.配置Tomcat 7

1.1添加3个系统变量
  • CATALINA_HOME D:\apache-tomcat-7.0.70
  • CATALINA_BASE  D:\apache-tomcat-7.0.70
  • TOMCAT_HOME   D:\apache-tomcat-7.0.70
2.在Eclipse中创建Servers

2.1在Eclipse中创建一个Dynamic web project
*该步骤选中tomcat 7+servlet 3.0的配置
JSP学习笔记(第0次):Eclipse j2ee+tomcat 7+servlet 3.0搭建
2.2.1创建class继承自  HttpServlet
package servletHello;

import java.io.IOException;
import java.io.PrintWriter;

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(name="Servlet01",urlPatterns="/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 // TODO Auto-generated method stub
 System.out.println("dasdsdsa");
 //super.doGet(req, resp);
 resp.setContentType("text/html;charset=UTF-8");
 PrintWriter out =resp.getWriter();
 out.println("<html>");
 out.println("<body><h1>hello servlet</h1></body>");
 out.println("</html>");
}

}


2.2配置Servlet
JSP学习笔记(第0次):Eclipse j2ee+tomcat 7+servlet 3.0搭建
这里可以选择保留自动创建一个Web.xml在web-inf中,从而可以用老的手段来配置servlet,如下:

比较:相对于web.xml中的配置,需要如下代码:


<servlet>

   <servlet-name>Hello</servlet-name>

   <servlet-class>servletHello.HelloServlet</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>Hello</servlet-name>

   <url-pattern>/hello</url-pattern>

 </servlet-mapping>


但在tomcat 7以上+servlet 3.0中可以直接用注解来配置servlet,如下

@WebServlet(name="Servlet01",urlPatterns="/hello")
public class HelloServlet extends HttpServlet {
.....}

在WebServlet中有一堆属性,可以用来与web.xml中配置servlet做一样的事情
部分属性如下:
JSP学习笔记(第0次):Eclipse j2ee+tomcat 7+servlet 3.0搭建
(本图转自点击打开链接

如此配置完成之后再浏览器中直接进入
http://localhost:8080/servlet/hello

此时会出现错误405,因为在类HellpServlet中重写doGet时先调用了父类的doGet,把导致执行doGet时转跳到父类的doGet里去了,此时把父类的doGet注释掉

//super.doGet(req, resp);

刷新页面,doGet执行即在页面中写了
JSP学习笔记(第0次):Eclipse j2ee+tomcat 7+servlet 3.0搭建