• HttpServletRequest学习


    package cn.request;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Enumeration;
    import java.util.Map;
    
    import javax.servlet.Servlet;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.commons.beanutils.BeanUtils;
    
    import cn.response.com.ResDemo2;
    
    public class ReqDemo1 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    			test8(request,response);
    	}
    
    	//利用requset 设置请求头 referer 放盗链
    	private void test8(HttpServletRequest request, HttpServletResponse response) throws IOException {
    		String data = "aaaa";
    		String referer = request.getHeader("referer");
    		
    		if (referer == null || !referer.startsWith("http://localhost")) {
    			response.sendRedirect("/Test/index.jsp");  // 如果不是从我的网站来请求的资源,那就跳到主页, 然胡再在主页提供连接再回来请求
    		} else {
    			response.getWriter().print(data);
    		}
    	}
    
    	//跳转之前数据不能写给客户端     java.lang.IllegalStateException: Cannot forward after response has been committed
    	//forward会清空response中的数据
    	//请求转发特点: 1: 客户端只发送一次请求,而服务端会产生多个资源的调用 2:客户机地址栏没有变化
    				
    	private void test7(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    		String data = "aa";
    		PrintWriter pw = response.getWriter();
    		pw.write(data);
    		pw.close();
    		
    		request.getRequestDispatcher("/Test/index.jsp").forward(request, response);
    		
    	}
    
    	//request的请求转发   实现MVC框架的设计思想
    	private void test6(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		String data = "aaa";
    		HttpSession session = request.getSession();
    		session.setAttribute("data", data);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    
    
    	//解决中文乱码问题
    	private void test5(HttpServletRequest request) throws UnsupportedEncodingException {
    		/*request.setCharacterEncoding("UTF-8");  //只对post提交有效
    		String name = request.getParameter("name");
    		System.out.println("name = " + name);*/
    		
    		//手工解决都get post 都可以..   
    		String name = request.getParameter("name");
    		String myName = new String(name.getBytes("ISO-8859-1"),"UTF-8");
    		System.out.println("myName = " + myName);
    	}
    	
    	//利用request收集用户提交的数据
    	private void test4(HttpServletRequest request) {
    		String username = request.getParameter("username");
    		System.out.println("username = " + username);
    		
    		String password = request.getParameter("password");
    		System.out.println("password = " + password);
    		
    		String gender = request.getParameter("gender");
    		System.out.println("gender = " + gender);
    		
    		String address = request.getParameter("address");
    		System.out.println("address = " + address);
    		
    		String[] likes = request.getParameterValues("likes");
    		for (int i = 0; likes != null && i < likes.length; ++i) {
    			System.out.println("likes :" + likes[i]);
    		}
    		
    		String des = request.getParameter("des");
    		System.out.println("des = " + des);
    		
    		
    		String id = request.getParameter("id");
    		System.out.println("id = " + id);
    	}
    	
    	//获得请求数据
        private void test3(HttpServletRequest request) {
    		String name1 = request.getParameter("name");
    		
    		Enumeration<String> e = request.getParameterNames();
    		while (e.hasMoreElements()) {
    			String name = e.nextElement();
    			String value = request.getParameter(name);
    			System.out.println("name = " + name + " value = " + value);
    		}
    		String[] v = request.getParameterValues("name");
    		for (int i = 0; v != null && i < v.length; ++i) {
    			System.out.println(v[i]);
    		}
    		Map<String, String[]> entity = request.getParameterMap();
    		User u = new User();
    		//这样可以利用BeanUtils 简单操作
    		try {
    			BeanUtils.populate(u, entity);
    		} catch (IllegalAccessException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		} catch (InvocationTargetException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    	}
        
    	//获取请求头
    	private void test2(HttpServletRequest request) {
    		String headValue = request.getHeader("Accept-Encoding");
    		System.out.println(headValue);
    		
    		Enumeration<String> e = request.getHeaders("Accept-Encoding");
    		while (e.hasMoreElements()) {
    			String value = e.nextElement();
    			System.out.println(value);
    		}
    		
    		e = request.getHeaderNames();
    		while (e.hasMoreElements()) {
    			String name = e.nextElement();
    			String value = request.getHeader(name);
    			System.out.println("name = " + name + "   value = " + value);
    		}
    	}
    
    	//获得用户请求的URI和URL 可以实现用户权限的控制, 统计某个web资源被访问的次数
    	private void test1(HttpServletRequest request) {
    		System.out.println("URI : " + request.getRequestURI());
    		System.out.println("URL : " + request.getRequestURL());
    		http://localhost:8080/Test/ReqDemo1?name=gbx
    		System.out.println("查询参数: " + request.getQueryString());
    		System.out.println("IP :" + request.getRemoteAddr());
    		System.out.println("Port :" + request.getRemotePort());
    		System.out.println("Host :" + request.getRemoteHost());
    		System.out.println("客户机请求方式 :" + request.getMethod());
    	}
    
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    class User{
    	
    }
    

      

    这里是测试request手机数据时的jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
     <meta http-equiv="content-tyoe"  content="text/html; charset=UTF-8">
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
      </head>
      
      <body>
        	<form action="/Test/ReqDemo1" method="post">
        		用户名: <input type="text" name="username"> <br/>
        		密码: <input type="password" name="password"> <br/>
        		性别 : <input type="radio" name="gender" value="男"><br/>
        			  <input type="radio" name="gender" value="女"><br/>
        	           住址: <select name="address">
        	            <option value="bj">北京</option>
        	           	<option value="sd">山东</option>
        	          </select> <br/>
        	    
        	          爱好: <input type="checkbox" name="likes" value="bas">篮球
        	          <input type="checkbox" name="likes" value="sing">唱歌
        	          <input type="checkbox" name="likes" value="dance">跳舞
        	    	  <br/>
        	    	  <input type="hidden" name = "id" value="123"> <br/>
        	    	  
        	         简介:<textarea rows="6" cols="60" name="des"></textarea><br/>	  
        	         照片: <input type="file" name="image"><br/>
        	             
        	         <input type="submit" value="提交">
        	</form>
      </body>
      
    </html>
    

      

    利用Http头的referer 实现图片的防盗链, 不是本网张的不给显示

    jsp

     <body>
      		<img alt="" src="/Test/ImgServlet?filename=1.jpg">
      </body>
    

      

    Servlet

    package cn.request;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ImgServlet extends HttpServlet {
    
    	
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String referer = request.getParameter("referer");
    		//如果非法就不给资源
    		if (referer == null || !referer.startsWith("http://localhost")) {
    			return ;
    			
    		} else  {  //合法
    			String filename = request.getParameter("filename");
    			System.out.println(referer + " " + filename);
    			String path = this.getServletContext().getRealPath("/download/" + filename);
    			System.out.println("path : " + path);
    			InputStream in = new FileInputStream(path);
    			OutputStream out = response.getOutputStream();
    			int len = 0;
    			byte[] buf = new byte[1024];
    			while ((len = in.read(buf)) > 0){
    				out.write(buf, 0, len);
    			}
    		}
    	}
    
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

      

  • 相关阅读:
    适配器模式(Adapter)
    状态模式(State)
    观察者模式(Publish/Subscribe)
    建造者模式(Builder)
    数据库,知识点汇总
    数据库
    css样式大全
    遮罩层
    js数组冒泡
    js基本方法
  • 原文地址:https://www.cnblogs.com/E-star/p/3506808.html
Copyright © 2020-2023  润新知