This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
Closed 7 years ago.
I am new to JavaEE and have a query regarding a servlet that has multiple methods.
I want to know how I can call a specific method on a servlet, when I click "Submit" button in JSP.?
Someone have suggested to use HTML hidden fields but I have no idea on how to implement them in Jsp.
You can just give the submit button a specific name.
<input type="submit" name="action1" value="Invoke action 1" />
<input type="submit" name="action2" value="Invoke action 2" />
<input type="submit" name="action3" value="Invoke action 3" />
The name-value pair of the pressed button is available as request parameter the usual way.
if (request.getParameter("action1") != null) {
// Invoke action 1.
}
else if (request.getParameter("action2") != null) {
// Invoke action 2.
}
else if (request.getParameter("action3") != null) {
// Invoke action 3.
}
Hidden fields in a JSP are the same as in HTML:
<input type="hidden" name="name" value="value">
Then in your servlet you can do
if (request.getParameter("name").equals("value")) { /* do something */ }
Depends on which method you want to call. Assuming that the URL Pattern declared for your servlet in web.xml is /myservlet*,
For doGet, just use a URL
http://localhost:8080/myservlet?name=value
For doPost, use a form.
<form action="/myservlet" method="post">
<input type="text" value="value" name="name" />
</form>
i dont think having 3 buttons is the best solution,basis on the logic and parameters method asked,
i believe this can be an accurate solution-
On the basis of parameters passed ,we can have 2 methods to access different actions via javascript-
1)getting values from user,checking them in javascript.
2)getting values from user,checking them in javascript,assigning values to hidden variables accordingly,calling servlets and using those hidden values.i have elaborated method1.
<html>
<head>
<script type="text/javascript">
function nawab() {
param = document.getElementById('param1').value;
alert('in nawab');
if (param != "") {
if (param === 'abc') {
alert('abc');
document.forms[0].action = "nawabServlet";
document.forms[0].submit();
}
if (param === 'def') {
alert('def');
document.forms[0].action = "nawabServlet2";
document.forms[0].submit();
}
}
else{
alert('empty');
document.forms[0].action = "nawabServlet";
document.forms[0].submit();
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>nawab has come</title>
</head>
<body>
<form>
param1:<input type="text" name="param1" id="param1"></select>
<input type="submit" onclick="nawab()">
</form>
</body>
</html>
Related
This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 7 years ago.
I have a JSP page with a textarea and a button, a servlet and a new jsp:
My 3 problems are:
My analysis.jsp is empty. My borwser opens a new tab but without the text "Hello World"
The variable "sql" in my java class is empty too. It should contain the text from my textarea
How can I hand over after my variable sql isn't empty (after analyze) new new code to a new jsp
index.jsp
<form action="ServletName" method="post" target="_blank">
<div class="form-group">
<label for="codeEditor" style="margin-top: 15px;">Code:</label>
<textarea name="codeEditor" class="form-control" id="codeEditor" rows="15" style="resize: none;"></textarea>
</div>
<div class="analysisButton">
<button type="submit" id="startAnalysis" class="btn btn-default btn-block" style="margin-top: 10px;">Start analysis</button>
</div>
</form>
ServletName.java
protected void doPost(...) ...{
String sql = request.getParameter("codeEditor");
response.sendRedirect("/analysis.jsp");
}
analysis.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
Many thanks in advance
UPDATE: nevermind the variable sql isn't empty <(^,^<) but the other 2 questions are open :)
Yes, this may be as simple as
JSP
<form action="some_url" method="post" >
<inputarea name="sqlQuery" >
<input type="submit" value="Sql query" >
<form >
In your servlet, you'll have something like
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
...//check that the request is correct
String query = request.getParameter("sqlQuery");//name of textarea
try{
Connection conn = getConnection();//Search SO for how to get a connection
PreparedStatement stmt = conn.prepareStatement(query);
//if your query has any arguments(?) (e.g select * from tbl where id=?), then you should set them too
//stmt.setInt(1, 1000);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
//get database dana here
int someIntVal = rs.getInt("intColumn");
String someStr = rs.getString("someStringColumn");
}catch(SQLException e){
//handle exception
}
}
You could do this using a simple form submit:
<form method="POST" action="/myServletPath">
<inputarea name="sqltext" ...
Your servlet (with url mapping 'myServletPath') can then, in the doPost method:
String sql = request.getParameter("sqltext")...
And then do whatever you want.
WARNING: If this is code for your production application, then be aware of SQL injection attacks. This is typically code you wouldn't write for any application that trusts users other than yourself.
I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.
I am new in servlets-
I am filling text in form but value in request is null-
In login page-
<body>
<form action="">
<input type="text" name="uname">
<input type="text" name="pwd">
link
</form>
</body>
In DisplayPage-
<body>
Display:
<%
String uname=(String)request.getParameter("uname");
String upass=(String)request.getParameter("pwd");
out.println(uname+" - "+upass);
Enumeration<String> enumeration = request.getParameterNames();
boolean b=enumeration.hasMoreElements();
out.println(b);
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
String data=(String)request.getParameter(name);
out.println(name+" - "+data);
}
%>
</body>
Now in my result value of uname and upass is null and hence boolean b is false.Weird!
My Question Is- If request object is created when we use anchor tag since there is no NPE on calling getParameter() on request object,so what kind of data attached with this request object.why this is provided to us?
Because you are not submitting your form to server or not passing any value in url, instead you are clicking on link, which will redirect it to your link.
<body>
<form action="display.jsp"> // added action
<input type="text" name="uname">
<input type="text" name="pwd">
<button type="submit">Link</button> // added submit button
</form>
</body>
For Updated Question
On server side every request is handled as HttpServletRequest object. So when we submit the form, every input field is submitted and then it is retrieved from the request object on server side.
In a form I have a field called Description. Through CKEditor I need to pass that value and store it in my database. Can anyone help me out? Here is my code:
<div id="descriptionMore" style="margin-bottom:20px;margin-top: 38px;margin-left: 101px;">
<aui:layout>
<aui:column columnWidth="240">
<liferay-ui:input-editor width="880" cssClass="richText" />
</aui:column>
</aui:layout>
</div>
First of all, make sure you are using aui:form.
Link which will be useful for you.
Save Content of CKeditor via "aui:form"
Add HTML Editor to Portlet
CK editor in Liferay 6.0
Adding CK Editor in Liferay
This will defiantly be useful for you.
<%
Content content = (Content) request.getAttribute(ApplicationConstants.CONTENT);
%>
<portlet:actionURL var="saveOrUpdateContentUrl" name="saveOrUpdateContent">
<portlet:param name="redirect" value="<%=currentURL%>" />
</portlet:actionURL>
<liferay-ui:header title='<%= (content==null) ? "new-content" : "edit-content" %>' backURL="<%=redirect %>" />
<aui:form method="post" name="content_fm" onSubmit='<%= "event.preventDefault(); " + renderResponse.getNamespace() + "saveEntry();" %>'>
<aui:fieldset>
<aui:field-wrapper label="product-content">
<liferay-ui:input-editor />
<aui:input name="content" id="content" type="hidden" />
</aui:field-wrapper>
<aui:button-row>
<aui:button type="submit" />
</aui:button-row>
</aui:fieldset>
</aui:form>
<script type="text/javascript">
function <portlet:namespace />initEditor() {
return '<%= UnicodeFormatter.toString((content==null)? StringPool.BLANK : content.getContent()) %>';
}
function <portlet:namespace />getContent() {
return window.<portlet:namespace />editor.getHTML();
}
function <portlet:namespace />saveEntry() {
document.<portlet:namespace />content_fm.action = '<%=saveOrUpdateContentUrl%>';
document.<portlet:namespace />content_fm.<portlet:namespace />content.value = <portlet:namespace />getContent();
alert(<portlet:namespace />getContent());
submitForm(document.<portlet:namespace />content_fm);
}
</script>
This above code is properly working in Liferay 6.2. You should fetch CKEditor content using alloy script or javascript and set in hidden parameter for storing the value.
I am using onclick event in anchor tag. when i clcik the anchor, I am invoking a java script function where I change the value of one input element and submit the form. The value is changed but the form does not submit the value. Please help me on this. FYI that if i create an element and add in the form before submission, it works. Why is not working in the first scenario.
<form name="form" >
<input type="hidden" name="input" value="test"/>
<a onclick='testMethod("test")'>click </a>
</form>
script used is
function testMethod(value)
{
if(serviceName != null && jQuery('#form') != null)
{
document.forms['form'].getElementById('input').value = value;
document.forms['form'].action = jQuery('#newAction').val();
document.forms['form'].submit();
}
}
The main problem here is you're trying to access the input by id when it doesn't have one set:
(Added id to form and id to input so we can select them easily):
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a onclick='testMethod("test")' >click</a>
</form>
And the javascript to match (updating to use jQuery's selectors since you indicated you have jQuery support available):
function testMethod(value)
{
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
}
You can also update your code such that you aren't including the binding to the onclick method in the DOM, but attaching to it directly in javascript:
Changing the a element to have an ID:
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a id="submitLink">click</a>
</form>
The javascript could now look like this:
$(document).ready(function() {
$('#submitLink').on('click', function(event) {
event.preventDefault();
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
});
});