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
Related
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.
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.
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.
I have created a simple servlet in which a user will be presented with 2 questions, answering either true or false. My problem lies in retrieving the answers selected by the user.
Code:
out.println("<FORM ACTION=\"Game\" METHOD = \"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q1rad2\" onclick = \"getAnswer('b')\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q2rad2\" onclick = \"getAnswer('b')\"> False<br>" +
out.println("<Center><INPUT TYPE=\"SUBMIT\"></Center>");
);
Each question has 2 radio buttons, Q1rad1 & Q2rad2, for answering True or False. How can i know the value selected by each user when the submit button is pressed.
I understand it may be more efficient when using Javascript but for the purposes of this problem I must be using servlets.
You have to define the value you want to retrieve when the radio button is selected
The value setting defines what will be submitted if checked.
The name setting tells which group of radio buttons the field belongs to. When you select one button, all other buttons in the same group are unselected.
<input type="radio" name="Q2" onclick="getAnswer('b')" value="b">
<input type="radio" name="Q2" onclick="getAnswer('a')" value="a">
In your Servlet which will recieve the request you'll have something like
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the value of the button group
String q2 = request.getParameter("Q2");
// compare selected value
if ("a".equals(q2)) {
...
}
...
}
You haven't named your radio buttons correctly. Each radio option for the same question need the same name attribute. Also, you should have a value attribute on each <input type="radio">. I'm not sure you need the onclick handler at all. You should also have a </form> closer tag. Your form might look like this:
out.println("<form action=\"Game\" method=\"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q1\" value=\"False\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q2\" value=\"False\"> False<br>" +
"<Center><INPUT TYPE=\"SUBMIT\"></Center>" +
"</form>"
);
And then in the doPost() method of servlet that handles the form submission, you can access the values using request.getParameter(). Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");
// more processing code...
}
Give the same name to the radios of the same question, and set different values.
Look at this page.
Then in the request you will get a parameter with the name of the radio group and the value selected.
After submit the servlet the receives the post can use:
String value = request.getParameter("radioName");
For your HTML Code the below lines are enough
protected void doPost(HttpServletRequest req,HttpServletResponse res){
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");`
}
For example, Considering your HTML Code.
If Q1 is pressed
"TRUE"
then it would be our "Input" in Servlet.
I am using RestfbApi to fetch my friends' names and display on a web page. I also want a corresponding checkbox to each friend, since from the use of table tag , I have friend's name as well as corresponding checkbox.
As I generated checkboxes dynamically , how to make sure which checkboxes are checked when my app runs. The scenario is if I checked five friends and press post to wall button, a wall should be post to all five friends. I know how to post a wall just want to know how to map user selected friends(checked ones) to java code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
User user = facebookClient.fetchObject("me", User.class);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1></H1>\n" +
"</BODY></HTML>");
JsonObject accounts = facebookClient.fetchObject("me/friends",JsonObject.class);
JsonArray data = accounts.getJsonArray("data");
for(int i = 0; i < data.length(); i++)
{
String id = data.getJsonObject(i).getString("id");
Double int1 = Double.parseDouble(id);
String strName = data.getJsonObject(i).getString("name");
out.println("<table>");
out.println("<tr><td> <input type='checkbox' name='wahtevername' value='"+int1 +"'>"+strName+" </td></tr>");
out.println("</table>" );
}
}
out.println(docType +"<form method=\"GET\">"+"<input type=\"submit\" value=\"Post to wall\" name=\"option\">"+"</form>");
Use request.gatParameterValues("whatevername") to get an array of the values of selected checkboxes.
(Btw, it would be better to place the html code in JSP. Set the list as request attribute and then use JSTL's <c:forEach> to iterate)