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");
Related
Hello and thank you for your help!
I am currently learning how to use servlets and JSP players to implement FrontController pattern.
First I will show the behaviour I would like to fix, then the code, and then the questions.
I have created 9 courses using a form, and it only shows the last one, and the other 8 are null, I added the current iteration count to debbug if it was iterating well:
My FrontServlet which is the main web app's entry point:
/*
* 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 org;
import frontController.FrontCommand;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
/**
*
* #author YonePC
*/
#WebServlet(name = "FrontServlet", urlPatterns = {"/FrontServlet"})
public class FrontServlet extends HttpServlet {
ArrayList cursos = new ArrayList();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession session = request.getSession(true);
Curso curso = (Curso) session.getAttribute("curso");
if (curso != null) {
cursos.add(curso);
session.setAttribute("cursos",cursos);
} else {
curso = new Curso(request.getParameter("titulo"),
request.getParameter("autor"),
request.getParameter("asignatura"),
request.getParameter("duracion"),
request.getParameter("video"));
cursos.add(curso);
session.setAttribute("cursos",cursos);
}
FrontCommand command = getCommand(request);
command.init(getServletContext(), request, response);
command.process(request);
} catch (Exception ex) {
Logger.getLogger(FrontServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
private FrontCommand getCommand(HttpServletRequest req) throws Exception {
try {
FrontCommand f = (FrontCommand) getCommandClass(req).newInstance();
return f;
} catch (Exception e) {
throw new Exception(e);
}
}
private Class getCommandClass(HttpServletRequest req) {
Class result;
final String command = "frontController." + (String) req.getParameter("command");
try {
result = Class.forName(command);
} catch (ClassNotFoundException e) {
result = UnknownCommand.class;
}
return result;
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The abstract class FrontCommand which is the boilerplate for concrete commands:
/*
* 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 frontController;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author YonePC
*/
public abstract class FrontCommand {
protected ServletContext context;
protected HttpServletRequest request;
protected HttpServletResponse response;
public void init(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
this.context = context;
this.request = request;
this.response = response;
}
abstract public void process(HttpServletRequest request);
public void forward(String target) throws ServletException, IOException {
RequestDispatcher dp = context.getRequestDispatcher(target);
dp.forward(request, response);
}
}
The command being called by FrontServlet when we submit the form related to course's creation:
/*
* 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 frontController;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
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 org.Curso;
/**
*
* #author YonePC
*/
#WebServlet(name = "CourseInfoCommand", urlPatterns = {"/CourseInfoCommand"})
public class CourseInfoCommand extends FrontCommand {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
public String getServletInfo() {
return "Short description";
}// </editor-fold>
#Override
public void process(HttpServletRequest request) {
HttpSession session = request.getSession();
ArrayList cursos = (ArrayList) session.getAttribute("cursos");
if (cursos != null) {
Iterator i = cursos.iterator();
while (i.hasNext()) {
int current = 0;
Curso cursoActual = (Curso) i.next();
request.setAttribute("titulo" + current, cursoActual.getTitulo());
request.setAttribute("autor" + current, cursoActual.getAutor());
request.setAttribute("asignatura" + current, cursoActual.getAsignatura());
request.setAttribute("duracion" + current, cursoActual.getDuracion());
request.setAttribute("video" + current, cursoActual.getVideo());
current++;
}
}
try {
forward("/CourseInfo.jsp");
} catch (ServletException ex) {
Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And the CourseInfo.jsp file where we collect and show the data:
<%#page import="org.Curso"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Enumeration"%>
<html>
<body>
<table width="100%" border=1>
<tr>
<th style="padding: 8px">Titulo</th>
<th style="padding: 8px">Autor</th>
<th style="padding: 8px">Asignatura</th>
<th style="padding: 8px">Duracion</th>
<th style="padding: 8px">Video</th>
</tr>
<tr>
<td><%= request.getAttribute("titulo")%></td>
<td><%= request.getAttribute("autor")%></td>
<td><%= request.getAttribute("asignatura")%></td>
<td><%= request.getAttribute("duracion")%></td>
<td>Video</td>
</tr>
<% if (session.getAttribute("cursos") != null) {%>
<tr>
<% ArrayList cursos = (ArrayList) session.getAttribute("cursos");
Iterator i = cursos.iterator();
int current = 0;
while (i.hasNext()) {
Curso cursoActual = (Curso) i.next();
%>
<td><%= request.getAttribute("titulo" + current)%></td>
<td><%= request.getAttribute("autor" + current)%></td>
<td><%= request.getAttribute("asignatura" + current)%></td>
<td><%= request.getAttribute("duracion" + current)%></td>
<td>Video</td>
<%
current++;
%>
<br/>
<p>current: <%= current%></p>
<%
}
%>
</tr>
<br/>
<% }%>
</table>
</body>
</html>
I first though that the problem could be because of I have included:
ArrayList cursos = new ArrayList(); in FrontServlet creation.
But then I realized that servlets are supposed to be shared between clients so it is not being recreated.
I realized that in CourseInfoCommand, the concreteCommand I should initialize the current counter before the while loop:
if (cursos != null) {
Iterator i = cursos.iterator();
int current = 0;
while (i.hasNext()) {
Curso cursoActual = (Curso) i.next();
request.setAttribute("titulo" + current, cursoActual.getTitulo());
request.setAttribute("autor" + current, cursoActual.getAutor());
request.setAttribute("asignatura" + current, cursoActual.getAsignatura());
request.setAttribute("duracion" + current, cursoActual.getDuracion());
request.setAttribute("video" + current, cursoActual.getVideo());
current++;
}
}
So thanks to post the previous question I realized the bug 😏😏😏😏😏
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);
}
}
}
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"
I am using spring framework and i am having Index.jsp like :
Code:
<html>
<head></head>
<body>
<p>File Upload</p>
<form action="ImportService" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
</body>
I have ImportService as
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImportService extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "c:\\files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
// String realPath =
// getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(DESTINATION_DIR_PATH);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH
+ " is not a directory");
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = "param";
String value = request.getParameter(name);
String welcomeMessage = "Welcome " + value;
System.out.println("Message=" + welcomeMessage);
response.setContentType("text/html");
response.setContentType("text/plain");
System.out.println("Inside Get Method");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post Method");
PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
out.println("File Name = " + item.getFieldName()
+ ", Value = " + item.getString());
} else {
// Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
}
out.close();
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
}
// doGet(request, response);
}
}
In my web.xml, I have
<servlet>
<servlet-name>ImportService</servlet-name>
<servlet-class>com.service.ImportService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImportService</servlet-name>
<url-pattern>/ImportService/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/Index.jsp</welcome-file>
</welcome-file-list>
Now when I try to hit the url: http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp then it gives me blank message and html form is not rendered.
Any suggestions or pointers?
change your entry URL from http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp
to http://localhost:8080/delta-webapp/jsp/Index.jsp
You've mapped ImportService servlet to handle all requests to /ImportService/*.
Your index.jsp is located at /jsp/Index.jsp. If instead you just put /delta-webapp It /may/ work.
In general though, I don't think welcome files have hard coded paths. Typically you specify something like index.jsp as your welcome file and if nothing handles the request at a particular location, it will fall back to see if one of the welcome files listed is available and will render that.
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();
}
%>