JavaWeb study notes 3: HttpServlet (Request & Response)

1-Servlet configuration essentials
  1. Match the full path
    > with a "/". Such as: / A, / aa / bb
    > localhost: 8080 / Project Name / aa / bb
  2. Path match, first half of the match
    > with a "/", but with "*" end. Such as: / A / *, / *
    > * is actually a wildcard, matches any character
    > localhost: 8080 / Project Name / aa / bb
  3. To extension matches
    > writing: start with "*." Such as: . Extension, . .Aa, * bb

ServletContext global parameters, similar to Java, is defined on the outside, as follows:

<!-- 定义全局参数 -->
<context-param>
	<param-name>favorite</param-name>
	<param-value>type and thinking</param-value>
</context-param>
2-ServletContext get the resource file (focus to test)

ServletContex What is the role?

  1. Get global configuration parameters
  2. Get web engineering resources
  3. Access data, field data objects shared among servlet

When ServletContext created when destroyed?

  1. Server startup, will be for each web application hosting to create a ServletContext object
  2. Managed removed from the server, or the server is shut down

ServletContext range of action: as long as the same project, you can take.
Q : A deposit project, why not take the B project? A : Different ServletContext object

There is not much BB, write directly on my previous blog post: Servlet reads the papers summary

3-ServletContext get the total number of successful login
  1. To provide information, be sure to visual interface, so write a html, to provide information form form
  2. getParameter method to get information, to write a Servlet, web.xml to configure and use objects to get information req
  3. Fill verify the information is correct, and print the results, specific code as follows:
    index.html in:
    <body>
    	<h2>请登录!</h2>
    	<form action="login" method="get">
    		账号:<input type="text" name="username">
    		密码:<input type="text" name="password">
    		<input type="submit" value="登录">
    	</form>
    </body>
    
    LoginServlet the doGet in:
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    if(username.equals("hpf")&&password.equals("123456")){
    	System.out.println("login success!");
    	resp.getWriter().write("login success!");
    }else{
    	System.out.println("login faild!");
    	resp.getWriter().write("login faild!");
    }
    
  4. To achieve a successful login Jump, you must first have a login_success.html, which provides a for obtaining the number of
  5. To get the number, you must also have a CountServlet. And, using the ServletContext to get the number, and print on the page
  6. Personal write code Summary and Precautions:

1.html associated with the Servlet, that form in the action contents of this form must be url-pattern web.xml configured
2. Each write a Servlet (except when selecting new Servlet), otherwise, be sure to manually web .xml configure
3.doGet the request and response objects doPost must make good use of the use of information here to get the page and jump
4.ServletContext can set properties, and reads the property, which is the key to get the number of times where
5.Servlet html path and the path is actually running in the same path, it is in the project directory, the same level

The following is an example of the complete code (full version):
index.html in:

<body>
	<h2>请登录!</h2>
	<form action="login" method="get">
		账号:<input type="text" name="username">
		密码:<input type="text" name="password">
		<input type="submit" value="登录">
	</form>
</body>

LoginServlet the doGet in:

ServletContext sc = getServletContext();
String username = req.getParameter("username");
String password = req.getParameter("password");
Object count = sc.getAttribute("count");
if(count==null){
	count = 1;
	sc.setAttribute("count", (int)count);
}else{
	sc.setAttribute("count",((int)count+1));
}
if(username.equals("hpf")&&password.equals("123456")){
	System.out.println("login success!");
	//设置状态码
	resp.setStatus(302);
	//定位跳转的位置是哪个页面
	resp.setHeader("Location", "loginSuccess.html");
}else{
	System.out.println("login faild!");
	resp.getWriter().write("login faild!");
}

During loginSuccess.html:

<body>
	<h1>congratulation!login success!</h1>
	<a href="count">点击获取登录成功的次数</a>
</body>

CountServlet the doGet in:

ServletContext sc = getServletContext();
int count = (int)sc.getAttribute("count");
resp.getWriter().write("count:"+count);
4-HttpServletRequest and Chinese garbage problem

