you can download jar from www.twitter4j.org and then follow bellow Steps
1. first register your application in twitter.com, there you will get consumerKey and consumerSecret
2. then include the above jar in your classpath,
3. write the following servlet to get authenticate by the user.
package com.servlet;
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;
import javax.servlet.http.HttpSession;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
@WebServlet("/twitter")
public class TwitterLogin extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
String CALLBACKURL = "http://localhost:8080/connect/twitter";
HttpSession session = req.getSession(true);
if(req.getParameter("oauth_verifier")== null){
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("ConsumerKey", "ConsumerSecret");
RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
// String authUrl = requestToken.getAuthorizationURL();
session.setAttribute("twitter", twitter);
session.setAttribute("requestToken", requestToken);
resp.sendRedirect(requestToken.getAuthorizationURL());
return;
}else{
AccessToken accessToken = null;
Twitter twitter = (Twitter)session.getAttribute("twitter");
RequestToken requestToken = (RequestToken)session.getAttribute("requestToken");
accessToken = twitter.getOAuthAccessToken(requestToken, req.getParameter("oauth_verifier"));
System.out.println("Got request token.");
System.out.println("accessToken : " + accessToken.getToken());
System.out.println("accessToken secret: " + accessToken.getTokenSecret());
System.out.println("screenname:" + accessToken.getScreenName());
}
} catch (TwitterException te) {
te.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}