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 {
// 接收url参数
String username = req.getParameter("username");
// 以数组的形式接收参数
String[] hobby = req.getParameterValues("hobby");
System.out.println(username); // admin
System.out.println(Arrays.toString(hobby)); // [1, 2]
// 接收url参数名列表 (枚举格式)
Enumeration<String> names = req.getParameterNames();
// 接受form表单数据
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 {
// 将ServletRequest 强转成 HttpServletRequest
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
// 获取完整的url路径
String requestURL = httpServletRequest.getRequestURL().toString();
// 获取url中资源路径部分
String requestURI = httpServletRequest.getRequestURI();
// 获取请求方式
String method = httpServletRequest.getMethod();
// 获取参数部分
String queryString = httpServletRequest.getQueryString();
System.out.println(requestURL); // http://localhost:8080/demo01/Two
System.out.println(requestURI); // /demo01/Two
System.out.println(method); // GET
System.out.println(queryString); // username=admin&psd=&hobby=1&hobby=2
}
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");
// 设置响应的内容类型 doc => application/msword 访问时转为下载
res.setContentType("application/msword");
}
HttpServletResponse
1、
HttpServletResponse.sendRedirect()
// 重定向跳转
访问该Servlet时,重定向到 名为Two的Servlet中
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// ServletResponse 强转成 HttpServletResponse
HttpServletResponse httpServletResponse = (HttpServletResponse) res;
// 重定向跳转
httpServletResponse.sendRedirect("/demo01/Two");
}