How to send a post request to the Spring controller using ajax - html

I want to send a post request to the spring controller using ajax. But it doesn't work. I would be grateful if anyone could tell me, what I have done worngly.
$("#myprofile").on('submit',function(e){
console.log("in changes ave"+ $("#firstname").val());
console.log("in changes ave"+ $("#lastname").val());
console.log("in changes ave"+ $("#current_password").val());
console.log("in changes ave"+ $("#new_password").val());
var myJSON = JSON.stringify({
"firstname" : $("#firstname").val(),
"lastname" : $("#lastname").val(),
"current_password" : $("#current_password").val() ,
"new_password" : $("#new_password").val()
});
$.ajax({
type : "POST",
url : "/edit_profile",
dataType:"json",
contentType: "application/json",
data : myJSON,
success : function(mydataa) {
console.log("Successful")
},
error: function(dataa){
alert(dataa.responseText)
}
});
})
Here is my controller:
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = "application/json")
public ModelAndView editProfile(#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname, #RequestParam("new_password") String new_password,
#RequestParam("current_password") String current_password) {
ModelAndView modelAndView = new ModelAndView();
//some logic here
user = profileRepository.changeUserInformation(user, firstname, lastname, new_password, current_password);
}
modelAndView.setViewName("profile");
return modelAndView;
}
And here is my html page:
<form class="col" id="myprofile">
<input type="text" class="form-control border-0" name="firstname" id="firstname" th:value="${currentUser.firstname}">
<input type="text" class="form-control border-0" name="lastname" id="lastname"
th:value="${currentUser.lastname}">
<input type="password" class="form-control border-0" placeholder="current password" name="current_password" id="current_password">
<input type="password" class="form-control border-0" placeholder="new password" name="new_password" id="new_password">
<input type="password" class="form-control border-0" name="confirm_password"
id="confirm_password" placeholder="confirm new password">
<button id = "changesave-btn" type="submit" class="save button-2">SAVE CHANGES</button>
</form>
I get Error 400 Bad request as the message returned from the alert line and I see this output in my console:
Required String parameter 'firstname' is not present
Thanks in advance,

Since you send a JSON payload, there is no request parameter.
Create a POJO to store the Ajax POST data.
public class MyProfile {
private String firstname;
private String lastname;
private String new_password;
private String current_password;
public MyProfile() {
}
// getter/setter ..
}
Accept the Ajax POST data with #RequestBody
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView editProfile(#RequestBody MyProfile myProfile) {
// ...
}

Related

how to send json objetct to servlet?

jsp code:
<script>
//login
function submitForm(thisObj, thisEvent) {
var userName = $('#userName').val();
var pwd = $('#pwd').val();
var myData = {
"mydata": {"userName": userName, "pwd" : pwd}
};
$.ajax({
type: "POST",
url: "/login",
data: {
jsonData: JSON.stringify(myData)
},
dataType: "json"
});
return false;
}
</script>
<tr><td><input type="text" id="userName" name="userName" size="30" maxlength="30"></td></tr>
<tr><td><input type="password" id="pwd" name="pwd" size="30" maxlength="30"></td></tr>
<tr><td><button class="button" type="submit" value="Login" name="Submit" accesskey="s" onClick="return submitForm(this,event)">LOG IN</button></td></tr>
servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
PrintWriter out = res.getWriter();
StringBuffer sbuffer = new StringBuffer();
String inLine = null;
String sUsername = "";
try{
BufferedReader reader = req.getReader();
while ((inLine = reader.readLine()) != null)
sbuffer.append(inLine);
if (sbuffer.length() != 0){
JSONObject jsObj = new JSONObject(sbuffer.toString());
sUsername = jsObj.optString("userName");
sPwd = jsObj.optString("pwd");
}
}catch(Exception e){
out.println(retResponse("E","error"));
return;
}
sUsername = sUsername.trim();
sPwd = sPwd.trim();
}
}
web.xml:
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
I would like to pass my login/pwd to server side for validation by using json and servlet.
I'm newbie on json.I reference to online example and develop above code. But it not works. Do anyone know what my coding wrong? my already put by login.class under WEB-INFO folder.
I got what I'm wrong. Its work after I change the ajax lib. from http://ajax.googl... to https://ajax.googl...

Edit view not being populated with objects data

