标签:
一、Request 通过表单收集客户机数据
input的type属性:text,checkbox,hidden,password,radio,file.
<form action="/day9/servlet/requestDemo2" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"><br/> 性别:<input type="radio" name="gender" value="male">男 <input type="radio" name="gender" value="female">女<br/> 所在地:<select name="location"> <option value="shanghai">上海</option> <option value="henan">河南</option> <option value="beijing">北京</option> </select><br/> 爱好:<input type="checkbox" name="likes" value="sing">唱歌 <input type="checkbox" name="likes" value="tiaowu">跳舞 <input type="checkbox" name="likes" value="paobu">跑步 <input type="checkbox" name="likes" value="dushu">读书<br/> 备注:<textarea row="3" row="60" name="description" ></textarea><br/> 大头贴:<input type="file" name="imapge" ><br/> <input type="hidden" name="id" value="890"> <input type="submit" value="提交"> </form>
Java:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getParameter("username")); System.out.println(request.getParameter("password")); System.out.println(request.getParameter("gender")); System.out.println(request.getParameter("location")); String likes[]=request.getParameterValues("likes"); for(int i=0;likes!=null&&i<likes.length;i++){ System.out.println(likes[i]); } System.out.println(request.getParameter("description")); System.out.println(request.getParameter("id")); }
二、request乱码问题
//get 方式乱发解决问题 private void test1(HttpServletRequest request) throws UnsupportedEncodingException{ String username=request.getParameter("username"); username=new String(username.getBytes("iso8859-1"),"UTF-8"); System.out.println(username); } //post 方式乱码解决问题 private void test2(HttpServletRequest request) throws UnsupportedEncodingException{ request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); System.out.println(username); }
三、request请求转发
请求转发的特点:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="aaa"; request.setAttribute("data", data); request.getRequestDispatcher("/test.jsp").forward(request, response); }
String data = "rsl"; PrintWriter writer = response.getWriter(); writer.write(data); writer.close(); request.getRequestDispatcher("/index.jsp").forward(request, response);
多个转发,一定要记得转发一个,return;
String data = "rsl"; if(true){ request.getRequestDispatcher("/index.jsp").forward(request, response); return ;//解决只要加个return就可以 } request.getRequestDispatcher("/index.jsp").forward(request, response);
String data = "rsl"; PrintWriter writer = response.getWriter(); writer.write(data); request.getRequestDispatcher("/index.jsp").forward(request, response);
index.jsp 页面 并看不到 rs1.
标签:
原文地址:http://www.cnblogs.com/lyjs/p/4889667.html