#java #session #servlets #chatbot #init
#java #сеанс #сервлеты #чат-бот #инициализация
Вопрос:
Я создаю чат-бота для Java-приложения с помощью Watson Assistant, кода сервлета:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String sessionIdOut = "";
String question = req.getParameter("message");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apikey>").build();
Assistant service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantid>";
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
// Suppress log messages in stdout.
LogManager.getLogManager().reset();
// Initialize with an empty value to start the conversation.
String inputText = question;
// Send message to assistant.
MessageInput input = new MessageInput.Builder().text(inputText).build();
MessageOptions messageOptions = new MessageOptions.Builder(assistantId, sessionId)
.input(input)
.build();
MessageResponse response = service.message(messageOptions).execute();
// Print the output from the dialog if any. Assumes a single text response.
List<DialogRuntimeResponseGeneric> responseGeneric = response.getOutput().getGeneric();
if(responseGeneric.size() > 0) {
System.out.println(response.getOutput()/*.getGeneric().get(0).getText()*/);
String answer = response.getOutput().getGeneric().get(0).getText();
// set up the response
res.setContentType("text/html");
res.setHeader("Cache-Control", "no-cache");
// write out the response string
res.getWriter( ).write(answer);
}
// Prompt for next round of input.
System.out.print(">> ");
}
В настоящее время сервлет всегда создает новый сеанс и настраивает помощника, когда поступает запрос GET из пользовательского интерфейса. Я хочу, чтобы он создавал новый сеанс и настраивал службу помощника только один раз при запуске сервера.
Попытался решить проблему, добавив функцию init () и написав код создания сеанса и настройки помощника внутри этой функции init () следующим образом:
@Override
public void init() throws ServletException {
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apikey>").build();
Assistant service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantid>";
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
super.init();
}
Но это не работает, когда я пишу вопрос в пользовательском интерфейсе, он отправляет мне обратно код состояния 500.
Комментарии:
1. вам нужно объявить сеанс SessionResponse на уровне класса, и если вы хотите, чтобы сеанс создавался при загрузке приложения, вам нужно определить load-on-startup любое положительное значение no в web.xml
Ответ №1:
Я решил проблему!
Рабочий код выглядит следующим образом:
package com.jtypebot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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 javax.servlet.http.HttpSession;
import com.ibm.watson.developer_cloud.assistant.v2.Assistant;
import com.ibm.watson.developer_cloud.assistant.v2.model.CreateSessionOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.DeleteSessionOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.DialogRuntimeResponseGeneric;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageInput;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageOptions;
import com.ibm.watson.developer_cloud.assistant.v2.model.MessageResponse;
import com.ibm.watson.developer_cloud.assistant.v2.model.RuntimeIntent;
import com.ibm.watson.developer_cloud.assistant.v2.model.SessionResponse;
import com.ibm.watson.developer_cloud.service.security.IamOptions;
import java.util.List;
import java.util.logging.LogManager;
@WebServlet("/JtypeBot")
public class JtypeBot extends HttpServlet {
private static final long serialVersionUID = 1L;
String sessionId;
String assistantId;
Assistant service;
/**
* @see HttpServlet#HttpServlet()
*/
public JtypeBot() {
super();
}
@Override
public void init() throws ServletException {
super.init();
// Set up Assistant service.
IamOptions iamOptions = new IamOptions.Builder().apiKey("<apiKey>").build();
service = new Assistant("2018-09-20", iamOptions);
service.setEndPoint("https://gateway-lon.watsonplatform.net/assistant/api/");
assistantId = "<assistantId>"; // replace with assistant ID
// Create session.
CreateSessionOptions createSessionOptions = new CreateSessionOptions.Builder(assistantId).build();
SessionResponse session = service.createSession(createSessionOptions).execute();
sessionId = session.getSessionId();
System.out.print(sessionId);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String sessionIdOut = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String question = req.getParameter("message");
// Suppress log messages in stdout.
LogManager.getLogManager().reset();
// Initialize with empty value to start the conversation.
String inputText = question;
// Send message to assistant.
MessageInput input = new MessageInput.Builder().text(inputText).build();
MessageOptions messageOptions = new MessageOptions.Builder(assistantId, sessionId)
.input(input)
.build();
MessageResponse response = service.message(messageOptions).execute();
// Print the output from dialog, if any. Assumes a single text response.
List<DialogRuntimeResponseGeneric> responseGeneric = response.getOutput().getGeneric();
if(responseGeneric.size() > 0) {
System.out.println(response.getOutput()/*.getGeneric().get(0).getText()*/);
String answer = response.getOutput().getGeneric().get(0).getText();
// set up the response
res.setContentType("text/html");
res.setHeader("Cache-Control", "no-cache");
// write out the response string
res.getWriter( ).write(answer);
}
// Prompt for next round of input.
System.out.print(">> ");
}
}