ServletRequest
1、ServletRequest.getParameter() // 接收指定名称的参数 2、ServletRequest.getParameterValues() // 以数组的形式接收参数 3、ServletRequest.getParameterNames() // 接收参数名列表 (枚举格式) 4、ServletRequest.getParameterMap() // 接受参数列表(map格式)
例:接收GET传参
访问url路径
- http://localhost:8080/demo01/Two?username=admin&psd=&hobby=1&hobby=2
Servlet中接收对应参数
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
String username = req.getParameter("username");
String[] hobby = req.getParameterValues("hobby");
System.out.println(username);
System.out.println(Arrays.toString(hobby));
Enumeration<String> names = req.getParameterNames();
Map<String, String[]> map = req.getParameterMap();
}
HttpServletRequest
1、HttpServletRequest.getRequestURL() // 获取完整的url路径 2、HttpServletRequest.getRequestURI() // 获取url中资源路径部分 3、HttpServletRequest.getMethod() // 获取请求方式 4、HttpServletRequest.getQueryString() // 获取参数部分
例:接收GET传参
访问url路径
- http://localhost:8080/demo01/Two?username=admin&psd=&hobby=1&hobby=2
Servlet中接收对应参数
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
String requestURL = httpServletRequest.getRequestURL().toString();
String requestURI = httpServletRequest.getRequestURI();
String method = httpServletRequest.getMethod();
String queryString = httpServletRequest.getQueryString();
System.out.println(requestURL);
System.out.println(requestURI);
System.out.println(method);
System.out.println(queryString);
}
ServletResponse
1、ServletResponse.getWriter().println() // 将文本内容响应到浏览器页面中 2、ServletResponse.setContentType() // 设置响应的内容类型,如"word" (tomcat的conf目录下的web.xml中查看类型)
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.getWriter().println("xiaoming");
res.setContentType("application/msword");
}
HttpServletResponse
1、HttpServletResponse.sendRedirect() // 重定向跳转
访问该Servlet时,重定向到 名为Two的Servlet中
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletResponse httpServletResponse = (HttpServletResponse) res;
httpServletResponse.sendRedirect("/demo01/Two");
}
|