Servlet之request和response
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet之request和response相关的知识,希望对你有一定的参考价值。
一、简介
web服务器收到客户端的Http请求后,会针对每一次请求,分别创建一个用于代表请求的request对象和代表响应的response对象。
request和response既然代表请求和响应,那么我们要获取客户端提交过来的数据,只需要找request对象就可以了,要向客户机输出数据,仅仅需要找response对象就行了。
Response对象
二、响应
响应行
public void setStatus(int sc)设置状态码
响应头:key:value的形式,一个key可以对应一个value,一个key可以对应多个value
设置头信息
public void setHeader(String name,String value) 一个key对应一个value,经常使用
public void setIntHeader(String name,int value)
public void setDateHeader(String name,long date)
public void addHeader(String name,tring value) 一个key对应多个value
public void addIntHeader(String name,int value)
public void addDateHeader(String name,long date)
响应体
public ServletOutputStream getOutputStream()throws IOException 字节输出流
public PrintWriter getWriter() throws IOException 字符输出流
三、response代码案例之重定向(登录页面)
登录页面的重定向
状态码是302 响应头是location
需求:登录页面,用户名和密码的登录页面,用户名和密码都是admin,如果有一个不是,重定向到登录页面,重新登录。
在webRoot下新建login.html
<!DOCTYPE html> <html> <head> <title>loginl.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="/day10/login" method="post"> <table> <tr> <td>用户名</td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td>密码</td> <td> <input type="password" name="password"/> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="登录"/> </td> </tr> </table> </form> </body> </html>
新建cn.servlet.LoginServlet类
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户名 String username = request.getParameter("username"); //获取密码 String password = request.getParameter("password"); if("admin".equals(username) && "admin".equals(password)){ //登录成功 response.setCharacterEncoding("utf-8"); response.getWriter().print("登录成功!"); }else{ //登录失败,重定向到登录页面 // 设置302的状态码 response.setStatus(302); // 设置地址 response.setHeader("location", "/day10/login.html"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
public void sendRedirect(String path) 可以完成重定向
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户名 String username = request.getParameter("username"); //获取密码 String password = request.getParameter("password"); if("admin".equals(username) && "admin".equals(password)){ //登录成功 response.setCharacterEncoding("utf-8"); response.getWriter().print("登录成功!"); }else{ //登录失败,重定向到登录页面 // 设置302的状态码 //response.setStatus(302); // 设置地址 //response.setHeader("location", "/day10/login.html"); response.sendRedirect("/day10/login.html"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml配置如下
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
四、response代码案例之页面定时刷新(页面读秒操作)
响应头 refresh
新建cn.servlet.RefreshServlet.java
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 页面的定时刷新 */ @SuppressWarnings("serial") public class RefreshServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().println("<h1>页面将在5秒后跳转</h1>"); //通过refresh头完成页面刷新 response.setHeader("refresh", "5;URL=/day10/login.html"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>RefreshServlet</servlet-name> <servlet-class>cn.servlet.RefreshServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RefreshServlet</servlet-name> <url-pattern>/refresh</url-pattern> </servlet-mapping> </web-app>
在webRoot下新建refresh.html
<!DOCTYPE html> <html> <head> <!-- 5秒后跳转 --> <meta charset="UTF-8"> <title>页面的定时跳转</title> <meta http-equiv="refresh" content="5;URL=/day10/login.html"/> </head> <body > <h2>页面将在<span id="spanId">5</span>秒后跳转</h2> </body> <script type="text/javascript"> /* 读秒操作 页面一加载,加载事件 onload 执行读秒的操作,每隔一秒变一次 使用js的定时器 */ window.onload = function(){ var x = 5; window.setInterval(function() { var span = document.getElementById("spanId"); span.innerHTML = x; x--; }, 1000) } </script> </html>
五、response代码案例之禁用浏览器缓存
应用:网银等
Cache-Control:no-cache
Expires:-1 值是日期类型
Pragma:no-Cache
新建cn.servlet.DateServlet
package cn.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 禁用浏览器缓存 */ @SuppressWarnings("serial") public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * Cache-Control : no-cache * Expires: -1 值是日期类型(setDateHeader()) * Pragma : no-cache */ //设置三个头信息 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", -1); response.setHeader("Pragma", "no-cache"); //向页面输出当前的事件 //获取当前的时间 Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = format.format(date); //输出 response.getWriter().println(str); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>DateServlet</servlet-name> <servlet-class>cn.servlet.DateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DateServlet</servlet-name> <url-pattern>/date</url-pattern> </servlet-mapping> </web-app>
六、response代码案例之中文输出问题
新建cn.servlet.OutServlet.java类
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class OutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printWriter(response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * 字符输出中文是否乱码 * 一定乱码 * response缓冲区的编码默认是ISO-8859-1 * 设置浏览器打开文件所采用的编码 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * @throws IOException * */ public void printWriter(HttpServletResponse response) throws IOException { response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getWriter().println("世界这么大 我想去看看"); } /** * 字节输出中文 * 输出“世界这么大 我想去看看”是否乱码? * 不一定乱码 * 解决办法: * 设置浏览器打开文件时所采用的编码 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * 获取字符串byte[]数组的编码和浏览器打开文件时候的编码相同 * "世界这么大 我想去看看".getBytes("utf-8"); * @throws IOException * */ public void printOutPutStream(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getOutputStream().write("世界这么大 我想去看看".getBytes("utf-8")); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>OutServlet</servlet-name> <servlet-class>cn.servlet.OutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OutServlet</servlet-name> <url-pattern>/out</url-pattern> </servlet-mapping> </web-app>
简写
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class OutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printWriter(response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * 字符输出中文是否乱码 * 一定乱码 * response缓冲区的编码默认是ISO-8859-1 * 设置浏览器打开文件所采用的编码 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * * 简写: * response.setContentType("text/html;charset=UTF-8"); * @throws IOException * */ public void printWriter(HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().println("世界这么大 我想去看看"); } /** * 字节输出中文 * 输出“世界这么大 我想去看看”是否乱码? * 不一定乱码 * 解决办法: * 设置浏览器打开文件时所采用的编码 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * 获取字符串byte[]数组的编码和浏览器打开文件时候的编码相同 * "世界这么大 我想去看看".getBytes("utf-8"); * @throws IOException * */ public void printOutPutStream(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getOutputStream().write("世界这么大 我想去看看".getBytes("utf-8")); } }
六、response代码案例之文件下载初级实现
超链接:浏览器可以解析直接打开
弹出下载窗口:
前提条件:先准备一个文件
读取文件,读取到输入流中,通过response输出到浏览器。
设置头信息:
Content-Disposition attachement;filename=文件名称
以附件的形式打开
新家cn.servlet.DownloadServlet.java类
package cn.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //先获取文件,读入输入流中 //获取文件的绝对磁盘路径 ServletContext context = this.getServletContext(); String path = context.getRealPath("/img/psb.jpg"); String filename = path.substring(path.lastIndexOf("/")+1); response.setHeader("Content-Disposition", "attachment;filename="+filename); InputStream is = new FileInputStream(path); OutputStream os = response.getOutputStream(); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b)) != -1){ os.write(b, 0, len); } is.close(); os.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>cn.servlet.DownloadServlet</servlet-class> </servlet> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app>
七、response代码案例之实现验证码
7.1验证码的热身
package cn.servlet; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 验证码的热身 */ @SuppressWarnings("serial") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在内存中生成图片 BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB); //获取画笔对象 Graphics g = image.getGraphics(); //设置颜色 g.setColor(Color.RED); //画矩形 g.drawRect(80, 80, 150, 100); g.setColor(Color.YELLOW); //定义字符串 String str = "abc"; g.drawString(str, 85, 85); //把内存中的图片输出的浏览器端 ImageIO.write(image, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>cn.servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping> </web-app>
7.2验证码的实现
package cn.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 验证码 */ @SuppressWarnings("serial") public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 在内存中生成图片(纸) ,没有设置背景颜色,画填充的矩形和纸的大小相同,并且矩形有颜色 * 获取画笔的对象(设置颜色、设置字体、画字符串、画矩形) * 先准备好数据,随机生成4个字符,把字符画到纸上 * 画干扰线 * 把内存中的图片输出的客户端 */ //在内存中生成图片 int width = 120; int height = 30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取画笔对象 Graphics2D g = (Graphics2D) image.getGraphics(); //设置灰色 g.setColor(Color.gray); //画填充的矩形 g.fillRect(0, 0, width, height); //设置颜色 g.setColor(Color.BLUE); //画边框 g.drawRect(0, 0, width-1, height-1); //准备数据 String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; //设置颜色 g.setColor(Color.YELLOW); //设置字体 g.setFont(new Font("隶书", Font.BOLD, 20)); Random random = new Random(); int x = 20; int y = 20; for (int i = 0; i < 4; i++) { /* * void rotate(double theta,double x,double y) * theta弧度 * 弧度 = 角度 *Math.PI / 180 * 获取正负30的角度 */ int jiaodu = random.nextInt(60) - 30; double hudu = jiaodu*Math.PI / 180 ; g.rotate(hudu, x, y); //获取下标 int index = random.nextInt(words.length()); //返回指定下标位置的字符,随机获取下标 char ch = words.charAt(index); //写字符串 g.drawString(""+ch, x, y); g.rotate(-hudu, x, y); x += 20; } g.setColor(Color.GREEN); int x1,x2,y1,y2; //画干扰线 for (int i = 0; i < 4; i++) { x1 = random.nextInt(width); y1 = random.nextInt(width); x2 = random.nextInt(width); y2 = random.nextInt(height); g.drawLine(x1, y1, x2, y2); } //把内存中的图片输出到客户端上 ImageIO.write(image,"jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>CheckCodeServlet</servlet-name> <servlet-class>cn.servlet.CheckCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckCodeServlet</servlet-name> <url-pattern>/checkCode</url-pattern> </servlet-mapping> </web-app>
Request对象
八、HttpServletRequest
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器的时候,HTTP强求中所有信息都封装在这个对象之中,开发人员通过这个对象的方法,可以获取客户的这心信息。
九、获取客户端的信息
public String getRemoteAddr() 获取IP地址
public String getMethod() 获取请求方法
public String getContextPath() 获取上下文路径(虚拟路径)
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RequestDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取IP String ip = request.getRemoteAddr(); System.out.println("客户机的IP是:"+ip); //获取请求的方法 String method = request.getMethod(); System.out.println("请求的方法是:"+method); //获取虚拟路径的名称 String contextPath = request.getContextPath(); System.out.println("虚拟路径的名称:"+contextPath); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>RequestDemo</servlet-name> <servlet-class>cn.servlet.RequestDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>RequestDemo</servlet-name> <url-pattern>/requestDemo1</url-pattern> </servlet-mapping> </web-app>
十、获取请求头的信息
public String getHeader(String name)
public long getDateHeader(String name)
public int getIntHeader(String name)
请求头:
referer 记住网页的来源
User-Agent 判断浏览器
if-modified-since 控制缓存
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RequestDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求头 //网页来源 防盗链 String referer = request.getHeader("referer"); System.out.println("网页来源于:"+referer); //判断浏览器 文件下载 String agent = request.getHeader("User-Agent"); System.out.println("浏览器版本:"+agent); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>RequestDemo2</servlet-name> <servlet-class>cn.servlet.RequestDemo2</servlet-class> </servlet> <servlet-mapping> <servlet-name>RequestDemo2</servlet-name> <url-pattern>/request2</url-pattern> </servlet-mapping> </web-app>
十一、获取请求参数
public String getParameter(String name)
public String[] getParameterValues(String name)
public Map getParameterMap()
public Enumeration getParameterNames()
register.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/day10/register" method="post"> <table> <tr> <td>输入姓名</td> <td> <input type="text" name="username"/> </td> </tr> <tr> <td>输入密码</td> <td> <input type="password" name="password"/> </td> </tr> <tr> <td>选择性别</td> <td> <input type="radio" name="sex" value="男"/>男 <input type="radio" name="sex" value="女"/>女 </td> </tr> <tr> <td>选择爱好</td> <td> <input type="checkbox" name="love" value="篮球"/>篮球 <input type="checkbox" name="love" value="足球"/>足球 <input type="checkbox" name="love" value="排球"/>排球 <input type="checkbox" name="love" value="乒乓球"/>乒乓球 </td> </tr> <tr> <td>选择城市</td> <td> <select name="city"> <option value="none">===请选择城市====</option> <option value="北京">北京</option> <option value="上海">上海</option> <option value="广州">广州</option> </select> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="注册"/> </td> </tr> </table> </form> </body> </html>
RegisterDemo.java
package cn.servlet; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RegisterDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String sex = request.getParameter("sex"); String[] love = request.getParameterValues("love"); String city = request.getParameter("city"); System.out.println("用户名:"+username+",密码:"+password+",性别:"+sex); for (int i = 0; i < love.length; i++) { System.out.println("爱好"+love[i]); } System.out.println("城市:"+city); System.out.println("==================="); //获取map集合 Map<String, String[]> parameterMap = request.getParameterMap(); //循环遍历 for(Iterator<String> keys = parameterMap.keySet().iterator();keys.hasNext();){ String key = keys.next(); String[] value = parameterMap.get(key); System.out.println("key:"+key+",value="+Arrays.toString(value)); } for(Iterator<Map.Entry<String,String[]>> iterator= parameterMap.entrySet().iterator();iterator.hasNext();){ Map.Entry<String, String[]> entry = iterator.next(); String key = entry.getKey(); String[] value = entry.getValue(); System.out.println("key:"+key+",value="+Arrays.toString(value)); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>RegisterDemo</servlet-name> <servlet-class>cn.servlet.RegisterDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterDemo</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping> </web-app>
十二、request获取中文乱码问题
POST请求乱码:request.setCharacterEncoding("utf-8");
GET请求乱码:
解决方案一:修改Tomcat/conf/server,xml
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>
必须有修改Tomcat服务器配置文件的权限
解决方案二:逆向编解码
username = URLEncoder.encode(username, "ISO-8859-1");
username = URLDecoder.decode(username, "utf-8");
解决方案三:简写形式
username = new String(username.getBytes("iso-8859-1"),"utf-8")
十三、利用请求域传递对象
public Object getAttribute(String name)
public void setAttribute(String name, Object o)
public void removeAttribute(String name)
十四、重定向和转发的区别
request对象提供了getRequestDispather方法,该方法返回一个RequestDispatcher对象,调用这个方法的forward方法可以实现请求转发,从而共享请求中的数据。
本文出自 “11831428” 博客,请务必保留此出处http://11841428.blog.51cto.com/11831428/1906302
以上是关于Servlet之request和response的主要内容,如果未能解决你的问题,请参考以下文章
javaweb学习路线-myeclipse的配置和Servlet之request和response
[Java拾遗四]JavaWeb基础之Servlet_Request&&Response