JSP- unable to insert record using JSP Beans [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am trying to insert college name into database using beans following MVC pattern but whenever I click on insert button I got 404 error. Here is the code
JSP File
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Practical 5</title>
</head>
<body>
<h1>Insert College</h1>
<form action="NewServlet">
Enter Name<input type="text" name="collegeName"><br>
Enter City<input type="text" name="collegeCity"><br>
Enter Year<input type="number" name="collegeYear"><br>
Enter Fees<input type="number" name="collegeFees"><br>
<input type="submit" name="Insert" value="Insert">
</form>
<%
String msg=(String)request.getAttribute("msg");
%>
<h2><%=msg%></h2>
</body>
</html>
CollegeBean.java
package college;
public class CollegeBean {
public String cname;
public String ccity;
public int year;
public float fees;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCcity() {
return ccity;
}
public void setCcity(String ccity) {
this.ccity = ccity;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public float getFees() {
return fees;
}
public void setFees(float fees) {
this.fees = fees;
}
}
CollegeDB.java
package college;
import java.sql.*;
public class CollegeDB {
public String insertOperation(CollegeBean collegeBeanObj) throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost/jspractical5", "root", "");
Statement st= cn.createStatement();
int flag= st.executeUpdate("INSERT INTO college (c_name, c_city, c_year, c_fees) VALUES('"+collegeBeanObj.getCname()+"','"+collegeBeanObj.getCcity()+"','"+collegeBeanObj.getYear()+"','"+collegeBeanObj.getFees()+"')");
if (flag!=0)
return "Record Inserted";
else
return "Record not inserted";
}
}
Finally the controller file the servlet to handle all the stuff
NewServlet.java
package college;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "NewServlet", urlPatterns = {"/college/NewServlet"})
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name=request.getParameter("name");
String city=request.getParameter("city");
int year=Integer.parseInt(request.getParameter("year"));
float fees=Integer.parseInt(request.getParameter("fees"));
CollegeBean collegeBeanObj= new CollegeBean();
collegeBeanObj.setCname(name);
collegeBeanObj.setCcity(city);
collegeBeanObj.setYear(year);
collegeBeanObj.setFees(fees);
CollegeDB cd= new CollegeDB();
String msg= cd.insertOperation(collegeBeanObj);
request.setAttribute("msg", msg);
RequestDispatcher rd= getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
out.println(e);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}

The problem is with the line in the controller where you assign the RequestDipatcher.
May be the file path of index.html is wrong. Check the folder structure and insert the path accordingly. If the index.html is in same directory of the page where request is sent then in the file path of index.html, remove the leading '/'.
Also change the form action attribute URL to same URL pattern defined in urlPattrns in the controller annotation "/college/NewServlet"

Related

Problems with cli.get() and getting attributes in JSP and Servlet

