I have a table on JSP page. I want to sort it, when click button. How I should do it? Result table will on other jsp page or I can change current table?
That is my servlet, but I cant understand, how return result after sorting. It
Thank you!
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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("/home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String[] name = {"x1","x2","x3","x4","x5","x6","x7","x8","x9","x10"};
int[] price = {7600,8500,11700,15000,6000,10200,6400,5800,8700,10400};
int[] memory = {4,4,12,16,2,10,3,1,6,8};
int[] camera = {10,8,10,15,6,9,5,4,8,12};
public HomeServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int temp = 0;
List<Product> products = new ArrayList<Product>();
while(temp!=price.length-1){
Product pr = new Product(name[temp], camera[temp], memory[temp], price[temp]);
temp++;
products.add(pr);
}
request.setAttribute("productList", products);
RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/WEB-INF/views/home.jsp");
rd.forward(request, response);
if (request.getParameter("button1") != null) {
Sorts.function1(price);// in this function I sort table by a certain field
} else if (request.getParameter("button2") != null) {
Sorts.function1(memory);
}
}
//???? WHAT I SHOULD DO HERE?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Related
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);
}
}
}
Below is my code:
package com.newyzon.controllers;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import com.newyzon.beans.Cart;
import com.newyzon.beans.BookData;
import com.newyzon.beans.BookMeta;
import com.newyzon.beans.DisplayBookList;
import com.newyzon.services.*;
public class BooklistController {
LoginController lc;
Map<String, BookData> booklist = new HashMap<String, BookData>();
public BooklistController(LoginController lc) {
this.lc = lc;
}
public void displayBookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ServiceException {
BooksService bs = new BooksServiceLocator();
Books books = bs.getBooksPort();
//response.getWriter().append(books.getBook(1).getTitle());
int quant = books.getSize();
String output = "<br/>";
for(int i=0; i < quant; i++) {
Book bk = books.getBook(i);
BookData bd = new BookData(bk.getId(), bk.getTitle(), bk.getAuthor(), bk.getPublisher());
output += "<a href='Controller?task=addbook&bookid=" + bd.getId() + "'>" + bd.getTitle() + "</a><br/>";
booklist.put("" + bd.getId(), bd);
}
DisplayBookList dbl = new DisplayBookList(output);
request.getSession().setAttribute("displayBookList", dbl);
lc.sendRedirectJsp("bookList", request, response);
}
public void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String bookid = request.getParameter("bookid");
BookData bk = booklist.get(bookid);
// Add the book to the cart
Cart cart = (Cart)request.getSession().getAttribute("cart");
if(cart == null) {
cart = new Cart();
request.getSession().setAttribute("cart", cart);
}
BookMeta bm;
if((bm = cart.contains(bk)) != null) {
bm.setQuantity(bm.getQuantity() + 1);
} else {
bm = new BookMeta(bk, 1);
cart.getBooks().add(bm);
}
}
}
For some reason, the HashMap.put() is run, but the resultant booklist object contains no BookData objects, instead it just puts a null value in there. I've debugged and checked to see that the parameter 'bd' contains a BookData object, (and it does), so why doesn't it end up in the hashmap?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
package com.dev.web.Controller;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dev.web.Dao.UserDao;
import com.dev.web.Model.User;
public class UserControll extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listEmp.jsp";
private UserDao dao;
public UserControll() {
super();
UserDao dao = new UserDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward="";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete")){
int Employee_Id= Integer.parseInt(request.getParameter("Employee_Id"));
dao.deleteUser(Employee_Id);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (action.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int Employee_Id = Integer.parseInt(request.getParameter("empId"));
User user = dao.getUserById(Employee_Id);
request.setAttribute("user", user);
} else if (action.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("Employee", dao.getAllUsers());
} else {
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
user.setEmployee_Name(request.getParameter("empname"));
user.setSalary(request.getParameter("empsalary"));// here is my error..i declared salary is double
try {
Date dob = new SimpleDateFormat("MM/dd/yyyy").parse(request.getParameter("empdob"));
user.setDob(dob);
} catch (ParseException e) {
e.printStackTrace();
}
user.setActive(request.getParameter("empactive"));// here is my error.. i declared active is boolean
String empid = request.getParameter("empid");
if(empid == null || empid.isEmpty())
{
dao.addUser(user);
}
else
{
user.setEmployee_ID(Integer.par`enter code here`seInt(empid));
dao.updateUser(user);
}
RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
}
}
The getParameter() method of HttpServletRequest is inherited from ServletRequest. From the API docs you can see this method always returns a string. You need to parse your boolean or double from this string, for example
Double.parseDouble(request.getParameter("empsalary"));
Hi just wanted to share this servlet it takes 2 arguments ( img-> image name , rot ->rotation of the images) loads the image from the images directory rotates it and outputs it to the servlet stream
you can find it in the answer below
package at.buchinger.mapdisplay;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RotatedImage
*/
public class RotatedImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RotatedImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String img = (String) request.getParameter("img");
String path = getServletContext().getRealPath("image/"+img);
String r;
r=request.getParameter("rot");
if(r==null){
r="0";
}
double rot = Double.parseDouble( r);
BufferedImage image = ImageIO.read(new File(path));
AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(rot), image.getWidth()/2, image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
ServletContext sc = getServletContext();
String filename = getServletContext().getRealPath(path);
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
ServletOutputStream out = response.getOutputStream();
Iterator iter = ImageIO.getImageWritersByMIMEType(mimeType);
ImageIO.write(image, "png", out);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
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();
}
%>