Problems with bootstrap form and POST Method - java

i was making a simple page with a formulary using bootstrap and Eclipse (With JBoss).
Html code(Just < body > part):
<div class="jumbotron">
<div class="container">
<form method="POST" class="form-inline" action="validarIngresoAdmin.htm">
<h4>Ingrese sus datos:</h4>
<input type="text" class="form-control input-sm" placeholder="Email" name="txtEmail">
<input type="password" class="form-control input-sm" placeholder="Password" name="txtPsw">
<button type="submit" class="btn btn-danger">Iniciar sesi&#243n</button>
</form>
</div>
but when i try to get the attributes txtEmail and txtPsw they return null.
Eclipse code:
private void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter pw = response.getWriter();
String email = (String)request.getAttribute("txtEmail");
String pass = (String)request.getAttribute("txtPsw");
}
¿Why 'email' and 'pass' attributes return null?
P.S: Sorry about my english.
Thanks.

To retrieve http variables, you should be using getParameter rather than getAttribute.

Related

Update operation is not performing -Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

I'm trying to develop an application in spring boot + thymeleaf, and I'm able to retrieve the logged in user details in the profile tab from the MySQL database, but when I try to change one or two field details (update) and hit the update button it is showing me an error message - Fri Sep 04 20:39:47 IST 2020
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported
see my controller code (I'm using #RestController annotated on top of the class)-
#RequestMapping(value = "/profile", method = RequestMethod.PUT)
public ModelAndView updateProfile(#ModelAttribute Customer customer, HttpSession session) {
ModelAndView model = new ModelAndView();
Customer exist = cRepo.findByCustEmail(customer.getCustEmail());
if(exist != null) {
if(exist.getCustEmail().equals(session.getAttribute("emailsession"))) {
cRepo.save(customer);
model.addObject("msg", "User Details has been successfully updated!!");
model.setViewName("profile");
}
}else {
model.addObject("exist", "Please enter correct email address!");
String email = (String) session.getAttribute("emailsession");
Customer cust = cRepo.findByCustEmail(email);
model.addObject("customer", cust);
model.setViewName("profile");
}
return model;
}
Thymleaf code (html) -
<div align="center" class="alert alert-success" th:if="${msg}" th:utext="${msg}"></div>
<div align="center" class="alert alert-danger" th:if="${exist}" th:utext="${exist}"></div>
<!-- Modal HTML -->
<div id="myModal">
<div class="modal-dialog modal-login">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Profile Details</h4>
</div>
<div class="modal-body">
<form name="myForm" th:action="#{/profile}" th:object="${customer}" method="post">
<div class="form-group">
<i class="fa fa-id-card"></i>
<input name="id" type="text" class="form-control" placeholder="Enter Id" th:field="${customer.custId}" disabled="true" required="required" />
</div>
<div class="form-group">
<i class="fa fa-user"></i>
<input name="name" type="text" class="form-control" placeholder="Enter Name" th:field="${customer.custName}" required="required" />
</div>
<div class="form-group">
<i class="fa fa-envelope"></i>
<input name="email" type="email" class="form-control" placeholder="Enter Email" th:field="${customer.custEmail}" required="required" />
</div>
<div class="form-group">
<i class="fa fa-lock"></i>
<input name="password" type="text" class="form-control" placeholder="Enter Password" th:field="${customer.custPassword}" required="required" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-block btn-lg" value="Update" />
</div>
</form>
</div>
</div>
</div>
</div>
I want when user login and visit he/she should be able to check his/her profile(which I'm able to do working code) and when the user wants to update few fields(1-2 based on choice) and hit update he/she should be able to update the details (not create new user or record) because when I use #Controller on top of class then this code work and create new user instead update.
Your controller is annotated with #RequestMapping(value = "/profile", method = RequestMethod.PUT) which makes it a PUT endpoint. However, your request is clearly a POST. If we look at your html form it contains method="post". HTML forms only support GET and POST as valid methods so you need to update your endpoint to be a POST endpoint.
tldr;
RequestMapping(value = "/profile", method = RequestMethod.PUT)
to
RequestMapping(value = "/profile", method = RequestMethod.POST)
You request mapping in is POST but Controller has set to accept request as PUT.
<form name="myForm" th:action="#{/profile}" th:object="${customer}" **method="post"**>
#RequestMapping(value = "/profile", method = **RequestMethod.PUT**)
Just keep these in similar way both should be same.
Please check what I find and resolve this.
#RequestMapping(value = "/profile" ,method = RequestMethod.POST)
public ModelAndView updateProfile(#ModelAttribute Customer customer, HttpSession session) {
ModelAndView model = new ModelAndView();
Customer exist = cRepo.findByCustEmail(customer.getCustEmail());
if(exist != null) {
if(exist.getCustEmail().equals(session.getAttribute("emailsession"))) {
**exist.setCustId(exist.getCustId());
exist.setCustName(customer.getCustName());
exist.setCustEmail(customer.getCustEmail());
exist.setCustPassword(customer.getCustPassword());**
cRepo.save(exist);
model.addObject("msg", "User Details has been successfully updated!!");
model.addObject("customer", exist);
model.setViewName("profile");
}
}else {
model.addObject("exist", "Please enter correct email address!");
String email = (String) session.getAttribute("emailsession");
Customer cust = cRepo.findByCustEmail(email);
model.addObject("customer", cust);
model.setViewName("profile");
}
return model;
}

HTTP method POST is not supported by this URL Java servlet

Can someone please tell me why i am getting error:HTTP Status 405 – Method Not Allowed ?
I am trying accomplish that after method doPost() ,user will be redirected to "/logout" controller ,where is invalidate session.
It's funny because method is called ,do everything what should do(update user in database), but after send to user error 405.Another where i use doPost() (for example: LoginController) working well ,but when i try compere and find bug ,i dont see any :<
<div class="container">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="account">
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" class="form-control" id="email"
value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="repeatPassword">Repeat Password</label>
<input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
id="repeatPassword" placeholder="Password">
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
</form>
</div>
</div>
#WebServlet("/account")
public class AccountController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
String repeatPassword = req.getParameter("repeatPassword");
if (email == null || password == null || repeatPassword == null) {
doGet(req, resp);
return;
}
if (password.equals(repeatPassword)) {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("loggedUser");
user.setEmail(email);
String sha1hexPassword = DigestUtils.sha1Hex(password);
user.setPassword(sha1hexPassword);
UserService service = new UserService();
try {
service.update(user);
} catch (UpdateObjectException e) {
e.printStackTrace();
}
req.getRequestDispatcher("/logout").forward(req, resp);
} else {
req.setAttribute("errorMessage", "Passwords not the same");
req.setAttribute("fragment", "account");
req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
}
}
}
Thanks for any hint.
Your doGet() method call is inside the server doPost() code. You should redirect the response, doGet is for recieving a GET request and any query string.
Problem solved. Here:
req.getRequestDispatcher("/logout").forward(req, resp);
i should do
resp.sendRedirect(req.getContextPath()+"/logout");
because in "/logout" i have only doGet() method ,and if i use "getRequestDispatcher()" its try to find doPost() method.

