赞
踩
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
主要两个方法
req.getParameter();
req.getParameterValues();
示例:
登录页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/l">
账号:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
爱好:<input type="checkbox" name="hobby" value="jsp">jsp
<input type="checkbox" name="hobby" value="java">java
<input type="submit" value="登录">
</form>
</body>
</html>
这里的${pageContext.request.contextPath}
表示为绝对路径
需要依赖jsp的jar包
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>6.0.14</version>
</dependency>
处理登录的servlet
public class ServletDemo06 extends HelloServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); req.setCharacterEncoding("UTF-8"); //根据前台name属性获取数据 String username = req.getParameter("username"); String password = req.getParameter("password"); String [] hobby = req.getParameterValues("hobby"); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobby)); resp.sendRedirect("/index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
输入
结果
上述的servlet页面跳转使用的是重定向
我们也可以使用request的请求转发
只要将resp.sendRedirect("/index.jsp"); 替换成 req.getRequestDispatcher("/index.jsp").forward(req,resp);
在之前的文章里提到重定向和请求转发的主要区别在与地址栏
请求转发的时候,url不会产生变化 响应状态码为 307
重定向时候,url地址栏会发生变化 响应状态码为 302
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。