1.getParameter与getRequestDispatcher
1.getParameter得到的都是String类型的。或者是用于读取提交的表单中的值,或者是某个表单提交过去的数据。getParameter()是获取POST/GET传递的参数值。
2.RequestDispatcher.forward()方法仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址。
2.代码
2.1 web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.he.servelt.requestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
2.2 jsp登录界面和跳转界面
2.2.1 登录界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<form action="/res/login" method="post">
密码:<input type="password" name="password"><br>
用户名:<input type="text" name="username"><br>
爱好:
<input type="checkbox" name="hobby" value="女孩"> 女孩
<input type="checkbox" name="hobby" value="代码"> 代码
<input type="checkbox" name="hobby" value="唱歌"> 唱歌
<input type="checkbox" name="hobby" value="电影"> 电影
<br>
<input type="submit">
</form>
</div>
</body>
</html>
2.2.2 跳转界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
2.3 实现跳转的核心Java代码
package com.he.servelt;
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;
public class requestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobby=req.getParameterValues("hobby");
System.out.println("======================================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobby));
System.out.println("======================================");
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}