getParameter returns null from Method get

I'm tryring to get an id from url but getParameter return null
this is how I'm sending the id in the url (tool.jsp):
Execute
this the doGet method where I want the id value
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
ToolDAO dao=new ToolDAO();
String id= req.getParameter("id");
Tool t=dao.getToolById(Integer.parseInt(id));
String first = req.getParameter("first");
byte[] bytes = first.getBytes(StandardCharsets.ISO_8859_1);
first= new String(bytes, StandardCharsets.UTF_8);
if(first!=null)
{
String [] input=first.split(" ");
System.out.println("input"+input[0]);
EXEJAVA exe=new EXEJAVA();
FileRead f=new FileRead();
f.writeinputfile(input);
ArrayList l=exe.executetool(t.getTool_path_exe());
req.setAttribute("l",l);
req.setAttribute("first", first);
req.getRequestDispatcher("executetool.jsp").forward(req, res);
}
and this is the form (executetool.jsp)
<form accept-charset="UTF-8" name="form" action="executetool" method="get">
<div class="centre">
<div class="row">
<div class="inline-div">
<label for="ta1">Text in Latin script</label>
<textarea cols="60" rows="15" id="first" name="first" class="inline-
txtarea">${first}</textarea>
</div>
<div class="inline-div">
<input type="button" value="Clear" onclick="javascript:eraseText();">
</div>
<div class="inline-div">
<label for="ta2" >Text in Arabic script</label>
<textarea cols="60" rows="15" id="second" name="second" class="inline-
txtarea"><c:forEach items="${l}" var="s">${s} </c:forEach>
</textarea>
</div>
</div>
</div>
</form>
Since it's method get the url keeps changing everytime the page is refreshed and so the "id=something" part gets replaced by the value of the two text areas that I have in the form what sould I do to always keep that part in the url?
Place a hidden field instead
<input type='hidden' name='id' value='${l.tool_id}'>
Then use input type submit for the button, not a generic <a> tag as that won't submit the form unless you have a javascript code somewhere that will submit the form for you.
You can also place the id in the action attribute of the form.
<form accept-charset="UTF-8" name="form" action="executetool?id=${l.tool_id}" method="get">