Q: HttpServletRequest in the end what's the use? A: This object encapsulates the client submitted over all the data.

  1. You can obtain information about the client request header

    //得到一个枚举集合  
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
    	String name = (String) headerNames.nextElement();
    	String value = request.getHeader(name);
    	System.out.println(name+"="+value);
    }
    
  2. Obtain data submitted by the client over

    String name = request.getParameter("name");
    String address = request.getParameter("address");
    System.out.println("name="+name);
    System.out.println("address="+address);
    -------------------------------------------------
    //name=zhangsan&name=lisi&name=wangwu 一个key可以对应多个值。
    Map<String, String[]> map = request.getParameterMap();
    Set<String> keySet = map.keySet();
    Iterator<String> iterator = keySet.iterator();
    while (iterator.hasNext()) {
    	String key = (String) iterator.next();
    	System.out.println("key="+key + "--的值总数有:"+map.get(key).length);
    	String value = map.get(key)[0];
    	String value1 = map.get(key)[1];
    	String value2 = map.get(key)[2];
    	System.out.println(key+" ======= "+ value + "=" + value1 + "="+ value2);
    }
    //一般情况下,传过来的数据不可能是name=hpf&name=hillain,所以上面的value数组一般不写
    
  3. Gets Chinese data
    submitted by the client to the server data, if the data with the Chinese and garbled situation, you can refer to the following solutions
    1, if the GET method:

    //使用代码转码
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println("userName="+username+"==password="+password);
    //get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码
    //tomcat收到了这批数据,getParameter 默认使用ISO-8859-1去解码
    //先让文字回到ISO-8859-1对应的字节数组 , 然后再按utf-8组拼字符串
    username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
    System.out.println("userName="+username+"==password="+password);
    
    //可以在tomcat里面做设置处理,conf/server.xml加上URIEncoding="utf-8"
    //直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码
     <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
    

    2, if the POST method

    request.setCharacterEncoding("UTF-8"); //这行设置一定要写在getParameter之前
    请求体里面的文字编码get方式,用这行,有用吗? ---> 没用
    

Garbled on the use of lead to get the ISO-8859-1 Why need to solve, see the figure to know:
get garbled explanation

5-HttpServletResponse and Chinese garbage problem

Q: HttpServletResponse in the end what's the use? A: This object is responsible for returning data to the client.

//以字符流的方式写数据	
//response.getWriter().write("<b>hello response...</b>");
//以字节流的方式写数据 
response.getOutputStream().write("hello response2222...".getBytes());

There are Chinese response data, it is possible that Chinese garbled
detailed below 2 two situations arise and how to solve the Chinese garbled:

  1. Character stream output

    response.getWriter()
    //1. 指定输出到客户端的时候,这些文字使用UTF-8编码
    response.setCharacterEncoding("UTF-8");
    //2. 直接规定浏览器看这份数据的时候,使用什么编码来看
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.getWriter().write("这是个测试...");
    
  2. Output byte stream

    response.getOutputStream()
    //1. 指定浏览器看这份数据使用的码表
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    //2. 指定输出的中文用的码表
    response.getOutputStream().write("这是个测试...".getBytes("UTF-8"));
    
  3. Whether byte stream or character stream, a direct line of code on it

    response.setContentType("text/html;charset=UTF-8");
    
6-HttpServletResponse achieve download file

In fact, very simple to achieve, the easiest way to directly use the Tomcat available for download. That you write a html, to put up the file, run the Web, and then mouse click to download, but the download here will directly open, that is, if not the text, but the archive that kind of thing, is displayed directly garbled, so this approach is not desirable.
Let me talk about why we would not have to do anything you can achieve download, this is because there is a default Tomcat Servlet, which is DefaultServlet, the Servlet Tomcat server designed for use on top of static resources, that is, Html, Css such things.
Here's to achieve it manually using the Response to download the file:

  1. The first to write html, the href changed "Servlet name? Filename = filename. Format"
  2. Write a Servlet, first get the data, and then get the file path dialog box is set to download files, last used to save the stream
  3. Code is as follows:
    download.html:
    <body>
    	<h3>文件下载</h3>
    	<a href="test?filename=lqtzs.png">lqtzs.png</a>
    </body>
    
    HttpServletResponse:
    //1.获取下载的文件名字aa.jpg -- inputStream
    String fileName = req.getParameter("filename");
    //2.获取这个文件在tomcat里面的绝对路径地址
    String path = getServletContext().getRealPath(fileName);
    //让浏览器收到这份资源的时候,以下载的方式提醒用户,而不是直接显示
    resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
    //3.转换成输入法(若没有3,也有对话框,不过没法保存)
    InputStream is = new FileInputStream(path);
    OutputStream os = resp.getOutputStream();
    int len = 0;
    byte[] buffer = new byte[1024];
    while((len = is.read(buffer))!=-1){
    	os.write(buffer,0,len);
    }
    os.close();
    is.close();
    
7-Servlet comprehensive training

