cookies giving unusual values along with set values in servlet - java

I have set cookies in a servlet class and read those cookies values in another servlet class. In another servlet class along with the set cookies values, I am getting some unusual values.
My Home.java servlet class results set ::
first result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello RACHEL
Hello last_name, Hello KIM
second result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello CAIRO
Hello last_name, Hello SENGAL
in both the results I am getting the set cookies values and names but along with them I am getting JSESSIONID and A502A7144AE035ED9B1A2549F5C7B74B. I can't understand from where do these cookies values are appearing? How can I remove this? Why are these values appearing?
My code :
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Authenticate
*/
#WebServlet("/Authenticate")
public class Authenticate extends HttpServlet {
private static final long serialVersionUID = 1L;
public Authenticate() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
out.print("Welcome "+ firstname);
// Create cookies for first and last names.
Cookie f_name = new Cookie("first_name", firstname);
Cookie l_name = new Cookie("last_name", lastname);
// Add both the cookies in the response header.
response.addCookie( f_name );
response.addCookie( l_name );
//creating submit button
out.print("<form action='Home' method='post' >");
out.print("<input type='submit' value='cookie click' />");
out.print("</form>");
out.close();
}
catch(Exception ex)
{
System.out.println("exception occured");
System.out.println(ex.toString());
}
}
}
Code for Home servlet
#WebServlet("/Home")
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Home() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[] = request.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
out.print("Hello " + ck[i].getName() + ", ");
out.print("Hello " + ck[i].getValue());
out.print("<br />");
}
}
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Related

JavaEE, Servlet create links to files in the folder

There is a servlet that accepts files from the client and stores them in a folder.
It is now necessary to list the files from this folder and create links to them (that is, click on the file name and it's downloaded from you).
Now just output a list of files in the form of text. How to create links to them? I read that for this it is enough to expose the headers, but how this is done and has not been found.
Sample Code:
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String param = "/dirs";
PrintWriter w = res.getWriter();
res.setContentType("text/html");
String root="/dirs";
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
w.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
w.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + param + "</FONT></H3><HR>");
w.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++)
printName(fileList[i], w);
w.println("</TABLE><HR>");
}
private void printName(File name, PrintWriter output)
{
String type = name.isDirectory()
? " (Directory)" : " (File)";
output.println("<TR><TD>" + type + "</TD><TD><FONT COLOR=BLUE>"
+ name.getName() + "</FONT></TD></TR>");
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
I solved my problem. In case someone needs it or someone knows a more beautiful way.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
printWriter.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
printWriter.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + root + "</FONT></H3><HR>");
printWriter.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++) {
printName(fileList[i], printWriter);
}
printWriter.println("</TABLE><HR>");
}
private void printName(File file, PrintWriter output)
{
System.out.println(file.getName());
output.println("<tr><td><a href=\"https://Upload/DownloadServlet?name="
+file.getName()+"\">" + file.getName() + "</a></td></tr>" );
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
And DownloadServlet
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DownloadServlet
*/
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DownloadServlet() {
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
String name = request.getParameter("name");
String fileType = "multipart/form-data";
response.setContentType(fileType);
response.setHeader("Content-disposition", "attachment; filename=" + name);
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
File file = new File(root + File.separator + name);
OutputStream output = response.getOutputStream();
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[4096];
int lenght;
while( ( lenght = input.read(buffer) ) > 0 ) {
output.write(buffer, 0, lenght);
}
input.close();
output.flush();
output.close();
response.getOutputStream().flush();
response.getOutputStream().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);
}
}

How can I get the data form SQL table in jsp file?

So after reading what was suggested to me.
here are all the files I'm using.
There's one problem, the method Authorfindall() in the AuthorServlet file is giving me an error that it's undeclared, which's not true because it's in the AuthorService file.
Can I get some help please?
Thank you.
Author class
package user.domain;
public class Author {
private String email;
private String name;
private String affiliation;
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAffiliation(){
return affiliation;
}
public void setAffiliation(String affiliation){
this.affiliation = affiliation;
}
#Override
public String toString() {
return "Author [ email=" + email + ", name="
+ name + ", affiliation=" + affiliation +"]";
}
}
Author service
package user.service;
import java.util.List;
import user.dao.UserDao;
import user.domain.Author;
public class AuthorService {
private UserDao userDao = new UserDao();
public List<Object> Authorfindall() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// TODO Auto-generated method stub
return userDao.Authorfindall();
}
}
Author Servlet
package user.web.servlet;
import java.io.IOException;
import java.util.List;
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 user.service.AuthorService;
import user.domain.Author;
/**
* Servlet implementation class AuthorServlet
*/
#WebServlet("/AuthorServlet")
public class AuthorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
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
AuthorService authorservice = new AuthorService();
try {
request.setAttribute("AuthorList", authorservice.Authorfindall());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
List<Object> li = authorservice.Authorfindall();
for(int i = 0; i < li.size();i++){
System.out.println(li.get(i).toString());
}
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/Queryresult/author.jsp").forward(request, response);
}
}
UserDao
Public Class UserDao {
public List<Object> Authorfindall()throws InstantiationException,
IllegalAccessException, ClassNotFoundException{
List<Object> list = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection connect = DriverManager
.getConnection("jdbc:mysql://127.0.0.1:3306/sampledb?"
+ "user=root&password=Shafiko93!");
String sql = "select * from author";
PreparedStatement preparestatement = connect.prepareStatement(sql);
ResultSet resultSet = preparestatement.executeQuery();
while(resultSet.next()){
Author author = new Author();
author.setEmail(resultSet.getString("email"));
author.setName(resultSet.getString("name"));
author.setAffiliation(resultSet.getString("affiliation"));
list.add(author);
}
} catch(SQLException e) {
throw new RuntimeException(e);
}
return list;
}
}

