Servelt接口 示例——8.13_17

本文介绍了Servlet的生命周期,包括init(), service(), 和destroy()方法。讲解了URL编码中的特殊字符转换,如%20、%2B等,并提到了前端js的encodeURIComponent()方法和Java中的URLDecoder与URLEncoder类。还分享了如何编写处理POST和GET请求的Servlet,并给出了相关示例链接。" 139604014,1495135,修复VTK CubeAxesActor刻度线与网格线分离问题,"['VTK', '3D渲染', '图形学']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1、servlet的生命周期
2、eclipse-tomcat-部署web项目
3、发送post和get的区别
4、写2个servlet,一个是接受post请求,一个是接收get请求
5、按照U8给的例子,写一个接口,有2种请求方式
5.1、第一种请求用html请求
5.2、第二种请求用java请求

 

servelt:https://blog.youkuaiyun.com/qq_19782019/article/details/80292110

            https://blog.youkuaiyun.com/qishubiao/article/details/78166836

中文乱码问题:https://blog.youkuaiyun.com/qishubiao/article/details/78166836

特殊字符问题:https://blog.youkuaiyun.com/hejisan/article/details/51786969

post和get的区别:https://baijiahao.baidu.com/s?id=1626599028653203490&wfr=spider&for=pc

            Servlet 生命周期可被定义为从创建直到毁灭的整个过程。以下是 Servlet 遵循的过程:
                Servlet 通过调用 init () 方法进行初始化。
                Servlet 调用 service() 方法来处理客户端的请求。
                Servlet 通过调用 destroy() 方法终止(结束)。
                最后,Servlet 是由 JVM 的垃圾回收器进行垃圾回收的。
                
            +  URL 中+号表示空格        %2B
            空格 URL中的空格可以用+号或者编码    %20
            /  分隔目录和子目录            %2F
            ?  分隔实际的 URL 和参数        %3F
            %  指定特殊字符                %25
            #  表示书签                %23
            &  URL 中指定的参数间的分隔符    %26
            =  URL 中指定参数的值        %3D

前端处理:在js中可以用  encodeURIComponent()方法来处理   处理不了  "(%22交给后台)(可以使用字符串拼接);

java中只有 java.net.URLDecoder和java.net.URLEncoder  可以自己编写一个encodeURIComponent()来实现

https://blog.youkuaiyun.com/KokJuis/article/details/84140514

         

 

Servelt代码:

package com.highgo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class ServletDemo1
 */
@WebServlet("/ServletTrue")
public class ServletTrue extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletTrue() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());

		response.setContentType("text/html;charset=utf-8");
		
		
		//		String strA = request.getParameter("name");
		//		StringBuffer strA = request.getRequestURL();
		//		String	strA = request.getRequestURI();

		String from_account = null;
		String app_key = null;
		String app_secret = null;  
		String aa = request.getRequestURI();
		System.out.println(aa);

		from_account = request.getParameter("from_account");
		System.out.println(from_account);
		app_key = request.getParameter("app_key");
		System.out.println(app_key);
		app_secret = request.getParameter("app_secret");
		System.out.println(app_secret);
		
		JSONArray jsonArray = new JSONArray();
			if(from_account !=  ""  && app_key != "" && app_secret != ""
				&&	from_account !=  null  && app_key != null && app_secret != null	) {

				jsonArray.add("errcode:0");
				jsonArray.add("errmsg:success");
				jsonArray.add("from_account:" + from_account);
				jsonArray.add("appKey:" + app_key);
				jsonArray.add("id:" + app_secret);
//				jsonArray.add("expiresIn:7200");
//				jsonArray.add("id:77397c50398f49aaa3513b71d34ec437");
				System.out.println("DOPOST+++++++True");

				PrintWriter out = response.getWriter();
				//	        out.print("True+++++++");
				out.print(jsonArray);
				out.flush();
				out.close();
		}  else {
				jsonArray.add("errcode:2001");
				jsonArray.add("errmsg:error");

				PrintWriter out = response.getWriter();
				out.print(jsonArray);
				out.flush();
				out.close();
			}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		doGet(request, response);
	
//		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		String from_account = null;
		String app_key = null;
		String app_secret = null;  
		String aa = request.getRequestURI();
		System.out.println(aa);

		from_account = request.getParameter("from_account");
		System.out.println(from_account);
		app_key = request.getParameter("app_key");
		System.out.println(app_key);
		app_secret = request.getParameter("app_secret");
		System.out.println(app_secret);
		
		JSONArray jsonArray = new JSONArray();
			if(from_account !=  ""  && app_key != "" && app_secret != ""
				&&	from_account !=  null  && app_key != null && app_secret != null	) {

				jsonArray.add("errcode:0");
				jsonArray.add("errmsg:success");
				jsonArray.add("from_account:" + from_account);
				jsonArray.add("appKey:" + app_key);
				jsonArray.add("id:" + app_secret);
//				jsonArray.add("expiresIn:7200");
//				jsonArray.add("id:77397c50398f49aaa3513b71d34ec437");
				System.out.println("DOPOST+++++++True");

				PrintWriter out = response.getWriter();
				//	        out.print("True+++++++");
				out.print(jsonArray);
				out.flush();
				out.close();
		}  else {
				jsonArray.add("errcode:2001");
				jsonArray.add("errmsg:error");

				PrintWriter out = response.getWriter();
				out.print(jsonArray);
				out.flush();
				out.close();
			}

		
	}

	public void init() throws ServletException{

	}
	public void destroy() {
		super.destroy();
	}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<script type="text/javascript" src="js/onclickTF.js"></script>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