Liferay: How to make enctype="multipart/form-data" and method="post" work together?

I'm developing a web app using liferay portal server 6.2
JSP code -
<form id="mainForm" action="<portlet:actionURL/>" method="post" enctype="multipart/form-data" >
<input type="hidden" id="varImport" name="varImport"/>
<div class="tab-pane" id="uploadFile">
<p>Please upload a file</p>
<div id="inputFileDiv">
<input type="file" name="uploadFile" />
</div>
</div>
<input type="submit" class="btn btn-info" onClick="import()" value="IMPORT" />
</form>
<script>
function import() {
console.log("importing");
document.getElementById("varImport").value = "IMPORTFILE";
document.getElementById("mainForm").submit();
}
</script>
Servlet code -
#Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
System.out.println("myPortlet.processAction() >> " + request.getParameter("varImport"));
//... rest of the code.
}
If I remove enctype from jsp form, I get the value of varImport in my servlet.
But if i keep it, it returns null.
What am i missing?
import com.liferay.portal.util.PortalUtil;
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("myPortlet.processAction() >> " + uploadRequest.getParameter("varImport"));

How to retrieve form elements at controller in java

I am trying to submit a form to controller in using java spring, in following code i am retrieving file element by following way successfully but not getting how to retrieve other elements(shortname and full name)value.
please help me out.
<body>
<div style="text-align: center; margin-top: 60px;">
<form action="upload" enctype="multipart/form-data">
<input type="hidden" id="shortName" name="michael">
<input type="hidden" id="fullName" name="michael jackson">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
Controller side code :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response,
#RequestPart("dataFile") MultipartFile file
){
System.out.println(file.getSize());
}
first change the input elements and create the name attribute for both shortName and fullName like so :
<input type="hidden" id="shortNameId" name="shortName" value="michael">
<input type="hidden" id="fullNameId" name="fullName" value="michael jackson">
however you can remove the default value attribute and just enter the value yourself when the page render so value="michael" & value="michael jackson" are optional !
Then you can retrieve those input elements like this :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response, #RequestParam("shortName")String shortName, #RequestParam("fullName")String fullName
#RequestPart("dataFile") MultipartFile file
){ .... }
Good Luck !
In your controller, try something like this,
#RequestMapping(value = "/your/url/{formParamenter}", method = RequestMethod.GET)
public String yourfunction(#PathVariable("formParameter") Type formParameter{}
The Type is the type of data, (String/int/float..etc).
In your case just change RequestPart to #PathVariable

Categories

Resources