I am using Spring 3. In my jsp I have a form
<form action='componentAction.html' method='POST'>
<input type='hidden' id='action_' name='componentAction' value=""/>
</form>
The value of the form's action changes to either start, stop or pause.
I also have 3 buttons: start, stop and pause. Upon pressing one of these buttons the value of the form changes.
<input type="button" value="Start" onclick="changeFormValueAndSubmit('start')">
<input type="button" value="Stop" onclick="changeFormValueAndSubmit('stop')">
<input type="button" value="Pause" onclick="changeFormValueAndSubmit('pause')">
I would like to be able to send the value of the form to my controller via ajax call after the press happens.
Can someone please show me the right way of doing it? Alsos hould I use POST or GET?
I have tried following tutorials such as
http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/
http://hmkcode.com/spring-mvc-json-json-to-java/
http://java.dzone.com/articles/using-spring-mvc%E2%80%99s
But I have failed miserably.
Thanks to anyone for their hlep in advance!
Using JQuery you can use the following in your changeFormValueAndSubmit() function
function changeFormValueAndSubmit(buttonName) {
var formData = $('form').serialize();
jQuery.post('/path', formData, function(d) {
// handle response
});
...
}
Note: that in this example, jquery will send all the data fields in your form.
Make your you include the jquery framework in your JSP and also have a controller method in spring to handle the POST.
POST is preferable over GET.
On server side using Spring 3 annotations, something like
#Controller
public class ExampleController {
#ResponseBody
#RequestMapping(value = "/path", method=RequestMethod.POST)
public String post(#RequestParam String componentAction) {
// do work
...
return "OK"; // depends on what you need to send back...
}
}
You must enable MVC annotations. See http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-annotation-driven
POST or GET will determine if the form data is sent encoded in the URL (GET) or in embedded in the http requests message body (POST). Since it is an ajax call, the URL will not be shown directly to the user, but either way, the user can see the contents of the request under the browser's developer tools.
The simplest way to get spring to direct traffic to your jsp is like such:
<servlet-mapping>
<servlet-name>MyJSPServlet</servlet-name>
<url-pattern>/urlFromOutside</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MyJSPServlet</servlet-name>
<jsp-file>/pathToJspFile/MyJspFile.jsp</jsp-file>
</servlet>
To get the form data, in your jsp file, you have access to the request object and can get the parameters like so:
<%= request.getParameter("componentAction") %>
Related
I would like to know how can I solve this problem, let me explain: I want to create a search bar and send the user to a jsp view with the results. I created in my controller the next method :
#RequestMapping(value = "/search={productName}", method = RequestMethod.GET)
public ModelAndView getProducteByName(#PathVariable("productName") String productName) {
ModelAndView modelview = new ModelAndView("/productSearch");
List productsByName = productService.getProductByName(productName);
modelview.addObject("productsByName", productsByName );
return modelview;
And I have a form in a jsp file like this:
<!-- Search form -->
<form class="form-inline md-form form-sm mt-0" method="get" >
<i class="fas fa-search" aria-hidden="true"></i>
<input class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" name="search"
aria-label="Search">
</form>
The problem is when I put anything to search in the bar search, it works put it puts me a ? in the url, so the controller doesn't understand the requestMapping.
Example: http://localhost:8080/projectbotigabio/search=potato
and it puts me: http://localhost:8080/projectbotigabio/?search=potato
I've tried a lot of things, including trying to putting as a method "post" instead of "get", but it doesn't work... any solution?
Web browsers only support 3 kinds of form submission:
method="get"
Every form value is added to the URL using ?name=value&name=value&...
method="post"
Every form value is added to POST with content type application/x-www-form-urlencoded and content name=value&name=value&...
method="post" enctype="multipart/form-data"
The POST request has content type multipart/form-data, and the content is a multipart with each part being a form value.
Web browsers cannot build the URL you want, so you have to do it yourself, i.e. prevent the web browser from sending the POST request, and send your own request using Ajax. If that's what you want, put on your learning hat and start studying how that works.
I recommend that you stop trying to use a non-standard URL syntax, and use the standard GET processing.
Either way, I suggest you learn more about how HTML forms work, before you try deviating from the standards any further.
Could you help me to come up with solution.
There are JSP-page which sends form parameters to servlet.
Usually I parse parameters by HttpServletRequest.getParameter() which works fine for forms with tiny parameter numbers.
Now I'm developing application which has a lot of JSPs with number of parameters and the standard way of form processing is inconvenient.
I think that possible solution might be by using -action.
I don't understand whether it works for me.
I browsed a lot of materials but find nothing about it.
I mean that there is any information regarding possibility to get form parameters in jsp by ,
automatically create instance of the entity class,
map all the parameters to entity-properties and send the entity-instance to the servlet.
Please take a look at the code:
index.jsp
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="NewFormServlet" enctype="application/x-www-form-urlencoded">
<jsp:useBean id="client-bean" class="model.entity.Client" scope="request"/>
<h3>Please enter client information</h3><br>
Client first name<input type="text" name="first-name"/><br>
<jsp:setProperty name="client-bean" property="firstName" value="${requestScope.first-name}"/>
Client last name<input type="text" name="last-name"/><br>
<jsp:setProperty name="client-bean" property="lastName" value="${requestScope.last-name}"/>
Client address<input type="text" name="address" size="100"/><br>
<jsp:setProperty name="client-bean" property="address" value="${requestScope.address}"/>
Client city<input type="text" name="city"/><br>
<jsp:setProperty name="client-bean" property="city" param="${requestScope.city}"/>
Client postal code<input type="text" name="postal-code"><br>
<jsp:setProperty name="client-bean" property="postalCode" value="${requestScope.postal-code}"/>
<input type="hidden" name="jsp-identifier" value="client-form">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is incorrect in this code? Thank you in advance.
You should first think about what occurs on server and what occurs in browser, as well as what is transmitted via HTTP. A form submission uses many phases :
on server : the JSP is executed using servlet context, session, and request attributes, with still full access at the previous request (parameters, ...) => all that generates a HTML page (with eventually css or javascript linked or included)
on browser : the browser gets and parses the HTML page, optionnaly gets linked resources (images, etc.), and display the form to the user
on browser : the user fills the input fields of the form and clicks the input button
on browser : the browser collates data form input fields, generate an new HTTP request (usually a POST one) and sends it to server
on server : the servlet container pre-processes the request (until that is is only a stream of bytes conforming to HTTP protocol) and calls the appropriate servlet method with a new HttpServletRequest reflecting current HTTP request, and a HttpServletResponse to prepare what will be sent back to browser after processing
All that means that anything you can do to request attributes in the JSP part will be lost at the time of processing of the submitted form by the servlet. You can only rely on session attributes, and on input form fields that will be accessible as request parameters.
So with your current JSP, the Servlet will find nothing in request attributes (it is a different HttpServletRequest) and will only be able to use parameters with names firstName, lastName, address, city, etc.
I can understand it is not the expected answer, but HTTP protocol is like that ...
EDIT per comment :
You can put the attribute in session, and then the servlet will use the same session as the JSP. But read again what I wrote above and think when things happen :
on server, when executing the JSP, you create an empty Client bean that you put in session scope, and use its value to initialize the form fields. Stop for the server part
on client, user fills the input fields - the server knows nothing on that - and submit the form through a new request
on server, the servlet has the values in request parameters, but the session still contains the previous values and so the Client bean has null values
I'm sorry but there's not enough magic for the server to automatically find in its attributes (either request or session) what comes from form submission : it only exists in request parameters, and it is the servlet job to process them and eventually put them in attributes.
Edit:
It appears that jsp:useBean is an old school way to collect up a group of parameter values for easier display on a page.
It does not add an attribute when the request is posted.
Based on that,
I see little value in the jsp:useBean tag,
since you can use el expressions to access attributes that you set in a servlet.
This does not help you get the posted parameter values into a bean in the servlet.
You can write a method on the bean to extract the parameter values from the request (visitor pattern).
For example:
class bean
{
private String value;
public void loadFromHttpServletRequest(final HttpServletRequest request)
{
value = request.getParameter("value");
}
}
Consider using a package like spring-mvc.
I want to send a post request in java.
I have seen examples for the post request by using Http Client.
But i want use sendRedirect method.
For ex,
https://processthis.com/process?name=xyz&phone=9898989898
I want to use post request to send those parameters. So, those params will not be visible to any one and at the same time i need to redirect my url to that url as,
response.sendRedirect("https://processthis.com/process");
According to RFC2616 with HTTP/1.1 you can send 307 response code, which will make user-agent to repeat it's POST request to provided host.
In your case just do
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", url);
response is your HttpServletResponse object.
Hope this helps.
When a browser receives an HTTP redirect code it will always perform a GET or HEAD to the given url by standard. This is why data must be sent by query strings.
If you want to simulate a redirect by POST, you can send to your client a form with the information you want and, on the page load event, you automatically submit the form using Javascript (commonly used to comunicate between different servers, used by SAML protocol for example). Here's an example:
<form name="myRedirectForm" action="https://processthis.com/process" method="post">
<input name="name" type="hidden" value="xyz" />
<input name="phone" type="hidden" value="9898989898" />
<noscript>
<input type="submit" value="Click here to continue" />
</noscript>
</form>
<script type="text/javascript">
$(document).ready(function() {
document.myRedirectForm.submit();
});
</script>
Side note:
If you already have the information in your server why are you sending a redirect instead of doing the given action?
Maybe you want to implement a POST/REDIRECT/GET pattern?
I do not think this is possible. Why do not you use RequestDispatcher. This will work for you. Just set the parameters in request
request.setAttribute("message", "Hello test");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
OR - The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue.
OR - another option, set the parameters in your session in servlet, if you have session. Then get it from session after you redirect to the required page.
I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:
var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";
function login() {
var login = baseUrl + loginCall + "?";
var loginFormElements = document.forms.loginForm.elements;
login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);
simpleHttpRequest(login, function(responseText){
var status = evalJSON(responseText);
if (status.errorCode == 200) {
var res = status.results;
var sessionId = res[0].sessionId;
setCookie(SESSION_ID,sessionId);
window.location="http://localhost:8080/"+baseUrl+"/main.html";
} else {
showError(status.errorCode, "Username or password was incorrect.")
}
}, function(status, statusText){console.log('z');
showError(status, statusText);
});
}
As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass
This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?
Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?
You need to have another look at the JSP MVC
The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.
So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>
Have a look at the tutorials here http://www.jsptut.com/
And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked.
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx
Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong
http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg
All the best
If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects
I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.
Here is java servlet class that will handle a posted form.
public class doLogin extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String username= request.getParameter("username"); // get username/pasword from form
String password = request.getParameter("password");
// This is your imaginary method for checking user authentication from database
if(checkUserAuthentication(username,password)){
/*
user is authenticated.Now fetch data for user to be shown on homepage
User is another class that holds user info. Initialize it with data received from database
*/
user userData = new User;
user.setName(...);
user.setAge(...);
user.setInfo(...);
// etc
}
RequestDispatcher view = req.getRequestDispatcher("login.jsp");
req.setAttribute("userdata", userData); // set user object in current request scope
view.forward(req, resp);//forward to login.jsp
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
}
but you need a form with some action to invoke above ServletClass
<form action="/checkLogin" method="POST">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="login" value="Login">
</form>
To tell your Servlet container to invoke doLogin class on form login button click
you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java
In web.xml' following xml snippet make apllication server aware ofdoLogin` class
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>
But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/checkLogin</url-pattern>
</servlet-mapping>
Now any post request to url /checkLogin will invole doPost method on doLogin class
After successful login request will be trasfered to 'login.jsp' page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
You can use java code in sciptlet <% %> syntax to access userData object
<%
User data = (User)request.getAttribute('userData');
%>
Better and tidy approach is to use expression language
${ pageContext.request.userData.name }
Above expression calls getName() method on object of User class using java beans naming conventions
Here, you can learn more about expression language
May be some time later I can improve this and provide you more insight.Hope that helps :)
This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work