码迷,mamicode.com
首页 > 编程语言 > 详细

【java web学习笔记(2)】first servlet

时间:2016-10-10 23:50:24      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

src-> new-> servlet

可见,继承自HttpServlet

dopost doget分别是post请求和get请求时调用的

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by DESTR on 2016/10/10.
 */
@WebServlet(name = "FirstServlet")
public class FirstServlet extends HttpServlet
{
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("<p>Hello post</p>");
		out.flush();
		out.close();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("<p>Hello get</p>");
		out.flush();
		out.close();
	}
}

url 映射:

在web.xml里添加<servlet-mapping>元素

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>FirstServlet</servlet-name>
        <servlet-class>FirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServlet</servlet-name>
        <url-pattern>/firstServlet/Hello</url-pattern>
    </servlet-mapping>
</web-app>
<url-pattern>元素表明访问路径
运行后:

技术分享

 

【java web学习笔记(2)】first servlet

标签:

原文地址:http://www.cnblogs.com/dreamingsheep/p/5947538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!