<html>
<body>
<form action="Test1.jsp" method="post">
<select name="source" onchange="">
<option value="rss">RSS LINK</option>
<option value="other">OTHER LINK</option>
</select>
Enter URL to be added <input type="text" name="url" size=50>
Enter the Source Name of the URL<t><input type="text" name="source1" size=50>
<input type="Submit" name="submit1" value="Add URL in DB">
</form>
</body>
</html>
The above code is stored in Addurl1.jsp file which calls the other jsp file named Test1.jsp.
The code under Test1.jsp is as follows
<%# page import="myfirst.*" %>
<%
String url1=request.getParameter("url");
String source1=request.getParameter("source1");
myfirst.SearchLink p=new myfirst.SearchLink();
String result=p.addURL(url1,source1);
out.println(result);
System.out.println(result);
%>
Test1.jsp calls addURL(String, String) function of SearchLink.java program.
In the dropdownbox of Addurl1.jsp program, if the user selects RSS link, the addURL() method must be called. If the user selects OTHER LINK, there is another method named addURL1() in the same java program which must be called.
Please let me know how the above codes can be modified inorder to achieve my task.
Thanks in advance!
At first it is better to change Addurl1.jsp into a servlet and implement the doPost method. Jsp files are supposed to only contain the presentation layer and no Java code. Java code should go in servlets (or controllers if you are using an MVC framework).
What you are asking can easily be achieved with an if statement:
final String RSS_LINK = "rss";
final String OTHER_LINK = "other";
String url1=request.getParameter("source");
String result="";
if (url1 != null && url1.equals(RSS_LINK)) {
result=p.addURL(url1,source1);
}
else if (url1 != null && url1.equals(OTHER_LINK)) {
result=p.addURL1(url1,source1);
}
Related
I have a .jsp file of a basic chat with a bot, the page is designed as a div that should hold the messages that outcome or income from a form.
The form has one input line that should hold the message.
I want to call a java function that's in a different .java file from the div only after the form is submited
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b>
<%
if (ctx.isLoggedIn()) //if there is someone in the current session
{
String name = ctx.getName(); // puts the name in the page
out.write(name); // same as last row
}
%></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox" style="overflow-y: scroll;">
<%
//the place I want to call the function
%>
</div>
<form name="message" action="#" method="post">
<input name="usermsg" type="text" id="usermsg" size="63" oninput="buttonEnabled()"/>
<input name="submitmsg" type="submit" id="submitmsg"/>
</form> <!-- the form that is served -->
</div>
ctx is defined as an object from a class I created
Context ctx = new Context(pageContext);
I tried to call the function like this-
<%
if(request.getParameter("usermsg").toString().length() > 0)// not empty
out.write(ctx.handleMessages());
%>
but It didn't work for some reason.
the function handleMessages() has a queue that contains all of the messages from the server and from the client and returns a String that is already build as an HTML code-
returnedMsg += "<b>"+message.getUser()+"</b> - <a style='color:gray;'>"+message.getTime()+"</a>";
returnedMsg += "<br>";
returnedMsg += "<a>"+msg.getText()+"</a>";
returnedMsg += "<hr>";
So every chat message should look like that-
It would really help me if someone knows how to call handleMessages() from that div when the form is submited.
Thank's ahead.
As we know every jsp program there is a servlet behind the jsp page. I have used a jsp page to make a form (its a very small form), and in the same jsp i used scriptlet tags and made a way to get the inserted form data, and display it using out.print(). but the problem is it when i run it, the form is displayed., but when i submit is, it doesn't recognize the servlet page (error coming as "The requested resource is not available"). i will put the code below., please help me friends to solve this problem. thank you.
i did this in netbeans.
jsp page name is- "hello.jsp"
the servlet page name behind the jsp page is: "hello_jsp.java".
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<form action="hello_jsp" method="post">
<input type="text" name="y"/>
<input type="submit" value="submit"/>
<%
if(request.getParameter("y")!=null) {
String s = request.getParameter("y");
if(s.equals("hello")){
out.print("welcome"+s);
}else{
out.print("not welcome");
}}
%>
</form>
</body>
</html>
My guess is that you need to change
<form action="hello_jsp" method="post">
to
<form action="hello.jsp" method="post">
<!-- ^---- change is here -->
The externally-accesible resource is the jsp, not the servlet. (By default, I'm sure some config-fu could change that.)
Or, of course, if the page is supposed to submit to itself, don't include action at all. The default is to submit to the current page.
<form method="post">
Hey i am a php developer and this is my first go with jsp. Now i retrieved a Json string from my class and converted it into GSON. I display a field in my result.jsp for eg:- ID and on clicking the id it should go to details.jsp and show more info about that ID
Currently my result.jsp is as follows:-
<html>
<body>
<div class="list-group">
<%
String json = (String)request.getAttribute("jsonstring");
Gson gson = new Gson();
ConCom diff = new ConCom();
diff = gson.fromJson(json, ConCom.class);
List<ComparisonResultDTOarr> ls = diff.getComparisonResultDTOarr();
for(int i = 0;i<ls.size();i++)
{
List<AuditItemLogsDTOArr> lsinner = ls.get(i).getAuditItemLogsDTOArr();
%><a href="#" class="list-group-item">
<%out.println(lsinner.get(0).getKeyAsString());%></a><%
}
%>
</div>
</body>
</html>
I read around SO and googled it and understood that that i could make a hidden form. Now I create a form with the following two fields and using the anchor tag i submit the form. But the values in the form need to be posted according to the ID clicked, how can i make that dynamic?
So if my form is as follows:-
<form action="details.jsp" method="post">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="phone">
</form>
And my details.jsp will be like:-
<%= request.getParameter("firstname") %>
<%= request.getParameter("phone") %>
I want the firstname and phone to be set according to the ID clicked and the form to be submitted. I can obtain the String/Integer value from my diff object in this page. Would i need to use JQuery? Any help?
Also i know i should be using JSTL. And i will get to that soon. Thank you.
You could call a javascript function during the onclick event of your anchor tag:
<a href="#" onclick="submitHiddenForm("<%=lsinner.getFirstName()%>", "<%=lsinner.getPhone()%>");">...
Your JS function would like like:
function submitHiddenForm(firstName, phone) {
document.getElementById("firstname").value = firstName;
document.getElementById("phone").value = phone;
// attach a name attribute to your form tag
// submit the form
document.myForm.submit();
}
I hope this helps.
EDIT: changed diff to lsinner, since that's the var used in the loop.
On click of the ID call a javascript function passing the values inside the function you can dynamically set the values of the form by getting each element like document.getElementById("firstname").value=value passed similarly set the other fields and in the end document.myform.submit();
Note since we are fetching HTML elements by Id you can use
<form action="details.jsp" method="post" name="myform">
First name: <input type="hidden" name="firstname" id="firstname"><br>
Last name: <input type="hidden" name="phone" id="phone">
</form>
type="hidden" will hide the elements.
check these for better understanding.
How to submit a form using javascript?
If you have the diff object in details.jsp as well, it should be enough to pass only the ID as a parameter, in a normal link.
details
You'd probably do the same in PHP.
JQuery is client side JavaScript and not required to solve your problem.
I am sending a request to the servlet it returning some data from db am constructing table and check box with the resulted data in, servlet itself using out.println and now i need to do select the data for further manipulation using check box and now i dono how to get a value of selected text boxes.
here is my servlet code,
ps=connection.prepareStatement("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id;");
ResultSet rs=ps.executeQuery();
out.println("<table>");
/*out.println(executionValues.append("<tr><td>").append("Test Case Name :").append("</td><td>").append("Scenario Name :").append("</td></tr>"));*/
while(rs.next()){
out.println("<li class='panel' value='"+rs.getInt("scenario_id")+"'><b>Scenario Name:</b>"+rs.getString("scenario_name")+"</li><b>Test Case Name:</b>"+rs.getString("tc_name")+"<input type=\"checkbox\" name=\"checkbox\"></li>");
}
you should remove the ;
your sql query:
("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id;");
you should change like:
("select t.tc_name,s.scenario_name,t.scenario_id from testcase t, scenario s where t.scenario_id=s.scenario_id");
You're printing a whole new <html> and <form> around every single checkbox. Your HTML ends up in browser like as:
<html>
<head></head>
<body>
<html><body><form><input type="checkbox"></form></body></html>
<form><input type="submit"></form>
</body>
</html>
This is syntactically invalid HTML. You need to rewrite your code so that all checkboxes and the submit button ends up in the same form:
<html>
<head></head>
<body>
<form>
<input type="checkbox">
<input type="submit">
</form>
</body>
</html>
Then you also don't need those ugly JavaScript workarounds. You just give the checkboxes the same name, but a different value. This way you can just grab the checked values by HttpServletRequest#getParameterValues().
String[] users = request.getParameterValues("user");
For example:
<form name="input" action="html_form_action" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<br><br>
<input type="submit" value="Submit">
</form>
If you check both of checkboxes your server will receive this parameters like so:
http://sitename.com/your_page.jsp?vehicle=Bike&vehicle=Car
After that you can get values like this:
String checkboxValues = request.getParameter("vehicle");
checkboxValues gets all values separated by comma.
Refer this link:
http://theopentutorials.com/examples/java-ee/servlet/getting-checkbox-values-from-html-form-in-servlet/
Dear suganth It is not appropriate now to put html code in servlet. Instead you use jsp pages.
but if you have to do in this way then You may provide
if(conditionMatch){
// code for checked box
}
else{
// code for unchecked box
}
Hope this helps
I have a JSP form. My requirement is to get this form's data and create a java beans object on the server side.
Example: my form has fields like Name, SSN, EMAIL & Phone Number
public class Test {
long ssv= 1282199222991L;
long phone= 4082224444L;
String email = "abcdef#yahoo.com";
String name="abcdef"
}
From the knowledge i have , i was thinking to create bean object using servlet, which is created out of JSP, at the server side. My question is how i access this "server created" servlet for getting the variables data?
PS: I am beginner in web programing & server side scripting. Please let me know if the question is not clear. Any information would very valuable for me. Please do let me know if i am thinking in the right way. Trailer Thanks!
The JSP should indeed submit the form to the servlet. The servlet should indeed create the bean and use it to transfer the submitted data through the necessary layers (save in database using DAO class and/or redisplay in result JSP after submit).
Here's a kickoff example of how the JSP should look like:
<form action="register" method="post">
<p><input name="name">
<p><input name="email">
<p><input name="phone">
<p><input name="ssv">
<p><input type="submit">
</form>
And here's how you could write the doPost() method of the servlet which is listening on an url-pattern of /register.
String name = request.getParameter("name");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String ssv = request.getParameter("ssv");
// Do the necessary validations here and then ..
User user = new User(name, email, phone, Long.valueOf(ssv));
// Now you have an User javabean with the necessary information.
// Do with it whatever you want. E.g. saving in database.
userDAO.save(user);
See also:
Beginning and intermediate JSP/Servlet tutorials
Well its been a long time since this question was asked. However, I believe this is the required answer.
Start with a HTML form to collect the data as below (I used only username and email)
<HTML>
<BODY>
<FORM METHOD=POST ACTION="process.jsp">
Name <INPUT TYPE=TEXT NAME=Name SIZE=20><BR>
Email <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
To collec this data in a bean create a class e.g. MyData as shown
package datapackage;
public class MyData{
String name;
String email;
public void setName( String value )
{
name = value;
}
public void setEmail( String value )
{
email = value;
}
public String getName() { return name; }
public String getEmail() { return email; }
}
Make sure it is compiled and available to your application's environment
Then create a JSP page process.jsp to receive this data
<jsp:useBean id="data" class="datapackage.MyData" scope="session"/>
<jsp:setProperty name="data" property="*"/>
<HTML>
<BODY>
You can output the data here too with e.g. <%= data.getName() %> but that was not your question
</BODY>
</HTML>
At this point you have an object in session (can be in page, application and request scopes too if you set the scope parameter on the jsp page to any of them). Any servlet that is called while the user still has a valid session after filling the form can access the object from session like this;
package datapackage;
import java.io.IOException;
import javax.servlet.http.*;
public class SalesServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
HttpSession session = request.getSession();
MyData d = (MyData)session.getAttribute("data"); //data is the variable name set in the JSP page
}
}
This, I believe, is the general flow to your show you how you can access a Java Bean's data from within a Servlet.
Take a look at the tutorial on Handling Form Data
if you need to be far to servlets, you can pass object to other JSPs from one page to another.
let's say your class is com.company.beans.User
on first page GetInput.jsp
you have the following code
<jsp:useBean id="user" class=com.company.beans.User />
now the object user can be reused in all JSPs pages such the container create an instance of the class ..
in the same page you can have a form that pass the form input to another jsp page
<form action="second.jsp">
<input type="text" name="uname"/>
<input type="password" name="pass"/>
<input type="submit" value="submit"/>
</form>
on the second page you can access the object named user
<jsp:useBean id="user" class="com.deeb.beans.User" />
<%
user.setUsername(request.getParameter("uname"));
user.setPassword(request.getParameter("pass"));
%>
also on the another page you can get the values