Good morning, I have this problem.
I have a java class "Cliente" with the corresponding data (I leave you the code)
package Clases;
public class Cliente {
public Cliente(String dni, String nombre, String apellido, String telefono){
}
}
Then, I have this Servlet with DoGet where I generate a list of Cliente and get my session, and a dopost that asks for the parameters:
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.util.*;
import Clases.Cliente;
#WebServlet(name = "SvPrueba", urlPatterns = {"/SvPrueba"})
public class SvPrueba extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Cliente> listaClientes = new ArrayList<> ();
listaClientes.add(new Cliente("12345678", "Luisina", "de Paula", "444222357"));
listaClientes.add(new Cliente("46325965", "Avril", "Lavigne", "774568931"));
listaClientes.add(new Cliente("69584123", "Gianluigi", "Guidicci", "4567531654"));
HttpSession misession = request.getSession();
misession.setAttribute("listaClientes", listaClientes);
response.sendRedirect("MostrarJSP.jsp");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String dni = request.getParameter("dni");
String nombre = request.getParameter("nombre");
String apellido = request.getParameter("apellido");
String telefono = request.getParameter("telefono");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Finally, I have a JSP where it presents the error: In it I bring the session and ask for the attributes to write them. However, on every "cli.get" I get cannot find symbol error
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Clientes</title>
</head>
<body>
<h1>Lista de Clientes</h1>
<%# page import="java.util.List" %>
<%# page import="Clases.Cliente" %>
<%
List<Cliente> listaClientes = (List) request.getSession().getAttribute("listaClientes");
int cont=1;
for (Cliente cli : listaClientes) { %>
<p><b>Cliente Nº <%=cont%></b></p>
<p>Dni: <%=cli.getDni()%></p>
<p>Nombre: <%=cli.getNombre()%></p>
<p>Apellido: <%=cli.getApellido()%></p>
<p>Teléfono: <%=cli.getTelefono()%></p>
<% cont= cont+1;%>
<%}%>
</body>
</html>
I'm starting in Java and I can't fix this :(
I hope that getDni, getNombre, etc. will bring me the data and write it in the HTML code, but I have some error and I don't know what it is.
Thank you ^^
The Cliente class is empty (apart from an empty constructor that does nothing by itself if you don't tell it what to do). You have to define both the data it contains and the methods to get the data. Something like this:
public class Cliente {
// the data in the class
String dni;
String nombre;
String apellido;
String telefono;
// manually set all members here
public Cliente(String dni, String nombre, String apellido, String telefono) {
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.telefono = telefono;
}
// getter methods are not created automatically, you have to define them
public String getDni() { return dni; }
public String getNombre() { return nombre; }
public String getApellido() { return apellido; }
public String getTelefono() { return telefono; }
}

No response from HttpServlet with AsyncContext

I'm trying to implement async servlet on Tomcat, that will send update to client every time an HttpSessionAttributeListener.attributeReplaced() is triggered. Client side is configured to receive Server Sent Events.
Although the listener receives the updates, the browser does not receive any response. Browser's developer pane shows, that the request is pending and it ends with error 500 after the timeout set by the AsyncContext.setTimeout(). I run out of ideas, why this is happening.
JS
var source = new EventSource('/acount/sse');
source.onmessage = function (event) {
console.log(event.data);
document.querySelector('#messageArea p').innerHTML += event.data;
};
And this is my servlet code:
Servlet
public class SSE extends HttpServlet implements HttpSessionAttributeListener {
public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";
private AsyncContext aCtx;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
resp.setContentType("text/event-stream");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("UTF-8");
aCtx = req.startAsync(req, resp);
aCtx.setTimeout(80000);
}
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
#Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
#Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
try {
String message = "data: " + httpSessionBindingEvent.getValue() + "\n\n";
aCtx.getResponse().getWriter().write(message);
aCtx.getResponse().getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The problem:
I tried your code and there was a java.lang.NullPointerException in:
aCtx.getResponse().getWriter().write(message);
Because the aCtx is null.
You have mixed the Servlet and Listener, but when the Listeners methods are called, the AsyncContext initialization is not. Therefore nothings go to the browser.
I splitted your code in Servlet an Listener and smuggled the AsychContext object through a session attribute. So it was accessible in the listener.
And it works.
The Complete Code:
The HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Server Event Listener</title>
</head>
<body>
<div id="messageArea">
<p></p>
</div>
<script>
var source = new EventSource('/yourPath/ServerSentEvent');
source.onmessage = function (event) {
console.log(event.data);
document.querySelector('#messageArea p').innerHTML += event.data;
};
</script>
</body>
</html>
The Servlet:
package testingThings.ServerSentEvent;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(asyncSupported = true, value = {"/ServerSentEvent"})
public class ServerSentEvent extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// add #WebServlet(asyncSupported = true) instead
// http://stackoverflow.com/questions/7855712/how-to-avoid-request-set-async-supported-true-to-enable-async-servlet-3-0-proces
// req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
resp.setContentType("text/event-stream");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("UTF-8");
AsyncContext aCtx = req.startAsync(req, resp);
aCtx.setTimeout(80000);
// add a asyncContext a session Attribute
req.getSession().setAttribute("asyncContext", aCtx);
//start logging in listener
req.getSession().setAttribute("entryProcessorProgress", "trigger output");
}
}
The HttpSessionAttributeListener:
package testingThings.ServerSentEvent;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
#WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {
public static final String ATTR_ENTRY_PROCESSOR_PROGRESS = "entryProcessorProgress";
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
#Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
#Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
write(httpSessionBindingEvent);
}
private void write(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals(ATTR_ENTRY_PROCESSOR_PROGRESS)) {
try {
// get the AsyncContext from the session
AsyncContext aCtx = (AsyncContext) httpSessionBindingEvent.getSession().getAttribute("asyncContext");
String message = "data: " + httpSessionBindingEvent.getValue() + "<br>\n\n";
aCtx.getResponse().getWriter().write(message);
aCtx.getResponse().getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Not able to fetch data from database by using ajax in java

hi i am implementing program which fetch data from database in java with ajax. but unfortunately it is not retireving output here is my code. program is running succesfully but not able to display database data from it.
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX JsonArray Example</title>
<link href='http://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<style type="text/css">
table, td, th
{
border:1px solid green;
font-family: 'Oxygen', sans-serif;
}
th
{
background-color:green;
color:white;
}
body
{
text-align: center;
}
.container
{
margin-left: auto;
margin-right: auto;
width: 40em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.get('PopulateTable',function(responseJson) {
if(responseJson!=null){
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['code']);
rowNew.children().eq(1).text(value['name']);
rowNew.children().eq(2).text(value['continent']);
rowNew.children().eq(3).text(value['region']);
rowNew.children().eq(4).text(value['population']);
rowNew.children().eq(5).text(value['capital']);
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
</script>
</head>
<body class="container">
<h1>AJAX Retrieve Data from Database in Servlet and JSP using JSONArray</h1>
<input type="button" value="Show Table" id="showTable"/>
<div id="tablediv">
<table cellspacing="0" id="countrytable">
<tr>
<th scope="col">Code</th>
<th scope="col">Name</th>
<th scope="col">Continent</th>
<th scope="col">Region</th>
<th scope="col">Population</th>
<th scope="col">Capital</th>
</tr>
</table>
</div>
</body>
</html>
FetchData.jsp
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import Countries.Countries;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
public class FetchData {
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream = FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("jdbc:mysql:");
String url = prop.getProperty("localhost:3306/country_db");
String user = prop.getProperty("root");
String password = prop.getProperty("");
Class.forName(driver);
connection = DriverManager.getConnection("localhost:3306/country_db", "root", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Countries> getAllCountries() {
connection = FetchData.getConnection();
ArrayList<Countries> countryList = new ArrayList<Countries>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from country");
while(rs.next()) {
Countries country=new Countries();
country.setCode(rs.getString("Code"));
country.setName(rs.getString("Name"));
country.setContinent(rs.getString("Continent"));
country.setRegion(rs.getString("Region"));
country.setPopulation(rs.getInt("Population"));
country.setCapital(rs.getString("Capital"));
countryList.add(country);
}
} catch (SQLException e) {
e.printStackTrace();
}
return countryList;
}
}
PopulateTable.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import Countries.Countries;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.ArrayList;
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;
#WebServlet("/PopulateTable")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;
public PopulateTable() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Coutries.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Countries;
public class Countries {
public Countries(String code,String name, String continent,String region,int population, String capital )
{
this.setCode(code);
this.setName(name);
this.setContinent(continent);
this.setRegion(region);
this.setPopulation(population);
this.setCapital(capital);
}
public Countries() {
}
private String code;
private String name;
private String continent;
private String region;
private int population;
private String capital;
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getContinent() {
return continent;
}
public void setRegion(String region) {
this.region = region;
}
public String getRegion() {
return region;
}
public void setPopulation(int population) {
this.population = population;
}
public int getPopulation() {
return population;
}
public void setCapital(String capital) {
this.capital = capital;
}
public String getCapital() {
return capital;
}
}
here is a image for mysql database and its table.
You can first try to figure out where the actual problem is occurring.
- First you can check if the data is actually being retrieved from database. In servlet doGet method you iterate over country list and print its data using system.out.println
- If you are able to retrieve data then on the client side see that proper Json data is coming. You can check response on client side using firebug.
- In the jQuery code use console.log to check whether the data is coming or not. You can put log statement before and after the if(responseJson!=null) to check if data is actually null or not.
- If data is not null then there must be some issue with the format in which data is coming or how you are iterating over the data.

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