Comprehensive training - to achieve registration, save the data, jumps to log in and download the online
experience and summary:

  1. First of all, if you created a new Web project, and if you want to delete this project, be sure to go to work in this environment deleted
  2. getContextPath.getRealPath ( "filename") also applies to documents to be stored, the original does not exist
  3. Writer and OutputStream wording wording bit rusty, resp jump and refresh functions should continue to enhance learning
  4. resp.setContentType ( "text / html; charset = UTF-8"); Code Chinese distortion is very important to solve
  5. Because OutputStream to write our own definition of the file path, the path is equivalent to write the dead, so we should write in the download code resp.getOutputStream, in fact, well understood, is the output stream with the server response, the file output
  6. DETAILED Version1 complete code as follows:
    regist.html:
    <body>
    	<h3>请注册:</h3>
    	<form action="save" method="get">
    		账号:<input type="text" name="username"><br><br>
    		密码:<input type="password" name="password"><br><br>
    		昵称:<input type="text" name="nickname"><br><br>
    		<input type="submit" value="注册">
    	</form>
    </body>
    
    SaveServlet:
    ServletContext sc = getServletContext();
    //String realPath = sc.getContextPath();
    //System.out.println(realPath);	//测试路径
    //获得Map集合
    Map<String, String[]> pm = req.getParameterMap();
    Set<String> ks = pm.keySet();
    Iterator<String> iterator = ks.iterator();
    Writer os = new FileWriter(sc.getRealPath("user.properties"));
    while(iterator.hasNext()){
    	String key = iterator.next();
    	String value = pm.get(key)[0];
    	String parameter = new String(key+"="+value);
    	System.out.println();
    	System.out.printf(parameter);
    	os.write(parameter);
    	os.append("\n");
    }
    os.close();
    //设置跳转
    resp.setStatus(302);
    resp.setHeader("Location", "login.html");
    
    login.html:
    <body>
    	<h3>请登录:</h3>
    	<form action="login">
    		账号:<input type="text" name="username">
    		密码:<input type="password" name="password">
    		<input type="submit" value="登录">
    	</form>
    </body>
    
    LoginServlet:
    String username_req = req.getParameter("username");
    String password_req = req.getParameter("password");
    Properties ps = new Properties();
    ServletContext sc = getServletContext();
    InputStream is = sc.getResourceAsStream("user.properties");
    ps.load(is);
    String username_ps = ps.getProperty("username");
    String password_ps = ps.getProperty("password");
    resp.setContentType("text/html;charset=UTF-8");
    if(username_req.equals(username_ps)&&password_req.equals(password_ps)){
    	resp.setStatus(302);
    	resp.setHeader("Location", "download.html");
    }else{
    	resp.getWriter().write("账号密码输入错误!");
    	resp.setHeader("refresh", "3;login.html");
    }
    
    download.html:
    <body>
    	<h3>请选择合适文件下载</h3>
    	<a href="download?filename=lqtzs.png">lqtzs.png</a>
    </body>
    
    DownloadServlet:
    //1.获取下载的文件名字aa.jpg -- inputStream
    String fileName1 = req.getParameter("filename");
    System.out.println(fileName1);
    //2.获取文件名的时候,以防中文乱码也要转码
    fileName1 = new String(fileName1.getBytes("ISO-8859-1"),"UTF-8");
    System.out.println(fileName1);
    //3.获取这个文件在tomcat里面的绝对路径地址
    String path = getServletContext().getRealPath(fileName1);
    /*4.如果文件的名字带有中文,那么要对这个文件名进行编码处理
    如果是IE或者Chrome,使用URLEncoding编码
    如果是Firefox,使用Base64编码*/
    String ua = req.getHeader("User-Agent");
    if(ua.contains("Firefox")){
    	fileName1 = DownloadUtil.base64EncodeFileName(fileName1);
    }else{
    	fileName1 = URLEncoder.encode(fileName1, "UTF-8");
    }
    //5.让浏览器收到这份资源的时候,以下载的方式提醒用户,而不是直接显示
    resp.setHeader("Content-Disposition", "attachment; filename="+fileName1);
    InputStream is = new FileInputStream(path);
    OutputStream os = resp.getOutputStream();
    byte[] bytes = new byte[1024];
    int len = -1;
    while((len = is.read(bytes))!=-1){
    	os.write(bytes, 0, len);;
    }
    os.close();
    is.close();
    
HPF- self-summary

  I think the focus of this section is to deal with Chinese garbled as well as an idea of the connection between Html and Servlet, because the response and request, in fact, with the use of the will. The difficulty might be using the operating input and output streams, because before I made a mistake, when DownloadServlet writing, Outputstream no use resp.getOutputStream, but to hand new one, ha ha ha, with predictable results.
  This is a blog note, if you can help people, then it is better ha ha ha. Last but not least, study and meditation is similar, there must be a perseverance.

Published 15 original articles · won praise 18 · views 4576

Guess you like

Origin blog.csdn.net/oZuoShen123/article/details/105061015