</head>
<body>
<div>

    <div style="width:50%;padding:0;margin:0;float:left;box-sizing:border-box;">
    <input type="submit" name="ButtonAibang" value="TRUE_GET" id="Button1" class="join-btn"
     onclick="true_get()"></div>     
	<div style="width:50%;padding:0;margin:0;float:left;box-sizing:border-box;">
    <input type="submit" name="ButtonBaidu" value="FALSE_GET" id="Button2" class="join-btn" 
    onclick="false_get()"></div>
    
    <div style="width:50%;padding:0;margin:0;float:left;box-sizing:border-box;">
    <input type="submit" name="ButtonAibang" value="TRUE_POST" id="Button1" class="join-btn"
     onclick="true_post()"></div>     
	<div style="width:50%;padding:0;margin:0;float:left;box-sizing:border-box;">
    <input type="submit" name="ButtonBaidu" value="FALSE_POST" id="Button2" class="join-btn" 
    onclick="false_post()"></div>

<div id="content" style="height:200px;width:400px;float:left;"></div>

</div>

</body>
</html>




function true_post(){
	$.ajax({       
		type:"POST",        
		url:"ServletTrue",       
//		dataType:"json",    
		data : {
			from_account:"FromAccount",
			app_key:"APPKEY",
			app_secret:"APPSECRET中文",
	},
		success:function(data){
			console.log(data);
			var jsonFormat = formatJson(data);
			$('#content').html(jsonFormat);
		},
	     });
	
}
function false_post(){
	$.ajax({       
		type:"POST",        
		url:"ServletTrue",       
//		dataType:"json",    
		data : {
			from_account:"FromAccount",
			app_key:"APPKEY中文",
//			app_secret:"APPSECRET",
	},
		success:function(data){
			console.log(data);
			var jsonFormat = formatJson(data);
			$('#content').html(jsonFormat);
		},
	     });
	
}



function true_get() 
{ 
$.ajax({       
	
	type:"GET",        
	url:"ServletTrue?from_account=FromAccount&app_key=APPKEY&app_secret=APPSECRET中文",       
	success:function(data){
		console.log(data);
		var jsonFormat = formatJson(data);
		$('#content').html(jsonFormat);
	},
     });

}



function false_get() 
{ 
	$.ajax({       
		type:"GET",        
		url:"ServletTrue?ServletTrue?from_account=FromAccount&app_key=APPKEY&app_secret=",       
		success:function(data){
			console.log(data);
			var jsonFormat = formatJson(data);
			$('#content').html(jsonFormat);
		},
	     });

}

//工具方法

var formatJson = function(json, options) {
                 var reg = null,
                     formatted = '',
                     pad = 0,
                     PADDING = '    '; // one can also use '\t' or a different number of spaces
                 // optional settings
                 options = options || {};
                 // remove newline where '{' or '[' follows ':'
                 options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
                 // use a space after a colon
                 options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
                 // begin formatting...
                 // make sure we start with the JSON as a string
                 if (typeof json !== 'string') {
                     json = JSON.stringify(json);
                 }
                 // parse and stringify in order to remove extra whitespace
                 json = JSON.parse(json);
                 json = JSON.stringify(json);
                 // add newline before and after curly braces
                 reg = /([\{\}])/g;
                 json = json.replace(reg, '\r\n$1\r\n');
                 // add newline before and after square brackets
                 reg = /([\[\]])/g;
                 json = json.replace(reg, '\r\n$1\r\n');
                 // add newline after comma
                 reg = /(\,)/g;
                 json = json.replace(reg, '$1\r\n');
                 // remove multiple newlines
                 reg = /(\r\n\r\n)/g;
                 json = json.replace(reg, '\r\n');
                 // remove newlines before commas
                 reg = /\r\n\,/g;
                 json = json.replace(reg, ',');
                 // optional formatting...
                 if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                     reg = /\:\r\n\{/g;
                     json = json.replace(reg, ':{');
                     reg = /\:\r\n\[/g;
                     json = json.replace(reg, ':[');
                 }
                 if (options.spaceAfterColon) {
                     reg = /\:/g;
                     json = json.replace(reg, ': ');
                 }
                 $.each(json.split('\r\n'), function(index, node) {
                     var i = 0,
                         indent = 0,
                         padding = '';
                     if (node.match(/\{$/) || node.match(/\[$/)) {
                         indent = 1;
                     } else if (node.match(/\}/) || node.match(/\]/)) {
                         if (pad !== 0) {
                             pad -= 1;
                         }
                     } else {
                         indent = 0;
                     }
                     for (i = 0; i < pad; i++) {
                        padding += PADDING;
                     }
                    formatted += padding + node + '\r\n';
                     pad += indent;
                 });
                 return formatted;
             };

                       

 

package com.highgo.httpURLConn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();
        }

        return result;
    }

    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            os = connection.getOutputStream();
            os.write(param.getBytes());
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();
        }
        return result;
    }
}


package com.highgo.httpURLConn;

public class MainURL {
	public static void main(String[] args) {
//		String httpurl = "http://localhost:8080/Serverlt/ServletTrue?"
//				+ "from_account=FromAccount"
//				+ "&app_key=APPKEY"
//				+ "&app_secret=%2525中文";
//		String result = HttpClient.doGet(httpurl);
//		System.out.println(result);
		
		String param =  "from_account=FromAccount"
				+ "&app_key=APPKEY"
				+ "&app_secret=%2525中文";
		String httpurl = "http://localhost:8080/Serverlt/ServletTrue";
		String result = HttpClient.doPost(httpurl, param);
		System.out.println(result);
		System.out.println(param);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值