ajax sending null to servlet [duplicate] - java

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 6 years ago.
I am trying send an bitmap and some string fields to server, and I have checked thoroughly no parameter is empty. This is my ajax code
var URL = "ProfileUpdater";
var username = $("#cp-setup-username").val();
var email = $("#cp-setup-email").val();
var birthday = $("#cp-setup-birthday").val();
var aboutYou = $("#cp-setup-about-you").val();
var intrests = $("#cp-setup-intrests").val();
var phoneNumber = $("#cp-setup-phone-number").val();
var sessionid = $.cookie('WhitePages_SessionID');
var session_username = $.cookie('WhitePages_Username');
var legal = emptyCheck(username,email,birthday,aboutYou,intrests,phoneNumber);
alert(username +" " + email + " " + birthday +" " + aboutYou + " " +intrests + " " + phoneNumber +" "+ sessionid +" " + session_username);
alert(result);
if(legal){
alert(sessionid + " " + session_username) ;
alert("about call server");
$.ajax({
type:'POST',
url : URL,
processData:'false',
contentType:'false',
data:{Username:username,Email:email,Birthday:birthday,AboutYou:aboutYou,Intrests:intrests,PhoneNumber:phoneNumber,sessionid:sessionid,username:session_username,Image:result,FieldsChanged:fieldsChanged,isMultiPart:isMultiPart},
success:function(data){
alert("success");
alert(data);
}
});
}
and this is my servlet code:
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 ProfileUpdater extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("Username");
String sessionid = request.getParameter("sessionid");
String username = request.getParameter("username");
//sessionid and username is null
PrintWriter out = response.getWriter();
out.println(sessionid +" " + username + " " + user);
System.out.println("hello " + username + "your session id is " +sessionid + " " + user );
}
}
I have put alerts in my script and they are not empty but on response it's null. I mean I think it's sending null to server. Can someone please tell me where I am going wrong ??? Thankyou.

You can't use getParameter() with a multipart post. It just returns null as you discovered. Depending on which servlet spec you are coding to, you can either use the #MultipartConfig annotation (spec 3.0+), or the Apache Commons FileUpload library. The annotation method is built-in, but requires a bit more work; the FileUpload library is easier to use IMO, but obviously requires including another library. I'm not sure which is more efficient in terms of resources or speed. Interestingly if you're using Tomcat it uses FileUpload to handle things in the background anyway.

Related

Making href only clickable & process to getPost