I am quite new to ASP .Net, and could use some help... I have an ASP .Net Core 1.1 web app. In it, I have an "Edit" view for editing a simple object, which a corresponding controller calls when routed to it. This is the view:
#model InspectionsTestClient.Models.Property
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
#Html.ValidationSummary();
<form asp-action="Edit">
<div class="form-horizontal">
<h4>Property</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="UnitNumber" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UnitNumber" class="form-control" />
<span asp-validation-for="UnitNumber" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="BuildingName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="BuildingName" class="form-control" />
<span asp-validation-for="BuildingName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Street" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Street" class="form-control" />
<span asp-validation-for="Street" class="text-danger"></span>
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is the controller which calls that view:
// GET: Property/Edit/5
public ActionResult Edit(int id)
{
return View();
}
And this is the model:
namespace InspectionsTestClient.Models
{
//[Table("property")]
public class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
[MaxLength(10, ErrorMessage = "Unit number too long")]
[Display(Name = "Unit #")]
public string UnitNumber { get; set; }
[MaxLength(45, ErrorMessage = "BuildingName name too long")]
public string BuildingName { get; set; }
[MaxLength(45, ErrorMessage = "Street too long")]
public string Street { get; set; }
}
}
So when I navigate to that page, the controller fires up, and returns the Edit view. I have confirmed the parameter "id" is populated. When the Edit view loads in the browser, however, all the input textboxes are empty. I would expect them to be pre-populated with the values for the object in question. What am I missing?
The issue you are experiencing is happening because you are not returning that object to the view.. actually in your case you're not even going out to the db to get the object.
You need to edit you Edit action to something like this:
// GET: Property/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var object = db.TableName.Find(id);
// db = connectionstring
// TableName = database table that holds the object that you want to return
if (object == null)
{
return HttpNotFound();
}
return View(object);
}
Let me know if this helps
public class PropertyController
{
private readonly ApplicationDbContext _dbContext;
public PropertyController(ApplicationDbContext dbContext){
_dbContext = dbContext;
}
//GET: Property/Edit/5
public async Task<IActionResult> Edit(int id)
{
var property = await _dbContext.Property.FirstOrDefaultAsync(p => p.Id == id);
return View(property);
}
}
If you don't pull the data from the database and send it to the view of course it will always be blank. Edit(int id) there will be 2, both slightly different from the other.
[HttpPost]
[ValidateAntiForgeryToken]
//Post: Property/Edit/5
public async Task<IActionResult> Edit(int id, [Bind("Id", "UnitNumber", "BuildingNumber", "Street")] Property property)
{
if(ModelState.IsValid){
}
else{
}
}
not everyting is present but that is part of your adventure.

Action routing goes to same controller

I'm trying to link to a different controller with a HTTPPost action, however, when I try to it just appends my route values onto the current page's controller. For example, if I'm trying to link from Site/ViewIndex to Page/createPage with a form and a HTTPPOST, then it throws a 404 and says it can't access Site/Page/createPage. Why is it doing this and how can I stop it?
Here is my site/createPage:
public ActionResult createPage(int siteId, string title, string description, bool isBlog = false)
{
if (string.IsNullOrWhiteSpace(title) ||
string.IsNullOrWhiteSpace(description))
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Please fill out all fields" });
}
try
{
Ops.PageOps.createPage(title, description, siteId, isBlog);
return RedirectToAction("ViewIndex", "Site", new { siteId = siteId, message = "Page created!" });
}
catch (Exception e)
{
return RedirectToAction("ViewIndex", new { siteId = siteId, message = "Error occured: " + e.Message });
}
}
Here is my form:
<form method="post" action="Page/createPage">
<input class="form-field form-control" type="text" name="title" placeholder="Page Title" />
<input class="form-field form-control" type="text" name="description" placeholder="Page Description" />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" /><br /><br />
<input class="btn btn-info" type="submit" value="Create" />
</form>
And I doubt it's any relevance but here's my Site controller:
public class SiteController : Controller
{
/// <summary>
/// The create page
/// </summary>
/// <returns></returns>
public ActionResult CreateIndex()
{
return View();
}
[HttpPost]
public ActionResult Create(string title, string description, bool privateSite = false)
{
Ops.SiteOps.createSite(Authenticated.AuthenticatedAs, title, description, privateSite);
return RedirectToAction("Index", "Home");
}
public ActionResult ViewIndex(int siteId, string message = null)
{
ViewBag.message = message;
ViewBag.siteId = siteId;
return View();
}
}
Use the Html.BeginForm helper method to render your form tag. This will render the correct relative path to your HttpPost action in your form's action attribute.
#using(Html.BeginForm("CreatePage","Page"))
{
<input class="form-field form-control" type="text" name="title" placeholder="Title" />
<input class="form-field form-control" type="text" name="description" " />
<input class="form-field form-control" type="hidden" name="siteId" value="#site.Id" />
Blog page? <input class="form-field" type="checkbox" value="true" name="isBlog" />
<input class="btn btn-info" type="submit" value="Create" />
}