Calling EJB Session outside of doGet or doPost

I am having a bit of problem figuring out whether I can actually call methods of the session bean in a method that doesn't take the HttpServletRequest and HttpServletResponse parameters ?
Having realized that the code works in doGet and doPost methods I have modified a custom made method to take the parameters of request and response, and suddenly it has started working.
My goal is to have the method working (calling session bean methods) without having a request and response in the method parameters.
However here is the code of the problematic version which grants NullPointerException on itemRegistrationSession.openConnection();
package web;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
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 auction.itemRegistrationRemote;
import auction.userRegistrationRemote;
/**
* Servlet implementation class processItem
*/
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
getCategories();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//ArrayList<String> categories = getCategories(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected ArrayList<String> getCategories() {
System.out.println("Hello from getCategories()");
itemRegistrationSession.openConnection();
System.out.println("Hello2 from getCategories()");
ArrayList<String> categories = itemRegistrationSession.getCategories();
itemRegistrationSession.closeConnection();
return categories;
}
}
package auction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
/**
* Session Bean implementation class itemRegistration
*/
#Singleton
public class itemRegistration implements itemRegistrationRemote {
Connection con;
PreparedStatement prepStat;
ResultSet resultSet;
final String ITEM_NAME = "ITEM_NAME";
final String CATEGORY_NAME = "CATEGORY_NAME";
final String USER_NAME = "USER_NAME";
final String ITEM_MODEL = "ITEM_MODEL";
final String ITEM_DESCRIPTION = "ITEM_DESCRIPTION";
/**
* Default constructor.
*/
public itemRegistration() {
// TODO Auto-generated constructor stub
}
#Override
public void openConnection() {
System.out.println("Openning connection for itemRegistration");
try {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
System.out.println("Openning database connection - Instantiation Exception " + e.getMessage());
} catch (IllegalAccessException e) {
System.out.println("Openning database connection - IllegalAccessException " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Openning database connection - ClassNotFoundException " + e.getMessage());
}
try {
con = DriverManager.getConnection("jdbc:derby:C:/Users/Adrian/MyDB;upgrade=true", "adrian", "testero");
} catch (SQLException e) {
System.out.println("Openning database connection - SQLException " + e.getMessage());
}
} // End of openConnection method
#Override
public void closeConnection() {
try {
resultSet.close();
prepStat.close();
con.close();
} catch (SQLException e) {
System.out.println("Closing database connection - SQLException " + e.getMessage());
}
} // End of closeConnection method
#Override
public ArrayList<String> getCategories() {
ArrayList<String> categories = new ArrayList<String>();
try {
prepStat = con.prepareStatement("SELECT * FROM CATEGORY");
resultSet = prepStat.executeQuery();
int i = 1;
while (resultSet.next()) {
categories.add(resultSet.getString(i));
i++;
}
} catch (SQLException e) {
System.out.println("getCategories SQLException - " + e.getMessage());
}
return categories;
}
}
Sounds like the dependency inject for the
#EJB itemRegistrationRemote itemRegistrationSession
isn't working. Trying adding a log statement showing the value of the itemRegistrationSession object to see if that member got initialized correctly.
You're getting the exception because by the time you call getCategories() the EJBs have not been injected yet.
At constructor invocation time injection hasn't occurred yet, keep in mind that the object is just being created so the container hasn't had time to inject anything, the proper way to do this is by using the #PostConstruct annotation. From the javadoc:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization...
so you need to move the getCategories() invocation to a #PostConstruct annotated method, like this:
#WebServlet("/processItem")
public class processItem extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB itemRegistrationRemote itemRegistrationSession;
#EJB userRegistrationRemote processRegistrationSession;
/**
* #see HttpServlet#HttpServlet()
*/
public processItem() {
super();
}
#Postconstruct
void init() {
getCategories();
}...

getting string value from jscript to servlet

I've a little doubt with this...how can i set/retrieve the value from a jsp page jscript string named "z" in a servlet.I need to use it in servlet...I'M exploring new thing n its a new thing for me as i"m new to these thing...Thanks for the quick help....i need the value of password if pass1 and pass2 are same,n then i need to retrieve it in servlet if pass1==pass2...tell me a way...for that i wrote a jscript to check pass1==pass2..
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New User Registration</title>
<script>
function myFunction(){
var x = document.forms["newForm"]["pass1"].value;
var y = document.forms["newForm"]["pass2"].value;
if(x==y){
document.newForm.submit();var z=x;
return true;
}
else {
alert("Passwords not matching!!!");}
}
</script>
</head>
<body>
<h1>Form</h1>
<fieldset>
<form name=newForm action="RegServlet">Username:<input
type="text" name="username"><br>
Password:<input type="text" name="pass1" id="pass1"><br>
Confirm Password:<input type="text" name="pass2" id="pass2"><br>
<input type="submit" onclick=myFunction() value="Create"></input></form>
</fieldset>
</body>
</html>
servlet
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegServlet
*/
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegServlet() {
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
String s1=request.getParameter("username");
System.out.println(s1);
String s2=request.getParameter("");//HERE I NEED THE PAssword value if PASS!==PASS2
System.out.println(s2);
String c="jdbc:mysql://localhost:3306/test";
Connection con=null;
System.out.println("Connection OK");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Done2");
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("Done3");
PreparedStatement ps=null;
System.out.println("Done4");
String qs = "insert into userinfo values(?,?);";
ps = con.prepareStatement(qs);
ps.setString(1,s1);
ps.setString(2,s2);
System.out.println("Success");
ps.execute();
con.close();
}
catch (Exception e) {
System.out.println("Failed: " + e.toString());
// TODO: handle exception
System.out.println("Failed");}}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Create a hidden field in your form; then in your "onsubmit" event set the value of that field to z.
<input type="hidden" name="zValue" id="zValue">
in onsubmit event
document.getElementById("zValue").value="The value I want to send";
and retrieve in your servlet as any other parameter.
The following is an example i use in tomcat. It will get you all parameters that are send in a POST or GET request. Be advised that this does not cover multicast requests (which are needed for file transfers). I don't know if it will work for you, as you have not specified you servlet container.
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;
#WebServlet(description = "A simple request test.", urlPatterns = { "/requesttest" })
public class RequestTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration<String> paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
EDIT
Seeing as you edited your question with your servlet code, the answer should be really simple.
String s2=request.getParameter("pass1");
This should get you the value that is transmitted within the password field. This is no different than you getting the username with String s1=request.getParameter("username");