Using Java servlets only, I'm trying to get something similar tosomething in my doGet(), but I need it to pass the parameter to the doPost(). Here is some of my code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List < Folder > listFolders = (List < Folder > ) getServletContext().getAttribute("listFolders");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
for (int i = 1; i < listFolders.size(); i++) {
out.println("<a name=" + listFolders.get(i).getName() + " href='#' > " + listFolders.get(i).getName() + " </a>" + "<br/>");
`
Using request.getParameter() how would I know/get whatever the user clicks? This assignment requires it to look like links and needs to be clickable. I've seen some other examples using .jsp but I am only limited to servlets for this assignment.
out.println("<a href='File?id=" + listFolders.get(i).getId() + "'>" + listFolders.get(i).getName()
+ "</a><br/>");
Here, File is my java file name (File.java). To get the parameter in the doPost(), I use
Integer id = Integer.valueOf(request.getParameter("id"));
Edit: You dont need the java file name in the href, so it could be just

How to create a WSResponse object from string for Play WSClient

Documentation suggests testing API client based on WSClient using a mock web service, that is, create a play.server.Server which will respond to real HTTP requests.
I would prefer to create WSResponse objects directly from files, complete with status line, header lines and body, without real TCP connections. That would require less dependencies and run faster. Also there may be other cases when this is useful.
But I can't find a simple way to do it. It seems all implementations wrapped by WSResponse are tied to reading from network.
Should I just create my own subclass of WSResponse for this, or maybe I'm wrong and it already exists?
The API for Play seems intentionally obtuse. You have to use their "Cacheable" classes, which are the only ones that seem directly instantiable from objects you'd have lying around.
This should get you started:
import play.api.libs.ws.ahc.AhcWSResponse;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseBodyPart;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseHeaders;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseStatus;
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders;
import play.shaded.ahc.org.asynchttpclient.Response;
import play.shaded.ahc.org.asynchttpclient.uri.Uri;
AhcWSResponse response = new AhcWSResponse(new Response.ResponseBuilder()
.accumulate(new CacheableHttpResponseStatus(Uri.create("uri"), 200, "status text", "protocols!"))
.accumulate(new CacheableHttpResponseHeaders(false, new DefaultHttpHeaders().add("My-Header", "value")))
.accumulate(new CacheableHttpResponseBodyPart("my body".getBytes(), true))
.build());
The mystery boolean values aren't documented. My guess is the boolean for BodyPart is whether that is the last part of the body. My guess for Headers is whether the headers are in the trailer of a message.
I used another way, mocking WSResponse with Mockito:
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import org.mockito.Mockito;
...
final WSResponse wsResponseMock = Mockito.mock(WSResponse.class);
Mockito.doReturn(200).when(wsResponseMock).getStatus();
final String jsonStr = "{\n"
+ " \"response\": {\n"
+ " \"route\": [\n"
+ " { \"summary\" :\n"
+ " {\n"
+ " \"distance\": 23\n"
+ " }\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(jsonStr);
} catch (IOException e) {
e.printStackTrace();
}
Mockito.doReturn(
jsonNode)
.when(wsResponseMock)
.asJson();
If you are using play-framework 2.8.x and scala, the below code can help us generate a dummy WSResponse:
import play.api.libs.ws.ahc.AhcWSResponse
import play.api.libs.ws.ahc.cache.CacheableHttpResponseStatus
import play.shaded.ahc.org.asynchttpclient.Response
import play.shaded.ahc.org.asynchttpclient.uri.Uri
import play.api.libs.ws.ahc.cache.CacheableHttpResponseBodyPart
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders
class OutputWriterSpec extends FlatSpec with Matchers {
val respBuilder = new Response.ResponseBuilder()
respBuilder.accumulate(new CacheableHttpResponseStatus(Uri.create("http://localhost:9000/api/service"), 202, "status text", "json"))
respBuilder.accumulate(new DefaultHttpHeaders().add("Content-Type", "application/json"))
respBuilder.accumulate(new CacheableHttpResponseBodyPart("{\n\"id\":\"job-1\",\n\"lines\": [\n\"62812ce276aa9819a2e272f94124d5a1\",\n\"13ea8b769685089ba2bed4a665a61fde\"\n]\n}".getBytes(), true))
val resp = new AhcWSResponse(respBuilder.build())
val outputWriter = OutputWriter
val expected = ("\"job-1\"", List("\"62812ce276aa9819a2e272f94124d5a1\"", "\"13ea8b769685089ba2bed4a665a61fde\""), "_SUCCESS")
"Output Writer" should "handle response from api call" in {
val actual = outputWriter.handleResponse(resp, "job-1")
println("the actual : " + actual)
actual shouldEqual(expected)
}
}

How should the JSP page handle the response sent by servlet? And how should the servlet looks like to implment this handle? [duplicate]

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
doGet and doPost in Servlets
(5 answers)
Closed 1 year ago.
I'm new to JSP/Servlet based web programming. I am currently following some tutorials of servlet and JSP but I found some of the example given doesn't make too much sense for me, for example, in one of the examples of servlet chapter, a servlet look like this:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}
To me, the way of displaying the html content is ugly. So I am wondering whether there is a way to make servlet return an object (or a primitive data type) as response, and the front-end part (jsp) use this object to render html content on the browser. I did some research and found out using
request.setAttribute();
is one of implementation of sending an object as response back to client. So I wrote the following servlet, I just paste a snippet of it:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Driver manager and DB url:
final String jdbcDriver = "com.mysql.jdbc.Driver";
final String DBUrl = "jdbc:mysql://localhost/zoo";
// DB credentials:
final String userName = "username";
final String password = "password";
//DB Query:
final String sql = "SELECT name FROM pet WHERE age=10;";
//Response ArrayList:
ArrayList<String> nameList = new ArrayList<String>();
try {
// Register a DB Driver:
System.out.println("Registering Driver.......");
Class.forName(jdbcDriver).newInstance();
// Open a connection:
System.out.println("Openning conncetion.......");
Connection conn = DriverManager.getConnection(DBUrl, userName, password);
// Execute a query:
System.out.println("Executing query.......");
Statement stmt = conn.createStatement();
// Store the result in ResultSet:
System.out.println("Loading the result......");
ResultSet rs = stmt.executeQuery(sql);
// Extract data from ResultSet:
System.out.println("Extracting data.......");
while (rs.next()) {
nameList.add(rs.getString("name"));
}
} ...some catch statement
request.setAttribute("nameList", nameList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
So basically this is JDBC is to extract all the pets' names whose age is 10, then store names in a ArrayList of String. I used setAttribute to store this ArrayList and make the index.jsp to handle this response. The index.jsp looks like this:
<%# page import="java.io.*,java.util.*"%>
<html>
<body>
<jsp:include page = "/GetPet" flush = "true" />
<%
ArrayList<String> nameList = request.getAttribute("nameList");
for (String name : nameList) {
out.write("<p>" + name + "</p");
}
%>
</body>
</html>
However, I got an error:
An error occurred at line: 6 in the jsp file: /index.jsp
Type mismatch: cannot convert from Object to ArrayList
So I'm wondering does anyone know:
What's going wrong on this specific error.
What is the best way to make JSP and servlet interact with each other? How the response from servlet be like? How JSP should handle this response?I don't want to write all the html markup in the servlet apparently.
Any hint/article/code example/blog will be greatly appreciated.

java rest jersey redirection for oauth2 not working

I am writing a java rest module, with jersey 2, whose first step is to get user credentials from an external Oauth2 server. When I try to redirect the user to the authentications service I see that url is correctly generated but It stays in the place. This is the code i am executing:
#GET
public String inOk(
#DefaultValue("") #QueryParam("code") String inoauthcode)
{
String oauthserv = "https://xxx";
String oauthclientid = "xxx";
String oauthsecret = "xxxx";
String oauthredirect = "http://myapp/url";
String oauthurl = "xxxx";
String redurl = "http";
String authurl = "http";
if (inoauthcode.equals("")) {
redurl = oauthserv + "?response_type=code&client_id=" + oauthclientid + "&redirect_uri=" + oauthredirect;
URI uri = UriBuilder.fromUri(redurl).build();
Response.temporaryRedirect(uri);
}
authurl = oauthurl + inoauthcode + "&redirect_uri=" + oauthredirect + "&client_id=" + oauthclientid + "&client_secret=" + oauthsecret;
...REST OF CODE ...
}
If I write the generated url to the screen It works perfectly but the temporaryRedirect command is doing nothing (aparently).
What am I doing wrong? Did I forget something? This code is almost directly copied from similar questions asked in this forum, but I can't get it to work.
It was an easy one this time, but took long to figure out.
The output of the function should not be a String but a Response:
public String inOk(
The redirection command should look like this:
return Response.seeOther(uri).build();
And now it works.

Cookies not being read correctly in JSP

First time post here, I hope its a valid question. I've been building a basic Java servlet which accepts 3 name/value pairs from a form on a page, sets those as 1. request attributes 2. session attributes and 3. cookie attributes. Cookies are then added to the response, and then the view (AccountSettings.jsp) is forwarded. The AccountSettings page is then supposed to use request.getCookies() to dump them into an array, then read the values from the array. All of this is supposed to happen every time I use this form.
My problem is that the cookie values are only correct the first time I use the form, then every time I use the form again, the cookies display the last value that was entered on page load. If I refresh the page, however, the cookies values will display correctly. I tried manually deleting the cookies in the Logout servlet (setMaxAge(0) then re-add to response) but this only produced a constant ArrayOutOfBoundsException at index 1, so I commented that portion out and leave the cookies alone.
I checked cookies associated with localhost in Chrome after the page is displayed, and the values are set correctly, so it seems to me like the JSP is drawn before the cookies are actually set correctly.
Any help on how to fix this would be appreciated. Here's my code.
Servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// get a new or existing session
HttpSession session = request.getSession();
// Instantiate user and populate values
User user = new User();
user.setUser(request.getParameter("user"));
user.setPass(request.getParameter("pass"));
// Get last page
String referringUrl = request.getParameter("referringPage");
session.setAttribute("user", user.getUser());
session.setAttribute("pass", user.getPass());
session.setAttribute("lastPage", referringUrl);
Cookie cookie1 = new Cookie("user", user.getUser());
Cookie cookie2 = new Cookie("pass", user.getPass());
Cookie cookie3 = new Cookie("lastPage", referringUrl);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
request.setAttribute("user", user.getUser());
request.setAttribute("pass", user.getPass());
request.setAttribute("lastPage", referringUrl);
try{
if (user.authorize()){
session.setAttribute("name", user.getName());
session.setAttribute("authorized", "1");
}else{
session.setAttribute("authorized", "0");
}
}
catch(Exception e){
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
user.destroy();
}
}
View:
<div id="content">
<div class="padding">
<%
if (!loggedIn){
out.print(
"Oops! I'm not sure how you got here..."
);
}else{
Cookie[] cookies = request.getCookies();
out.print(
"<h2>Account Settings</h2><br><br>" +
"<table>" +
"<tr>" +
"<th>Source</th>" +
"<th>Username</th>" +
"<th>Password</th>" +
"<th>Last Page Visted</th>" +
"</tr>" +
"<tr>" +
"<th>Request</th>" +
"<td>" + request.getAttribute("user") + "</td>" +
"<td>" + request.getAttribute("pass") + "</td>" +
"<td>" + request.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Session</th>" +
"<td>" + session.getAttribute("user") + "</td>" +
"<td>" + session.getAttribute("pass") + "</td>" +
"<td>" + session.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Cookies</th>" +
"<td>" + cookies[1].getValue() + "</td>" +
"<td>" + cookies[2].getValue() + "</td>" +
"<td>" + cookies[3].getValue() + "</td>" +
"</tr>" +
"</table>"
);
}
%>
</div>
</div>
so it seems to me like the JSP is drawn before the cookies are actually set correctly
That's correct. You're adding new cookies to the response (so they're only available in subsequent requests on the same domain and path), but your JSP is attempting to read cookies from the current request.
You need either to send a redirect instead of a forward by replacing
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
by
response.sendRedirect("AccountSettings.jsp");
or to copy cookie values as request attributes, so that JSP can get them as request attributes (you already know how to do that).
Unrelated to the concrete problem, passing around the password in a cookie is a very bad idea. That's a huge security hole. For your concrete functional requirement, you're better off storing the logged-in user as a session attribute instead.

Categories

Resources