6、Servlet
6.2 helloServlet
一个接口Servlet,
开发servlet
httpservlet
重写方法 dopost() doget()
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletOutputStream outputStream = resp.getOutputStream();
PrintWriter writer = resp.getWriter();//响应流
writer.print("hello,servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
5、编写servlet的映射
为什么需要映射:java程序,需要浏览器访问,浏览器需要连接web服务器,所以需要在web服务中注册写的Servlet,还需要给他一个浏览器能访问的路径。
6、webxml
//注册servlet
//servlet的请求路径
<servlet-mapping>
<servlet-name>hello</servlet_name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
6.3 servlet原理
浏览器发送http请求给web容器
6.4 mapping问题
1、一个servlet可以对应一个映射路径
<servlet-name>hello</servlet_name>
<url-pattern>/hello</url-pattern>
2、一个servlet可以指定多个映射路径
3、一个servlet可以指定通用映射路径
4、错误处理
servlet
public class ErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h1>404<h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
5、问题 优先级问题
指定了固有的映射路径优先级最高;如果找不到,就会走自定义;
6.5 ServletContext对象
web容器启动时,为每个web程序都创建了一个对应的servletContext对象,它代表了当前的web应用。
应用
共享数据
在这个servlet保存的数据,可以在另一个servlet拿到。
架构表示
案例
代码1
在helloServlet中新建插入一个servletContext
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username="秦将";
context.setAttribute("username",username); //将一个数据保存在servletContext中
}
代码2
在getServlet类中得到
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
System.out.println(username);
//注意,这些还不够
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print("名字"+username);
}
当然,别忘了
注册
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.kuang.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>