我正在Dynamic Web项目中使用Eclipse Java EE IDE。 运行我的servlet“ Controleur2”后,会发生此错误:
ERROR HTTP 500
javax.servlet.ServletException: L''exécution de la servlet a lancé une exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
cause mère
java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpUriRequest
servlets.ControleurForm.doPost(ControleurForm.java:44)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
cause mère
java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpUriRequest
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
servlets.ControleurForm.doPost(ControleurForm.java:44)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
这是我的servlet:
Controleur2
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Controleur2
*/
@WebServlet("/Controleur2")
public class Controleur2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Controleur2() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setAttribute("orga","salut");
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
ControleurForm
package servlets;
import java.io.IOException;
import java.util.Map;
import org.apache.http.client.methods.HttpUriRequest;
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 dataPackage.Data;
import dataPackage.Model;
/**
* Servlet implementation class ControleurForm
*/
@WebServlet("/ControleurForm")
public class ControleurForm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ControleurForm() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String orga = request.getParameter("orga"); //lecture des données fournies par l'utilisateur
Data data = new Data("2018-10-04","2018-10-05","ELECTRICITE DE France","0fe13821-9014-4cc5-a5f9-469a5a04b2e9"); //création de l'objet Data en fonction
Map<String, Object> map = data.getData(); //appel de la méthode pour récupérer la réponse
request.setAttribute("datamap",map);
this.getServletContext().getRequestDispatcher("/charts.jsp").forward(request, response);
}
}
这是我的JSP文件:
索引
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>StatsAPIViewer</title>
</head>
<body>
<p>Ceci est une page générée depuis une JSP.</p>
<% String attribut = (String) request.getAttribute("orga");
out.println(attribut);%>
<form method="post" action="controleurform">
<p>
<label for="orga">API :</label><br />
<select name="orga" id="orga">
<option value="ELECTRICITE">ELECTRICITE</option>
<option value="ELECTRICITEOA">ELECTRICITEOA</option>
</select>
</p>
<input type="submit" value="Envoyer" />
</form>
</body>
</html>
图表
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Your chart</title>
</head>
<body>
Page de graphes
<p>
<%
String attribut2 = (String) request.getAttribute("data");
out.println( attribut2 );
%></p>
</body>
</html>
这是我的java类:
数据类
package dataPackage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class Data {
private String from;
private String to;
private String orga;
private String client;
public Data(String pFrom, String pTo, String pOrga, String pClient) {
from = pFrom;
to = pTo;
orga = pOrga;
client = pClient;
}
public Map<String, Object> getData() throws IOException {
Map<String, Object> mapApp = null;
String organization = URLEncoder.encode(this.orga, "UTF-8");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
System.setProperty("jsse.enableSNIExtension", "false");
final String url = "https://vespa-prd-api1-gmg.rte-france.com/api/portal/v1.3/metrics/reports/api/summary/0?from="+ this.from+"T22%3A00%3A00Z&to="+this.to+"T13%3A23%3A58Z&organization="+organization+"&client="+this.client+"&reportsubtype=trafficAll";
final HttpGet get = new HttpGet(url);
get.addHeader("Authorization", "Basic YXBpYWRtaW46Y2hhbmdlbWU=");
//System.out.println("here");
//System.out.println(get);
try (final CloseableHttpResponse response = httpClient.execute(get)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("Erreur : "+response.getStatusLine().getStatusCode());
}
String jsonResponse = EntityUtils.toString(response.getEntity());
ObjectMapper objectmapper = new ObjectMapper();
ArrayList<Object> jsonList = objectmapper.readValue(jsonResponse,ArrayList.class);
//System.out.println(jsonList);
//JSON PARSER
final GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.disableHtmlEscaping();
builder.serializeNulls();
builder.setLenient();
final Gson gson = builder.create();
ArrayList<Object> listFailures = new ArrayList<>();
ArrayList<Object> listTime = new ArrayList<>();
ArrayList<Object> listSuccesses = new ArrayList<>();
ArrayList<Object> listExceptions = new ArrayList<>();
ArrayList<Object> listNumMessages = new ArrayList<>();
for(Object truc : jsonList) {
String jsonInString = gson.toJson(truc); /**on force à ce qu'il soit reconnu comme json */
mapApp = gson.fromJson(jsonInString, new TypeToken<Map<String, Object>>() {}.getType()); //on l'insère dans une map
//mapApp.forEach((x,y)-> System.out.println("key : " + x + " , value : " + y));
//System.out.println(mapApp.get("totalNumMessages"));
listFailures.add(mapApp.get("totalFailures")); //on ajoute la donnée voulue dans la liste
listTime.add(mapApp.get("totalProcessingTimeAvg"));
listTime.add(mapApp.get("totalNumMessages"));
listSuccesses.add(mapApp.get("totalSuccesses"));
listExceptions.add(mapApp.get("totalExceptions"));
listNumMessages.add(mapApp.get("totalNumMessages"));
}
}
catch (IOException e) {
System.out.println(e);
}
}
return mapApp;
}
public static double sumData(ArrayList<Object> list) {
double somme=0;
for (Object objet : list) {
somme = somme + Double.parseDouble(objet.toString());
}
return somme;
}
public static double sumTime(ArrayList<Object> list) {
double somme=0;
int n = list.size();
for (int i=0; i<(n-1); i++) {
i=i+1;
somme = somme + (Double.parseDouble(list.get(i-1).toString())*(Double.parseDouble(list.get(i).toString())));
}
double moy = somme/(n/2);
return moy;
}
public static Map<String, Object> getTimeline(String from, String to, String orga, String client) throws IOException {
Map<String, Object> mapApp = null;
String organization = URLEncoder.encode(orga, "UTF-8");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
System.setProperty("jsse.enableSNIExtension", "false");
final String url;
if (client == null) {
url = "https://vespa-prd-api1-gmg.rte-france.com/api/portal/v1.3/metrics/reports/app/timeline/0/numMessages?from="+from+"T22%3A00%3A00Z&to="+to+"T14%3A46%3A58Z&organization="+organization+"&reportsubtype=trafficAll";
}
else {
url = "https://vespa-prd-api1-gmg.rte-france.com/api/portal/v1.3/metrics/reports/app/timeline/0/numMessages?from="+from+"T22%3A00%3A00Z&to="+to+"T14%3A46%3A58Z&organization="+orga+"&client="+client+"&reportsubtype=trafficAll";
}
final HttpGet get = new HttpGet(url);
get.addHeader("Authorization", "Basic YXBpYWRtaW46Y2hhbmdlbWU=");
try (final CloseableHttpResponse response = httpClient.execute(get)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("Erreur : "+response.getStatusLine().getStatusCode());
}
String jsonResponse = EntityUtils.toString(response.getEntity());
ObjectMapper objectmapper = new ObjectMapper();
objectmapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
ArrayList<Object> jsonList = objectmapper.readValue(jsonResponse,ArrayList.class);
//JSON PARSER
final GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.disableHtmlEscaping();
builder.serializeNulls();
builder.setLenient();
final Gson gson = builder.create();
ArrayList<Object> listData= new ArrayList<>();
for(Object truc : jsonList) {
String jsonInString = gson.toJson(truc);
mapApp = gson.fromJson(jsonInString, new TypeToken<Map<String, Object>>() {}.getType()); //on l'insère dans une map
//mapApp.forEach((x,y)-> System.out.println("key : " + x + " , value : " + y));
String jsonSeries = gson.toJson(mapApp.get("series"));
ArrayList<Object> jsonList2 = objectmapper.readValue(jsonSeries, ArrayList.class);
for (Object truc2 : jsonList2) {
String jsonString = gson.toJson(truc2);
Map<String, Object> mapApp2 = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType());
//mapApp2.forEach((x, y) -> System.out.println("key : " + x + " , value : " + y));
listData.add(mapApp2.get("data"));
}
}
//System.out.println(listData);
}
}
return mapApp;
}
}
这是我的类路径文件(由Eclipse自动生成):
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_181">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0 (2)">
<attributes>
<attribute name="owner.project.facets" value="jst.web"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/gson-2.6.2.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/gson-2.8.5-javadoc.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/jackson-annotations-2.6.0.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/jackson-core-2.6.3.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/jackson-databind-2.6.3.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/jackson-dataformat-csv-2.1.2.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/commons-codec-1.10.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/commons-logging-1.2.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/fluent-hc-4.5.6.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/httpclient-4.5.6.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/httpclient-cache-4.5.6.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/httpclient-win-4.5.6.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/httpcore-4.4.10.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/httpmime-4.5.6.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/jna-4.4.0.jar"/>
<classpathentry kind="lib" path="C:/Users/piriouame/eclipse-workspace/lib/httpcomponents-client-4.5.6/lib/jna-platform-4.4.0.jar"/>
<classpathentry kind="output" path="WebContent/WEB-INF/classes"/>
</classpath>
在此先感谢您的帮助:)
答案 0 :(得分:1)
请确保将Apache httpclient
lib加载到您的类路径中。如果您使用的是maven / gradle,请检查是否已在其中添加了给定的lib。
答案 1 :(得分:0)
即使我添加了 httpclient ,使用 keycloak-quickstarts \ app-springboot 时我也遇到了同样的问题:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
<!-- <scope>test</scope> -->
</dependency>
所以我刚刚评论了<scope>test</scope>
这行,并且效果很好。