一
Web工程结构 实例1FirstServlet.java
package com.servlet;
public class FirstServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接受请求发来的参数
String name = request.getParameter("name");
String html = "hi,"+ name +"!
";
PrintWriter out = response.getWriter();//从服务器到浏览器返回的输出流
System.out.println("返回给浏览器的响应数据为:"+html);
out.println(html);//将html发回浏览器
}
}
xml:
FirstServlet ... first com.servlet.FirstServlet first /hi
图解
浏览器中输入信息,通过请求给TC,TC查看url去xml中匹配,匹配到后查找,再创建FirstServlet对象,执行service方法,提供响应和支持
out后,TC通过响应给浏览器,执行结果。
步骤:
1.创建Servlet类,继承HttpServlet
2.重写service方法,编写程序代码
3.配置web.xml,绑定URL
Servlet访问方法
http://IP地址:端口/context-path/url-mapping远程访问使用IP地址,本地访问localhost(127.0.0.1)context-path成为“上下文路径”,默认为工程名 实例2
SampleServlet.java
package com.servlet;
public class SampleServlet extends HttpServlet {
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();//向浏览器输出的数据流
out.println("Baidu");
}
}
xml:
sample com.servlet.SampleServlet sample /sample
访问使用:
http://localhost:8080/FirstServlet/sample
http://127.0.0.1:8080/FirstServlet/sample
请求参数是指浏览器通过请求向Tomcat提交的数据。通常是用户输入的数据,待Servlet进行处理;
格式:参数名1=值1&参数名2=值2&参数名n=...
表单中action属性