JSON simple program showing error

Tyring a simple example of json but it is showing error.
I have included gson-2.2.3.jar in class path.
I am using netbeans 7.1. This program is not deploying.
Apache tomcat log is showing:
Unable to load configuration. - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: Error building results for action sayHi in namespace - action - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:10:73
Caused by: There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'? - result - file:/D:/APP/webApp1/build/web/WEB-INF/classes/struts.xml:11:33
I am trying simple example. Please see what is the proble.
Action Class
public class AjaxActions extends ActionSupport {
private String name;
private String greeting;
public String sayHi() {
greeting = "HI " + name;
return ActionSupport.SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
Struts.xml
<package extends="struts-default,json-default" name="ajax-package" namespace="/ajax">
<action class="example.AjaxActions" method="sayHi" name="sayHi">
<result type="json">
</result>
</action>
</package>
in jsp file
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input name="name">
<input type="submit">
</form>
<script>
$(function(){
$("#introForm").submit(function(){
var formInput=$(this).serialize();
$.getJSON('ajax/sayHi.action', formInput,function(data) {
$('.result').html('' + data.greeting + '');
return false;
});
});
</script>
add struts2-json-plugin.jar according to struts2 version in your project libraries.
if you are using struts2.3.4 then use struts2-json-plugin2.3.4.jar
And change your in your struts.xml
<package extends="struts-default,json-default"
to
<package extends="json-default".
And use the following html code.
<form action="" id="introForm">
<label for="name">Enter Your Name</label>
<input type="text" id="name" name="name">
<input onclick="javascript:getResultData();" type="submit">
<span id="resultHtml"></span>
</form>
<script>
function getResultData(){
var formInput=$("#name").val();
vat inputData={"name":formInput}
$.getJSON('ajax/sayHi.action', inputData,function(data) {
$("#resultHtml").html('' + data.greeting + '');
return false;
});
}
</script>

Losing data (specifically, the apostrophes) from HTML form to Java Servlet

Reference: HTML forms, php and apostrophes
I've been trying to pass data from my HTML form to my servlet for processing. However, I noticed that I'd lose the apostrophes in the text inputs. I'm not sure if this is a client or server side processing error, but looking through the reference above, i think i need to do some processing on the servlet side? Tried looking for a servlet alternative to the above but couldn't find any.
Here's the code snippets:
Html form:
<form method="post" action="CreateThreadServlet">
<b>Title</b><br>
<input type="text" name="title" size="60%" placeholder="Enter your title here"/><br>
<br><b>Tags</b><br>
<input type="text" name="tags" placeholder="Additional Tags: comma separated, e.g. Gamification, Java" size="60%" /><br>
<br><b>Details</b><br>
<textarea name="content" style="width:100%;height:50%"></textarea>
<input type="hidden" name="nick" value=<%=nick%>>
<input type="hidden" name="userid" value=<%=userid%>>
<button type="button" style='float: right;' onClick="closeDimmer()">Cancel</button>
<input type="submit" name="Submit" value="Submit" text-align='center' style='float: right;'>
</form>
This is the servlet code that processes the form:
String userid = req.getParameter("userid");
String nick = req.getParameter("nick");
String title = null; //tried using the URLDecoder, doesn't work
try {
title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateThreadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String tags = req.getParameter("tags");
String[] tagStr = tags.split(",");
String[] addTags = req.getParameterValues("addTags");
PLEASE HELP THE NEWBIE.
As this link explains you could simply config a filter
<filter>
<filter-name>HitCounterFilter </filter-name>
<filter-class>
net.my.filters.HitCounterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
having this:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, wrapper);
}
}
so you force an UTF-8 encoding.