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)
Related
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
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 have this application where i want to populate a text file on the basis of entries entered from user interface.
I chose Struts1 for this and i have been able to complete most of the functionalities.But the part of keeping on populating the
text file on the basis of user entries in my JSP is something i am struggling with. The following are the flow of pages on user interface
1.'Accept user entries' http://www.image-share.com/ijpg-1178-104.html
2.'Ask for scan data on the basis of entries in page1' http://www.image-share.com/ijpg-1178-105.html
3.'Submit after entering the scandata. ' http://www.image-share.com/ijpg-1178-106.html
(I have been able to straighten the null values in the images via session variables. Thanks to Dave)
message is seen with null entries like this Post validation.
My questions is:
What should be used so that there is a scenario that the users enter the Scan Data on page 2 and can continue to enter
more scan data values by falling back on the same JSP . I was thinking on the lines of reloading the page using JavaScript
on the button click. Is it the right approach?
The relevant code for this is
<html:form action="txtwriter">
<% String itemname = (String)session.getAttribute("itemname"); %>
<% String lotnumber = (String)session.getAttribute("lotnumber"); %>
<% String godownname = (String)session.getAttribute("godownname"); %>
<br/>
<% String message = (String)session.getAttribute("message");
session.setAttribute( "theFileName", message ); %>
Filename : <%= message %>
<br/> Item Name :<%= itemname %>
<br/> Lot Number :<%= lotnumber %>
<br/> Godown Name :<%= godownname %>
<br/> <bean:message key="label.scandata"/>
<html:text property="scanData" ></html:text>
<html:errors property="scanData"/>
<br/>
<html:submit/>
/* How should the submit button handle the onClick event so that when the users click
after entering the text.
1. The entered text must be populated in the text file using a different action class. (I have this part working)
2.They must be on the same jsp with the scanData text box cleared waiting for the next user entry into that text
box so that this subsequest entry can also be entered into the text file.
Is there a way i can empty the 'scanData' textbox by accessing it by name inside my action so that i can empty it from my action class?
(I am looking for this answer)
*/
I used this inside the LoginAction.java
HttpSession session = request.getSession();
session.setAttribute("message", textFile);
session.setAttribute("itemname",loginForm.getItemName().trim());
session.setAttribute("lotnumber",loginForm.getLotNumber().trim());
session.setAttribute("godownname",loginForm.getStockGodown().trim());
(Not an answer; refactored but untested code for others trying to help.)
This is a refactored action, making it easier to see what's actually going on; the original code is difficult to reason about. The trim() functionality is moved to action form setters to avoid redundancy.
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if (invalidForm(loginForm)) {
return mapping.findForward("failure");
}
String fileName = createFile(loginForm);
request.setAttribute("message", fileName);
request.setAttribute("itemname", loginForm.getItemName());
request.setAttribute("lotnumber", loginForm.getLotNumber());
request.setAttribute("godownname", loginForm.getStockGodown());
return mapping.findForward("success");
}
private String createFile(LoginForm loginForm) throws IOException {
ServletContext context = getServlet().getServletContext();
String driveName = context.getInitParameter("drive").trim();
String folderName = context.getInitParameter("foldername").trim();
String pathName = driveName + ":/" + folderName;
new File(pathName).mkdirs();
String fileNamePath = pathName + createFileName(loginForm);
ensureFileExists(fileNamePath);
return fileNamePath;
}
private void ensureFileExists(String fileNamePath) throws IOException {
boolean fileExists = new File(fileNamePath).exists();
if (!fileExists) {
File file = new File(fileNamePath);
file.createNewFile();
}
}
private boolean invalidForm(LoginForm loginForm) {
return loginForm.getItemName().equals("")
|| loginForm.getLotNumber().equals("")
|| loginForm.getStockGodown().equals("");
}
private String createFileName(LoginForm loginForm) {
return loginForm.getItemName() + "_"
+ loginForm.getLotNumber() + "_"
+ loginForm.getStockGodown() + "_"
+ createFileNameTimeStamp() + ".txt";
}
private String createFileNameTimeStamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' hh.mm.ss z");
String dateTime = sdf.format(Calendar.getInstance().getTime());
String[] tempDateStore = dateTime.split("AD at");
return tempDateStore[0].trim() + "_" + tempDateStore[1].trim();
}
}