Key in Request Token is null or blank- Brick red Social Auth

I need to import contacts to the enable my web app users to send invitation to his/her friends from my site, I am using SocioAuth Open source API to get this done, I have written 2 servlets to get this done I am pasting the code of my servlet. when I deployed the app in my Ec2 instance, I am getting an exception saying "Key in request token is null or blank in the line number 27 of the NewSocialAuthentication,
package com.auth.actions;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
public class NewSocialAuthentication extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of NewSocialApp..");
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
String returnToUrl = "http://ec2-50-19-118-108.compute-1.amazonaws.com/SocialAuthNew6/return";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
}
package com.auth.actions;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.util.*;
public class ReturnServlet extends HttpServlet{
/**
*
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Coming to doGet of Return Servlet..");
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");//this the line is rising exception
Profile p = provider.verifyResponse(request);
System.out.println(p.getFirstName());
List<Contact> contactsList = provider.getContactList();
for(int i=0;i<contactsList.size();i++){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println(contactsList.get(i).getFirstName()+" : "+contactsList.get(i).getLastName());
out.println(contactsList.get(i).getFirstName());
out.println(contactsList.get(i).getLastName());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
This is the servlet which redirects to the email service provider
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.AuthProviderFactory;
/**
* Servlet implementation class NewSocialAuthentication
*/
public class NewSocialAuthentication extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewSocialAuthentication() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
#SuppressWarnings("unused")
PrintWriter out = response.getWriter();
String socialAppId = request.getParameter("id");
System.out.println("SocialAppId: "+socialAppId);
AuthProvider provider;
try {
provider = AuthProviderFactory.getInstance(socialAppId);
//String returnToUrl = "http://ec2-50-16-183-101.compute-1.amazonaws.com/SocialAuthNew/return";
String returnToUrl = "u r returning url ";
System.out.println("Return URL..." + returnToUrl);
String urlString = provider.getLoginRedirectURL(returnToUrl);
System.out.println("URLString: "+urlString);
request.getSession().setAttribute("SocialAuth", provider);
response.sendRedirect(response.encodeRedirectURL(urlString));
} catch (Exception e) {
System.out.println("Exception...");
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
the return url would look like this I have embedded in the jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Contact" %>
<%#page import="org.brickred.socialauth.AuthProvider" %>
<%#page import="org.brickred.socialauth.Profile" %>
<%#page import="java.util.*" %>
Insert title here
CONTACT LIST
<%
try{
AuthProvider provider = (AuthProvider)request.getSession().getAttribute("SocialAuth");
try{
System.out.println(provider.getContactList());
}
catch(Exception e){
System.out.println("Exception Encountered..");
}
Profile p = provider.verifyResponse(request);
List contactsList = provider.getContactList();
%>
Hello, <%= p.getFirstName() %>
Contact List
First Name
Email
<%
for(int i=0;i
"/><%= contactsList.get(i).getFirstName() %><%= contactsList.get(i).getEmail() %>
<%
}
%>
</table>
<input type="submit" value="GET CONTACTS"/>
</form>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>

Categories

Resources