API用法
public class ServletThreeImpl extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // :6003/servletThreeImpl?myName=cicada String method = request.getMethod(); System.out.println("method="+method); // GET String requestURL = request.getRequestURL().toString(); // :6003/servletThreeImpl System.out.println("requestURL="+requestURL); String requestURI = request.getRequestURI(); System.out.println("requestURI="+requestURI); // /servletThreeImpl String queryString = request.getQueryString() ; System.out.println("queryString="+queryString); // myName=cicada String myName = request.getParameter("myName"); System.out.println("myName="+myName); // cicada } } 五、ServletResponse接口 1、接口简介HttpServletResponse继承自ServletResponse,封装了Http响应信息。客户端每个请求,服务器都会创建一个response对象,并传入给Servlet.service()方法。核心作用:1.设置响应头信息;2.发送状态码;3.设置响应正文;4.重定向;
2、代码案例配置文件
<servlet> <servlet-name>servletFourImpl</servlet-name> <servlet-class>com.node02.servlet.impl.ServletFourImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletFourImpl</servlet-name> <url-pattern>/servletFourImpl</url-pattern> </servlet-mapping>API用法
public class ServletFourImpl extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8") ; response.setCharacterEncoding("UTF-8"); response.setStatus(200) ; response.getWriter().print("Hello,知了"); } } 3、转发和重定向转发
服务器端进行的页面跳转的控制 ;
request.getRequestDispatcher("/转发地址").forward(request, response);重定向
服务端响应跳转信息,浏览器端进行的页面跳转 ;
response.sendRedirect("重定向地址");转发和重定向对比
区别 转发 重定向地址栏 不变 变化
跳转 服务端跳转 浏览器端跳转
请求次数 一次 两次
域中数据 不会丢失 丢失
六、源代码地址 GitHub·地址 https://github.com/cicadasmile/java-base-parent GitEE·地址 https://gitee.com/cicadasmile/java-base-parent