• JavaWeb 后端 <三> 之 Response Request


    1. 响应对象 Response(重点:HTTP协议响应部分)

    查看 HttpServletResponse

    set是 有这个头 修改 没有添加一个新的 和 add 有点小区别

    案例:

    1.1 字节流向客户端输出中文数据 ServletOutputStream

    //字节流向客户端输出中文数据
    public class ResponseDemo1 extends HttpServlet {
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		test2(response);
    	}
    
    	//解决方案一:更改浏览器的码表(不建议)
    		//解决方案二(不建议):向客户端输出一个<meta>标签,模拟了响应消息头:<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>
    			//out.write("<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>".getBytes());
    		//解决方案三(建议):向客户端输出响应消息头:response.setHeader("Content-Type", "text/html;charset=UTF-8");
    		//解决方案四(建议):向客户端输出响应消息头response.setContentType("text/html;charset=UTF-8");
    		
    	
    	//字节流输出数据查UTF-8
    		private void test2(HttpServletResponse response) throws IOException {
    			String data = "不见了远处的青山";
    			response.setContentType("text/html;charset=UTF-8");
    			ServletOutputStream out = response.getOutputStream();
    			out.write(data.getBytes("UTF-8"));//默认情况下:浏览器是乱码的(他默认查GBK)
    		}
    	
    	//字节流输出数据查本地码表
    	private void test1(HttpServletResponse response) throws IOException {
    		String data = "不见了远处的青山";
    		ServletOutputStream out = response.getOutputStream();
    		out.write(data.getBytes());//String:  getBytes()查本地默认的码表GBK getBytes(String charset)查指定码表
    	}
    

    1.2  字符流输出中文数据 PrintWriter

    //字符流输出中文数据
    public class ResponseDemo2 extends HttpServlet {
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		String data = "幸福是什么呢";
    		//改变字符流查的码表,还能告知客户端用UTF-8进行解码
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		//HttpServletResponse的实例由Tomcat服务器提供,默认查ISO-8859-1的。
    		//Tomcat8.X ,默认编码就变为了UTF-8
    		
    		out.write(data);
    	}
    	
    	private void test1(HttpServletResponse response) throws IOException {
    		String data = "幸福是什么";
    		//改变字符流查的码表
    		response.setCharacterEncoding("UTF-8");
    		//告知客户端用UTF-8进行解码
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();//HttpServletResponse的实例由Tomcat服务器提供,默认查ISO-8859-1的。
    												//Tomcat8.X ,默认编码就变为了UTF-8
    		out.write(data);
    	}
    

    1.3 输出随机验证码图片:CAPTCHA图像

    //输出随机验证码图片:CAPTCHA图像
    public class ResponseDemo3 extends HttpServlet {
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		int width = 120;
    		int height = 25;
    		//创建一副内存图像
    		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    		//得到画笔
    		Graphics g = image.getGraphics();
    			//开始画
    			//边线
    			g.setColor(Color.BLUE);
    			g.drawRect(0, 0, width, height);
    			//填充背景色
    			g.setColor(Color.YELLOW);
    			g.fillRect(1, 1, width-2, height-2);
    			//话干扰线
    			g.setColor(Color.GRAY);
    			
    			Random r = new Random();
    			for(int i=0;i<9;i++)
    				g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
    			//验证码
    			g.setColor(Color.RED);
    			g.setFont(new Font("宋体", Font.ITALIC|Font.BOLD, 19));
    //			String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
    			int x = 20;
    			for(int i=0;i<4;i++){
    				g.drawString(r.nextInt(10)+"", x,20 );
    //				g.drawString(base.charAt(r.nextInt(base.length()))+"", x, 20);
    				x+=18;
    			}
    		//输出
    		response.setHeader("Expires", "-1");
    		response.setHeader("Cache-Control", "no-cache");
    		response.setHeader("Pragma", "no-cache");
    		ImageIO.write(image, "jpg", response.getOutputStream());
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

     html

    <body>
        <form action="" method="post">
        	用户名:<input type="text" name="username"/><br/>
        	密码:<input type="password" name="password"/><br/>
        	<input type="text" size="3" name="code"/><img id="img1" src="/day08_00_response/servlet/ResponseDemo3"/><a href="javascript:change()">看不清</a><br/>
        	<input type="submit" value="登录"/>
        </form>
        <script type="text/javascript">
        	function change(){
        		var imgObj = document.getElementById("img1");
        		imgObj.src="/day08_00_response/servlet/ResponseDemo3?time="+new Date().getTime();//浏览器发现地址没有变化,根本不发请求
        	}
        </script>
      </body>
    

    1.4 定时刷新  登陆跳转等待

    //控制客户端定时刷新
    public class ResponseDemo4 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		test2(response);
    	}
    	//定时刷新到别处
    	private void test2(HttpServletResponse response) throws IOException {
    		response.setContentType("text/htm;charset=UTF-8");
    		response.setHeader("Refresh", "2;URL=http://www.huyifan.cn");
    		response.getWriter().write("登录成功,2秒后跳转到主页");
    	}
    	//定时刷新自己
    	private void test1(HttpServletResponse response) throws IOException {
    		Random r = new Random();
    //		response.setHeader("Refresh", "1");
    		response.setIntHeader("Refresh", 1);
    		response.getWriter().write(r.nextInt()+"");
    	}
    

    1.5 控制缓存时间

    //控制缓存的时间
    //静态资源需要控制缓存时间
    //动态资源一般不要缓存
    public class ResponseDemo5 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String data = "不见了远处的青山";
    		//让他缓存1个小时
    		response.setDateHeader("Expires", System.currentTimeMillis()+1*60*60*1000);
    		response.setContentType("text/html;charset=UTF-8");
    		response.getWriter().write(data);
    	}
    

    1.6 请求重定向

    //演示请求重定向:可以重定向到任何地址上
    	//发出2次请求
    	//地址栏会发生变化
    public class ResponseDemo6 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.sendRedirect("http://www.huyifan.com");
    	}
    	//重定向到应用内的资源
    	private void test1(HttpServletResponse response) throws IOException {
    		//		response.setStatus(302);
    //		response.setHeader("Location", "/day08_00_response/servlet/ResponseDemo7");
    		response.sendRedirect("/day08_00_response/servlet/ResponseDemo7");
    	}
    
    public class ResponseDemo7 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.getWriter().write("I am yif");
    //		response.getOutputStream().write("a".getBytes());
    	}
    

    细节:

    1、字节流和字符流互斥,只能用其中一个。

    2、response的流用完之后自动关(服务器关)

    2. 请求对象 Request(重点:HTTP协议请求部分)

    2.1 HttpServletRequest对象的生命周期

    诞生:请求来了

    死亡:响应结束

    2.2 也是一个域(范围)对象:请求范围

    request

    Map

    setAttribute

    getAttribute

    removeAttribute‘

    2.2 开发中尽量用绝对路径

    绝对路径:要不要加应用名称

    地址给服务器用的:/就代表当前应用

    地址给客户端用的:/应用名demo

    2.3 HttpServletRequest中的常用方法

    public class RequestDemo1 extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String method = request.getMethod();//请求方式
            String uri = request.getRequestURI();//    /day08_01_request/servlet/RequestDemo1
            String url = request.getRequestURL().toString();//  http://localhost:8080/day08_01_request/servlet/RequestDemo1
            String protocal = request.getProtocol();//客户端使用的协议
            
            String remoteIp = request.getRemoteAddr();//来访者的ip
            int port = request.getRemotePort();// 随机的
            String queryString = request.getQueryString();//GET方式:/day08_01_request/servlet/RequestDemo1?username=abc&password=123
                                                    //username=abc&password=123
            System.out.println(method);
            System.out.println(uri);
            System.out.println(url);
            System.out.println(protocal);
            System.out.println(remoteIp);
            System.out.println(port);
            System.out.println(queryString);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    

    2.4 获取请求消息头

    public class RequestDemo2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		test3(request);
    	}
    	//得到所有的消息头
    	private void test3(HttpServletRequest request) {
    		Enumeration<String> e = request.getHeaderNames();
    		while(e.hasMoreElements()){
    			String headerName = e.nextElement();//透明称
    			Enumeration<String> headerValues = request.getHeaders(headerName);
    			while(headerValues.hasMoreElements()){
    				System.out.println(headerName+":"+headerValues.nextElement());
    			}
    		}
    		
    	}
    	//http协议是允许头有重复的情况,多个重名的头
    	private void test2(HttpServletRequest request) {
    		Enumeration<String> e = request.getHeaders("Accept-Encoding");//得到的头值
    		while(e.hasMoreElements()){
    			String headerValue = e.nextElement();
    			System.out.println(headerValue);
    		}
    		
    	}
    	//得到指定请求消息头的值。如果没有该头,返回null
    	private void test1(HttpServletRequest request) {
    		String supportEncoding = request.getHeader("Accept-Encoding");
    		if(supportEncoding.contains("gzip")){
    			System.out.println("支持gzip压缩");
    		}else{
    			System.out.println("不支持gzip压缩");
    		}
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    2.5 获取请求参数

    public class RequestDemo3 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		test8(request, response);
    	}
    	//终极解决方案:借助BeanUtil框架      jar包直接放在 web-inf 的 ;lib 文件夹里就ok
    	private void test8(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		User user = new User();
    		System.out.println("封装前:"+user);
    		try {
    			BeanUtils.populate(user, request.getParameterMap());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		System.out.println("封装后:"+user);
    	}
    	//getParameterMap获取参数:封装到JavaBean中
    	private void test7(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		//key:请求参数名 value:请求参数值数组
    		Map<String,String[]> map = request.getParameterMap();
    		User user = new User();
    		System.out.println("封装前:"+user);
    		for(Map.Entry<String, String[]> me:map.entrySet()){
    			String paramName = me.getKey();//参数名称
    			String paramValues[] = me.getValue();//参数值
    			try {
    				PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class);
    				Method m = pd.getWriteMethod();//setter方法
    				if(paramValues.length>1){
    					m.invoke(user, (Object)paramValues);//参考补充视频:反射main方法
    				}else{
    					m.invoke(user, paramValues);
    				}
    			} catch (Exception e1) {
    				e1.printStackTrace();
    			}
    		}
    		System.out.println("封装后:"+user);
    	}
    	//getParameterMap获取参数
    	private void test6(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		//key:请求参数名 value:请求参数值数组
    		Map<String,String[]> map = request.getParameterMap();
    		for(Map.Entry<String, String[]> me:map.entrySet()){
    			System.out.println(me.getKey()+"="+Arrays.asList(me.getValue()));
    		}
    	}
    	
    	//把请求参数的值封装到JavaBean中
    	//约定优于编码:表单的输入域的name取值和JavaBean中的属性(getter和setter方法)保持一致
    	private void test5(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		
    		
    		Enumeration<String> e = request.getParameterNames();//参数名
    		User user = new User();
    		System.out.println("封装前:"+user);
    		while(e.hasMoreElements()){
    			String paramName = e.nextElement();//即是JavaBean中的属性名称
    			String paramValue = request.getParameter(paramName);
    //			setUsername(paramValue); setPassword(paramValue);
    			//JavaBean的内省
    			try {
    				PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class);
    				Method m = pd.getWriteMethod();//setter方法
    				m.invoke(user, paramValue);
    			} catch (Exception e1) {
    				e1.printStackTrace();
    			}
    		}
    		System.out.println("封装后:"+user);
    	}	
    //	private void test4(HttpServletRequest request, HttpServletResponse response)
    //			throws ServletException, IOException {
    //		User user = new User();
    //		System.out.println("封装前:"+user);
    //		String username = request.getParameter("username");
    //		String password = request.getParameter("password");
    //		String gender = request.getParameter("gender");
    //		user.setUsername(username);
    //		user.setPassword(password);
    //		user.setGender(gender);
    //		System.out.println("封装后:"+user);
    //	}	
    	//以下内容只用简单的程序开发
    	
    	//获取所有的请求参数名和值
    	private void test3(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		Enumeration<String> e = request.getParameterNames();//参数名
    		while(e.hasMoreElements()){
    			String paramName = e.nextElement();
    			String values [] = request.getParameterValues(paramName);
    			System.out.println(paramName+"="+Arrays.asList(values));
    		}
    	}
    	//获取重名请求参数的值
    	private void test2(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String username = request.getParameter("username");//不区分get还是post的
    		String passwords[] = request.getParameterValues("password");//获取重名的请求参数值
    		System.out.println(username+":"+Arrays.asList(passwords));
    	}
    	//获取单一的请求参数的值(用户所有的输入都是String)
    	private void test1(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String username = request.getParameter("username");//不区分get还是post的
    		String password = request.getParameter("password");
    		System.out.println(username+":"+password);
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    domain

    public class User {
    	private String username;
    	private String password[];
    	private String gender;
    	public String getUsername() {//读属性,属性名称username
    		return username;
    	}
    	public void setUsername(String username) {//写属性,属性名username
    		this.username = username;
    	}
    	
    	public String[] getPassword() {
    		return password;
    	}
    	public void setPassword(String[] password) {
    		this.password = password;
    	}
    	public String getGender() {
    		return gender;
    	}
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    	@Override
    	public String toString() {
    		return "User [username=" + username + ", password="
    				+ Arrays.toString(password) + ", gender=" + gender + "]";
    	}
    	
    	
    }
    
    public class Student {
    	private int id;//BeanUtil对于基本类型自动转换
    	private String name;
    	private String password;
    	private String gender;
    	private boolean married;
    	private String[] hobby;
    	private String province;
    	private String description;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public String getGender() {
    		return gender;
    	}
    	public void setGender(String gender) {
    		this.gender = gender;
    	}
    	public boolean isMarried() {
    		return married;
    	}
    	public void setMarried(boolean married) {
    		this.married = married;
    	}
    	public String[] getHobby() {
    		return hobby;
    	}
    	public void setHobby(String[] hobby) {
    		this.hobby = hobby;
    	}
    	public String getProvince() {
    		return province;
    	}
    	public void setProvince(String province) {
    		this.province = province;
    	}
    	public String getDescription() {
    		return description;
    	}
    	public void setDescription(String description) {
    		this.description = description;
    	}
    	@Override
    	public String toString() {
    		return "Student [id=" + id + ", name=" + name + ", password="
    				+ password + ", gender=" + gender + ", married=" + married
    				+ ", hobby=" + Arrays.toString(hobby) + ", province="
    				+ province + ", description=" + description + "]";
    	}
    	
    }
    
    <form action="/day08_01_request/servlet/RequestDemo4" method="post">
        	用户名:<input type="text" name="username"/><br/>
        	密码:<input type="password" name="password"/><br/>
        	确认密码:<input type="password" name="password"/><br/>
    		性别:<input type="text" name="gender" value="male"/>
        	<input type="submit" value="注册"/>
        </form>
    

    2.4 以输入流的形式接收请求正文:POST

      一般情况下用不着,文件上传时使用。

    public class RequestDemo4 extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            ServletInputStream in = request.getInputStream();
            int len = -1;
            byte b[] = new byte[1024];
            while((len=in.read(b))!=-1){
                System.out.println(new String(b,0,len));
            }
            in.close();
        }
    

    2.5 获取常用表单输入域的值

     type:radio checkbox   ,如果用户一个都没有选,客户端是根本不会传参数到服务器的。

    public class RequestDemo5 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		test3(request,response);
    	}
    	//请求编码和响应编码没有关系
    	private void test3(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");//设置请求正文的编码。只对POST有效
    		Student s = new Student();
    		System.out.println("封装前:"+s);
    		try {
    			BeanUtils.populate(s, request.getParameterMap());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		
    		response.setContentType("text/html;charset=UTF-8");
    		
    		response.getWriter().write(s.toString());
    	}
    	
    	//get请求方式的编码问题
    	private void test2(HttpServletRequest request)
    			throws UnsupportedEncodingException {
    		String username = request.getParameter("name");//是二进制数据  %E6%9D%8E%E5%9B%9B
    		
    		byte b[] = username.getBytes("ISO-8859-1");
    		username = new String(b,"UTF-8");
    		
    		System.out.println(username);//二进制转为字符,用ISO-8859-1的
    		
    	}
    	//获取请求正文的参数乱码问题
    	private void test1(HttpServletRequest request)
    			throws UnsupportedEncodingException {
    		request.setCharacterEncoding("UTF-8");//设置请求正文的编码。只对POST有效
    		
    		Student s = new Student();
    		System.out.println("封装前:"+s);
    		try {
    			BeanUtils.populate(s, request.getParameterMap());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		System.out.println("封装后:"+s);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    <form action="/day08_01_request/servlet/RequestDemo5" method="post">
        	<input type="hidden" value="438" name="id"/>
        	<table border="1" width="438">
        		<tr>
        			<td>姓名</td>
        			<td>
        				<input type="text" name="name"/>
        			</td>
        		</tr>
        		<tr>
        			<td>密码</td>
        			<td>
        				<input type="password" name="password"/>
        			</td>
        		</tr>
        		<tr>
        			<td>性别</td>
        			<td>
        				<input type="radio" name="gender" value="male" checked="checked"/>男性
        				<input type="radio" name="gender" value="female"/>女性
        			</td>
        		</tr>
        		<tr>
        			<td>婚否</td>
        			<td>
        				<input type="checkbox" name="married"/>
        			</td>
        		</tr>
        		<tr>
        			<td>爱好</td>
        			<td>
        				<input type="checkbox" name="hobby" value="eat"/>吃饭
        				<input type="checkbox" name="hobby" value="sleep"/>睡觉
        				<input type="checkbox" name="hobby" value="java"/>学Java
        			</td>
        		</tr>
        		<tr>
        			<td>籍贯</td>
        			<td>
        				<select name="province">
        					<option value="BJ">北京</option>
        					<option value="SD">山东</option>
        					<option value="HB">湖北</option>
        				</select>
        			</td>
        		</tr>
        		<!-- 
        		<tr>
        			<td>靓照</td>
        			<td>
        				<input type="file" name="image"/>
        			</td>
        		</tr>
        		 -->
        		 <tr>
        			<td>简介</td>
        			<td>
        				<textarea rows="3" cols="38" name="description"></textarea>
        			</td>
        		</tr>
        		<tr>
        			<td colspan="2">
    <!--     				<input type="submit" value="注册"/> -->
    <!-- 					<input type="image" src="an-0333.gif"/> -->
    					<input type="button" value="注册" onclick="toSubmit()"/>
        			</td>
        		</tr>
        	</table>
        	<script type="text/javascript">
        		function toSubmit(){
        			//验证用户的输入
        			document.forms[0].submit();
        		}
        	</script>
        </form>
    

    编码:

     

    2.6 请求转发

    //转发:源
    //源和目标:共享请求范围中的数据
    public class RequestDemo6 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.setAttribute("p", "ppp");
    		//ServletContext:地址的写法。必须以"/",代表当前应用。(应用开头的绝对路径)
    //		RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/RequestDemo7");
    		//绝对路径
    //		RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo7");
    		//相对路径
    		RequestDispatcher rd = request.getRequestDispatcher("RequestDemo7");
    		rd.forward(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //转发:目标
    public class RequestDemo7 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String s = (String)request.getAttribute("p");//注意和getParameter没有关系
    		response.getWriter().write(s);
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    请求与重定向区别

     

    2.7 包含:源  服务器端行为

    public class RequestDemo8 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		response.getWriter().write("我喜欢");
    		RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo9");
    		rd.include(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    public class RequestDemo9 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		response.getWriter().write("成都");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    2.8 请求 和 包含 的小细节

    //转发前后,源输出的任何响应正文无效
    public class Forward1 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setHeader("Refresh", "1");
    		System.out.println("转发前");
    		response.getWriter().write("forward before");//转发前会清空响应对象中的正文内容
    		request.getRequestDispatcher("/servlet/Forward2").forward(request, response);//转发
    		System.out.println("转发后");
    		response.getWriter().write("forward after");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //转发:目标
    public class Forward2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.getWriter().write("222222");//响应结束
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //包含:源
    //只会包含目标的正文,头部信息包含前清空
    public class IncludeDemo1 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.getWriter().write("11111");
    		request.getRequestDispatcher("/servlet/IncludeDemo2").include(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //包含:目标
    public class IncludeDemo2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setIntHeader("Refresh", 1);
    		response.getWriter().write("22222");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    



  • 相关阅读:
    随机抽样一致性算法(RANSAC)
    RANSAC算法详解
    添加“返回顶部”小图标按钮的JS(JavaScript)代码详解
    vue-cli3组件嵌套
    vue-cli3文件的引入
    vue-cli3组件的使用
    vue ui 使用图形化界面
    vue-cli3及以上版本安装及创建项目
    NetTerm共享文件
    Gin框架配置静态文件static
  • 原文地址:https://www.cnblogs.com/loveincode/p/5170759.html
Copyright © 2020-2023  润新知