Myeclipse2017实例关于servlet的@WebServlet注解。

目录结构

Myeclipse2017实例关于servlet的@WebServlet注解。_第1张图片

Servlet

@WebServlet注解用于标注在一个继承了HttpServlet类之上,属于类级别的注解。
用法形如:
@WebServlet(“/DisplayHeader1”)

package tuzi.com;
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("/HelloForm")
public class HelloForm extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "使用 GET 方法读取表单数据";
        // 处理中文
        String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
        String docType = " \n";
        out.println(docType +
            "\n" +
            ""</span> + title + <span class="hljs-string">"\n" +
            "\n" +
            "

" + title + "

\n"
+ "
    \n" + "
  • 站点名:" + name + "\n" + "
  • 网址:" + request.getParameter("url") + "\n" + "
\n"
+ ""); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

其中 /DisplayHeader1 表示访问该servlet的 url 映射(地址)(此处为相对路径,即
“项目名称/DisplayHeader1” )。

Web.xml


<web-app>
  <servlet>
    <servlet-name>HelloFormservlet-name>//类名,和servlet-mappping中的url-mapping值要相同
    <servlet-class>tuzi.com.HelloFormservlet-class>//所在的包名
  servlet>
  <servlet-mapping>
    <servlet-name>HelloFormservlet-name>
    <url-pattern>/Servet/HelloFormurl-pattern>//在浏览器中输入的url
  servlet-mapping>
web-app>

结果

Myeclipse2017实例关于servlet的@WebServlet注解。_第2张图片

你可能感兴趣的:(JAVA-WEB,JAVA-EE,Myeclipse)