servlet之HttpServletRequest
1.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有信息会被封装HttpServletRequest的方法,获得客户端的所有信息
方法:
//获取前端参数,并且请求转发 req.getParameter();//常用 返回一个字符串 req.getParameterValues();//常用 返回一个数组(多个值) req.getParameterMap();//不用 req.getParameterNames();//不用
一个简单的表单提交:
package com.kuang.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; //@WebServlet(value="/login",loadOnStartup=1)//注解式路由 效果与web.xml配置一致 public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8");//设置编码 String username = req.getParameter("username"); String passsord = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("===================="); //后台接收中文乱码问题 System.out.println("username = "+username); System.out.println("psaaword = "+ passsord); System.out.println(Arrays.toString(hobbys)); System.out.println("===================="); //通过请求转发 //这里的 /代表当前web应用 req.getRequestDispatcher("/success.jsp").forward(req,resp); } }
web.xml
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.kuang.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> </head> <body> <h1>登录</h1> <div style="text-align: center"> <form action="${pageContext.request.contextPath}/login" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 爱好: <input type="checkbox" name="hobbys" value="女孩">女孩 <input type="checkbox" name="hobbys" value="代码">代码 <input type="checkbox" name="hobbys" value="唱歌">唱歌 <input type="checkbox" name="hobbys" value="电影">电影 <br> <input type="submit" name="提交" id=""> </form> </div> </body> </html>
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录成功</title> </head> <body> 登录成功 </body> </html>
请求转发和重定向的区别:
相同点:
页面都会跳转
不同点:
请求转发的时候,URL不会发生变化 307
重定向时候,URL地址栏会发生变化 302