I use the doGet method to get the parameter and then process it. When the reply is sent, it contains the status data. Also, when the second client connects, the answer contains the data from frist client.
I want the send new the data after the second client is connected. Reset buffer and send new data to second client the data, or after restoring the page send new data.
Its not working. The client retrieves the page again and sends me a old and new data. I need only new data to be sent to client.
class HttpTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HttpTest() {
super();
// TODO Auto-generated constructor stub
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println(request.getQueryString());
String[] parameters = request.getQueryString().split(";");
String out_data="";
/*
* algorithm for generate out data
*/
out.println(out_data);
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
try this might help
private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try (PrintWriter writer = response.getWriter()) {
System.out.println(request.getQueryString());
String[] parms = request.getQueryString().split(";");
String outData = "";
/*
* algorithm for generate out data
*/
writer.println(outData);
}
}
Related
I'm developing an application for sending bulk emails from multiple senders in a continuous loop. Sender email-ID's are stored in a csv file and I am reading that in ReadFile class and calling it in servlet class where I am also calling an email utility class which have email sending functions.
ReadFile.java
CsvReader senders;
public List<String> read(){
ArrayList<String> al=new ArrayList<String>();
try {
senders = new CsvReader("C:/Users/dc/Documents/Senderlist.csv");
senders.readHeaders();
while (senders.readRecord()) {
String SenderID = senders.get("SenderID");
// perform program logic here
System.out.println("Sender ID is: "+SenderID );
al.add(SenderID);
}
senders.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return al;
}
Servlet.java:
public class MailController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String ExchangeIP;
private String port;
ReadFile rf;
/**
* #throws IOException
* #see HttpServlet#HttpServlet()
*/
public MailController() throws IOException {
rf=new ReadFile();
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
ExchangeIP = context.getInitParameter("ExchangeIP");
port = context.getInitParameter("port");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
String resultMessage = ""; //null
try {
List sendersInput = rf.read();
// print all the elements in the list
Iterator itr = sendersInput.iterator();
while(itr.hasNext()) {
EmailUtility.sendEmail(ExchangeIP, port, itr.next(), recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail has been sent successfully";
}
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext()
.getRequestDispatcher("/Result.jsp")
.forward(request, response);
}
}
}
While running this I am getting an error:
java.lang.ClassNotFoundException: com.csvreader.CsvReader
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at com.project.util.ReadFile.read(ReadFile.java:20)
at com.project.controller.MailController.doPost(MailController.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
How to resolve this error.
You're missing the opencsv.jar library.
Specify it in your java command with
java -cp opencsv.jar:...
By adding servlet-api.jar from apache tomcat library in to projects->properties->java build path, Solved the error.
I wrote a method which return an Array converted as String. When calling this method in the main method and printing it out the array is filled. When I am calling the same method in the doGet method for printing it in my html file, the array is empty and it prints only: []
Normally the doGet method schould work because when the method return not the array but just "hello" the html file print the String.
Here ist the code:
public static String test(senderonpremise s){
String t;
//this should be printed
t = String.valueOf(s.arrivalList);
//startSending();
//this works in doGet()
//return "this works";
// when I return this it works in the main-method but not in DoGet()
return t;
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/event-stream");
resp.setCharacterEncoding("UTF-8");
senderonpremise s = new senderonpremise();
PrintWriter out = resp.getWriter();
String next = "data: " + test(s) + "\n\n";
out.write(next);
out.flush();
}
/**
public static void main(String[] args) {
senderonpremise s = new senderonpremise();
System.out.print(test(s));
}
**/
I recommend you using the JEaSSE library: https://github.com/mariomac/jeasse, which is lightweight and works out of the box with Servlets 3.x
#WebServlet(asyncSupported = true)
public class ExampleServlet1 extends HttpServlet {
EventTarget target;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
target = new ServletEventTarget(req).ok().open();
}
public void onGivenEvent(String info) {
target.send("givenEvent",info);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_KEY_SECRET);
try {
StringBuffer callbackURL = request.getRequestURL();
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/LinkedInCallbackServlet");
LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken(callbackURL.toString());
request.getSession().setAttribute("requestToken", requestToken);
System.out.println("token:"+requestToken);
System.out.println("Success");
String path=callbackURL.toString();
String verifier = request.getParameter("oauth_verifier");
System.out.println("----"+verifier);
response.sendRedirect(requestToken.getAuthorizationUrl());
} catch (LinkedInApiClientException e) {
throw new ServletException(e);
}
}
/** * #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stubss
}
When it run this code then shows error:
HTTP Status 500 - oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 403 for URL: https://api.linkedin.com/uas/oauth/requestToken
The init method gets called again and again on every request in servlet.
Here is the code:
public class PersonInfoController extends HttpServlet {
private static final long serialVersionUID = 1L;
public PersonInfoController() {
super();
}
public void init() throws ServletException {
Connection connection = Database.getConnection();
System.out.println("init method");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<PersonInfoServiceI> myList = new ArrayList();
PersonInfoServiceI instance = new PersonInfoServiceImpl();
myList = instance.getdata();
String jsonstring = new Gson().toJson(myList);
request.setAttribute("List", jsonstring);
RequestDispatcher rd = request.getRequestDispatcher("showdata.jsp");
rd.forward(request, response);
}
public void destroy() {
System.out.println("the destory");
}
}
According to your code init() should call only once when servlet will load on first request. Then after its destruction init() will be called again on new request. In between only your service method will be called. Your code is good having no logical mistakes.
Are you calling init method outside the servlet?
Can you attach you deployment descriptor?
I'm trying to tracking valid user Ids in my Java servlet, can I implement HttpSessionListener this way ?
public class my_Servlet extends HttpServlet implements HttpSessionListener
{
String User_Id;
static Vector<String> Valid_User_Id_Vector=new Vector<String>();
private static int activeSessions=0;
public void sessionCreated(HttpSessionEvent se)
{
// associate User_Id with session Id;
// add User_Id to Valid_User_Id_Vector
Out(" sessionCreated : "+se.getSession().getId());
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se)
{
if (activeSessions>0)
{
// remove User_Id from Valid_User_Id_Vector by identifing it's session Id
Out(" sessionDestroyed : "+se.getSession().getId());
activeSessions--;
}
}
public static int getActiveSessions()
{
return activeSessions;
}
public void init(ServletConfig config) throws ServletException
{
}
public void destroy()
{
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
User_Id=request.getParameter("User_Id");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
public String getServletInfo()
{
return "Short description";
}
}
How to get the listener notified when a session ends ? I'm trying to bypass "/WEB-INF.web.xml" all together, is it doable ? Or does it make sense ?
This won't bypass /WEB-INF/web.xml. Furthermore, you'll end up with 2 instances of this class, not 1 performing both functions. I suggest you put this Vector in the ServletContext and have 2 separate classes.
In the servlet, you get to it via getServletContext(). In the listener, you'll do something like this:
public void sessionCreated(HttpSessionEvent se) {
Vector ids = (Vector) se.getSession().getServletContext().getAttribute("currentUserIds");
//manipulate ids
}