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.
Related
<html>
<head>
<title>Report Preview</title>
</head>
<body>
<div class="container">
<h2>Patient Data</h2>
<form action = "reportUpdate" method = "post" >
<input type="text" name="fvalue" value="testingData1"/>
<input type="text" name="svalue" value="testingData2"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type = "text/javascript" src = "main.js"></script>
</body>
</html>
I have a SpringBootProject and I'm using the above Freemarker code template file(*.ftl). I tried to display some input field with the values(binded), after editing I want to extract the data from HTML input tags(fvalue,svalue) to controller without using any model. How to get the values?
My controller code:
#PostMapping({ "/reportUpdate"})
public String reportToUpdate( ) {
String firstName = ""; // I should get fvalue here
String secondName = ""; // I should get svalue here
//Some other logics which will use above value.
return "Data saved!";
}
By using HttpServletRequest request, HttpServletResponse response we can get the data from HTML form.
Using the below code.
public void getDataFromForm(HttpServletRequest request, HttpServletResponse response) throws ServletException{
// Get the values from the request using 'getParameter'
String name = request.getParameter("name");
}
For more info, you can see this.
I am currently working with Jersey to support RESTful web service with jsp.
I have a form submitted from client side from jsp that calls upon REST api.
index.jsp
<form action = "../project/rest/user/transfer" method = "POST">
<div class="row">
<div class="col">
<h3>Sender Address</h3>
<input type = "text" name = "sender_address" id="sender_address">
</div>
<div class="col">
<h3>Receiver Address</h3>
<input type = "text" name = "receiver_address" id="receiver_address">
</div>
<div class="col">
<h3>Amount</h3>
<input type = "number" name = "amount" id="transferAmount" />
</div>
</div>
<br>
<input id="submitButton" type = "submit" value = "Transfer"/>
</form>
java class that uses jersey
#POST
#Path("/transfer")
#Produces(MediaType.APPLICATION_JSON)
public ResponseMessage transfer(#FormParam("sender_address") String from, #FormParam("receiver_address") String to, #FormParam("amount") int value){
ResponseMessage msg = new ResponseMessage();
msg.setResponseCode("200");
msg.setResponseMessage("some message");
Transaction trans = new Transaction();
msg.setData(trans);
return msg;
}
When the form is submitted, this calls upon the above java method and display a new page that displays the java method info in JSON format.
However, I would like the page to stay on the same page but be able to retrieve/use the Transaction data returned from that java method(JSON object).
Is there a way to perform something of similar?
Thanks
I want create 2 JSP pages. I have Controller:
#Controller
#RequestMapping(value = "/api/web/users")
public class ServletWebController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "message");
return "hello";
}
}
It open first JSP page with form:
<html>
<body>
<form action="main.jsp" method="post">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
When I input data to the form and press submit button, I want to open second JSP page and print data from form:
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
But the second JSP page not opened. So I input http://localhost:4000/api/web/users And i have form. Then I input data and press "Submit". Then I have this link http://localhost:4000/api/web/main.jsp and error:
HTTP Status 404 - /api/web/main.jsp
type Status report
message /api/web/main.jsp
description The requested resource is not available.
Apache Tomcat/8.0.26
I am new in Spring and JSP, how can I open JSP from another JSP?
in your Controller you can do something like this:
#RequestMapping(value="/successpage", method =RequestMethod.POST)
public void successpage(ModelMap model, Users user)
{
model.addAttribute("name", user.getFirstName());
}
#RequestMapping(value="/signupform", method=RequestMethod.GET)
public ModelAndView signupForm()
{
return new ModelAndView("user", "command", new Users()); //Object that contains your getter and setters
}
On your form you can modify your open Form tag to look like this:
<form action="/successpage" method="POST">
In your WEB-INF/jsp folder you will need the 2 pages: signupform.jsp and successpage.jsp
After all is said and done, you can pass the ${name} variable on your successpage.jsp to see the value from the form.
This question is related to this. But since I haven't solved that question yet, I want to restate my problem a bit. I'm using Java Jersey REST API as my backend web service. The client side is a simple web form HTML page. Basically what I want is: If the user submits a web form and there are some errors caused by database unique constraint violation, I want the user to see an error message showing along with the id field in the form such as "ID already exists!". The web form is a simple form.html:
<form action="/myapp/rest/customer/created" method="POST">
<table border="1">
<tr>
<td>Customer name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Customer ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>Customer DOB:</td>
<td><input type="text" name="dob"></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit">
</form>
If there is an error occurred, how to pass the error information from Jersey API to the client-side? My server-side POST call associated with this form submission is as follows:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("created")
public Response createCustomer(#FormParam("id") int id,
#FormParam("name") String name, #FormParam("dob") Date dob)
throws ServletException, IOException {
URI uri = URI.create(uriInfo.getPath());
Response r;
r = Response.created(uri).build();
try {
dbController.create(id, name, dob); //This may throw exception.
} catch (DataAccessException ex) {
//To do: How to pass the error message to the client-side UI via e.g., Ajax?
}
return r;
}
First of all add this somewhere in your code. It will display the error message:
<span id="errorDiv" name="errorDiv" class="errorDiv" ></span>
Next, modify your form declaration as:
<form action="/myapp/rest/customer/created" method="POST" onsubmit="return checkForm()">
Before submitting the form it will call checkForm() function. if the function returns true then it will post the form. if not then it will prevent form from submission and display error message.
Assuming that you are submitting the form contents by using jQuery/AJAX calls. You can return a String(default value = 'success') from the server. In case there is an error change the specific string and return it and check the value client-side.
responseTxt is the value returned.
function checkForm(){
//get values from form
var name= $("#name").val();
var id= $("#id").val();
var dob= $("#dob").val();
$.post('DESTINATION',{name:name,id:id,dob:dob},function(responseTxt) {
//MAKE YOUR CHECK HERE. JUST AN EXAMPLE
if (responseTxt.substring(0,4)=='succ'){
//redirect to destination
return true;
}else{
//display error in errorDiv span
$('#errorDiv').html('<font color=red>Wrong username or password.</font>');
//prevents form to be submitted
return false;
}
});
}
Hope it helps
I have 2 jsp-page. In first jsp-page I use combobox who choosing subject, several radio button for action. On servlet this page I get request.getParameter("subjectID").
Better If I show servlets and jsp
<form action="/TutorWebApp/controller" method="POST" name="editTestForm">
<p>
Choose subject
<select name='subject'>
<c:forEach items="${subjects}" var="subject" >
<option value="${subject.key}">
${subject.value.getName()}
</option>
</c:forEach>
</select>
</p>
<input type="radio" name="command" value="add_test">
Add test <br />
<input type="radio" name="command" value="add_subject">
Add subject <br />
<input type="submit" value="OK"/>
</form>
In this page I choose subject from combobox. And choose "Add test". After I go to servlet where
class AddTestCommand implements Command {
private static final String PARAM_TEST_NAME = "testName";
private static final String PARAM_SUBJECT = "subject";
#Override
public String execute(HttpServletRequest request) throws ServletException, IOException {
String page = " ";
String message = " ";
String testName = request.getParameter(PARAM_TEST_NAME);
if (testName != null && (!"".equals(testName))) {
HttpSession session = request.getSession(true);
Integer userID = (Integer) session.getAttribute("userID");
Integer subjectId =
Integer.valueOf(request.getParameter(PARAM_SUBJECT));
if(AddTestLogic.addTest(userID, subjectId, testName)){
message = "Success";
} else{
message = "This test already exist";
}
request.setAttribute("result", message);
}
page = ResourceBuilder.getPropertyManager(PropertyEnum.JSP_PAGE).
getProperty("path.page.addtest");
return page;
}
}
There I can get value of subject as request.getParameter("subject"); near with testName before if(){} And next step - go to next jsp
<form action="/TutorWebApp/controller" method="POST" name="addTestForm">
<input type="hidden" name="command" value="add_test" />
Name of new test:
<input type="text" name="testName" value=""/>
<input type="submit" value="Add test"/>
</form>
An after input data in jsp I go to the same servlet again. But I lose value request.getParameter("subject").
I try to use HttpSession but on first page I send Map. And get with request just choosen subjectID from Map.
I don't know how resolve this problem.
Thanks
You can retain request parameters for the next request with a hidden field. Request parameters are available by the ${param} map in EL. So, this should do:
<input type="hidden" name="subject" value="${fn:escapeXml(param.subject)}" />
Note that I'm using JSTL fn:escapeXml() to escape HTML entities; this will prevent possible XSS attacks.