passing more than one data from servlet to jsp through ajax - javascript

Hi i am trying to call servlet from jsp through ajax,and return two data from servlet. But facing some problem with result data.
both pono podt are combined together at output. how to split the same to get the correct data.
$(document).ready(function() {
$('#grn').blur(function() {
$.ajax({
url : 'callserv0',
type: 'POST',
data : {
grnno : $('#grn').val()
},
success : function(data) {
alert("new");
$('#pono').val(data);
$('#podt').val(data);
return false;
}
});
});
});
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
<form>
Receipt number: <input type="text" id="grn" />
PO number: <input type="text" id="pono" />
PO Date : <input type="text" id="podt" />
<input type="button" id="find" value="Find" />
</form>
</body>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class callserv0 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//response.setContentType("text/html");
//PrintWriter out= response.getWriter();
//out.println("i am in callserv0");
String grn = request.getParameter("grnno");
String pono = grn;
String podt = "12/12/12";
response.setContentType("text/plain");
response.getWriter().write(pono);
response.getWriter().write(podt);
}
}
enter image description here

You can put a delimiter such as a comma(,) when you write the values to response.
Then use JavaScript method split()
.
var str = "123,2/21/2017";
var res = str.split(",");
console.log(res[0]);
console.log(res[1]);

Related

Spring boot AJAX POST request and knockout.js debug error from user interface

I have two java models as player and team. I have a controller class. I get an error when I send a post request via ajax from the user interface. I've solved errors like CORS. But there is an error I can't solve; The knockout.js debug error and the post request are not occurring. There is no change in my database. I shared the model classes, the controller class, the html and javascriptfiles.
What do I need to change? Could you help?
Player Model
#Entity
#Table(name = "player")
public class Player{
#Id
#GeneratedValue
#NotNull
#Column
private int id;
#NotNull
#Column
private String playerName;
#NotNull
#Column
private String playerSurname;
#Column
private int playerAge;
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerSurname() {
return playerSurname;
}
public void setPlayerSurname(String playerSurname) {
this.playerSurname = playerSurname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPlayerAge() {
return playerAge;
}
public void setPlayerAge(int playerAge) {
this.playerAge = playerAge;
}
}
Team Model
#Entity
#Table(name = "team")
public class Team {
#Id
#GeneratedValue
#NotNull
#Column
private int id;
#NotNull
#Column
private String teamName;
#Column
private String teamCountry;
public Team(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamCountry() {
return teamCountry;
}
public void setTeamCountry(String teamCountry) {
this.teamCountry = teamCountry;
}
#ManyToOne
private Player player;
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
}
Controller
#CrossOrigin(origins = "http://localhost:8000/")
#RestController
public class TeamController {
#Autowired
PlayerRepository playerRepository;
#Autowired
TeamRepository teamRepository;
#RequestMapping("/")
public void main() {
//create players by manual
Player messi = new Player();
Player ronaldo = new Player();
Player ozil = new Player();
messi.setPlayerName("Lionel");
messi.setPlayerSurname("Messi");
messi.setPlayerAge(31);
ronaldo.setPlayerName("Cristiano");
ronaldo.setPlayerSurname("Ronaldo");
ronaldo.setPlayerAge(32);
ozil.setPlayerName("Mesut");
ozil.setPlayerSurname("Ozil");
ozil.setPlayerAge(29);
this.playerRepository.save(messi);
this.playerRepository.save(ronaldo);
this.playerRepository.save(ozil);
//create teams by manual
Team barcelona = new Team();
Team juventus = new Team();
Team arsenal = new Team();
barcelona.setTeamName("Barcelona");
barcelona.setTeamCountry("Spain");
barcelona.setPlayer(messi);
juventus.setTeamName("Juventus");
juventus.setTeamCountry("Italy");
juventus.setPlayer(ronaldo);
arsenal.setTeamName("Arsenal");
arsenal.setTeamCountry("England");
arsenal.setPlayer(ozil);
this.teamRepository.save(barcelona);
this.teamRepository.save(juventus);
this.teamRepository.save(arsenal);
}
//**PLAYER**
#GetMapping(value="/getAllPLayers")
public List<Player> getAllPlayers(){
return playerRepository.findAll();
}
#PostMapping(value="getPlayerByName")
public List<Player> getPlayerByName(#RequestParam("playerName") String playerName){
return playerRepository.findByPlayerName(playerName);
}
#PostMapping(value="getPlayerBySurname")
public List<Player> getPlayerBySurname(#RequestParam("playerSurname") String playerSurname){
return playerRepository.findByPlayerSurname(playerSurname);
}
#PostMapping(value="getPlayerByAge")
public List<Player> getPlayerByAge(#RequestParam("playerAge") int playerAge){
return playerRepository.findByPlayerAge(playerAge);
}
#PostMapping(value="createNewPlayer")
public Player createNewPlayer(#Valid #RequestBody Player player) {
return playerRepository.save(player);
}
//**TEAM**
#GetMapping(value="/getAllTeams")
public List<Team> getAllTeams(){
return teamRepository.findAll();
}
#PostMapping(value = "/getTeamsByName")
public List<Team> getTeamByName(#RequestParam("teamName") String teamName){
return teamRepository.findByTeamName(teamName);
}
#PostMapping(value = "/getTeamsByCountry")
public List<Team> getTeamByCountry(#RequestParam("teamCountry") String teamCountry){
return teamRepository.findByTeamCountry(teamCountry);
}
#PostMapping(value="/createNewTeam")
public Team createNewTeam(#Valid #RequestBody Player player,#RequestBody Team team) {
playerRepository.save(player);
team.setPlayer(player);
return teamRepository.save(team);
}
}
Config
#Configuration
#EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
System.out.println("WebConfig; "+request.getRequestURI());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Expose-Headers", "USERID");
response.addHeader("Access-Control-Expose-Headers", "ROLE");
response.addHeader("Access-Control-Expose-Headers", "responseType");
response.addHeader("Access-Control-Expose-Headers", "observe");
System.out.println("Request Method: "+request.getMethod());
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
"USERID"+"ROLE"+
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
Player Repo
public interface PlayerRepository extends JpaRepository<Player, Integer>{
List<Player> findByPlayerName(String playerName);
List<Player> findByPlayerSurname(String playerSurname);
List<Player> findByPlayerAge(int playerAge);
}
Team Repo
public interface TeamRepository extends JpaRepository<Team, Integer>{
List<Team> findByTeamName(String teamName);
List<Team> findByTeamCountry(String teamCountry);
}
POST HTML Page
<!DOCTYPE HTML>
<html>
<head>
<title>Team Management</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="js/restGetPlayer.js"></script>
<script src="js/restGetTeam.js"></script>
<script src="js/postTeam.js"></script>
</head>
<body>
<div class="container">
<h3 style="color: darkolivegreen" align="center">Create a new team</h3>
<div class"main-block>
<form id="teamForm" class="form-inline" style="margin:20px 20px 20px 20px">
<div class="form-group">
<label for="playerName" style="margin-left:20px; margin-right:5px">Player Name:</label>
<input type="text" class="form-control" id="playerName" placeholder="Enter player name"/>
</div>
<br>
<div class="form-group">
<label for="playerSurname" style="margin-left:20px; margin-right:5px">Player Surname:</label>
<input type="text" class="form-control" id="playerSurname" placeholder="Enter player surname"/>
</div>
<div class="form-group">
<label for="playerAge" style="margin-left:20px; margin-right:5px">Player Age:</label>
<input type="text" class="form-control" id="playerAge" placeholder="Enter player age"/>
</div>
<br style="clear: both;">
<div class="form-group">
<label for="teamName" style="margin-right:5px">Team Name:</label>
<input type="text" class="form-control" id="teamName" placeholder="Enter team name"/>
</div>
<br>
<div class="form-group">
<label for="teamCountry" style="margin-left:20px; margin-right:5px">Team Country:</label>
<input type="text" class="form-control" id="teamCountry" placeholder="Enter team country"/>
</div>
<br>
<hr>
<button type="submit" class="btn btn-default" style="margin-left:20px; margin-right:5px" >Submit Team</button>
</form>
</div>
<div class="col-sm-7" style="margin:20px 0px 20px 0px">
<button id="getAllTeams" class="btn btn-primary">Get Team Information</button>
<div id="getResultDiv3" style="padding:20px 10px 20px 50px">
<ul class="list-group">
</ul>
</div>
</div>
</div>
<style>
.container {
max-width: 400px;
width: 100%;
margin: 0 auto;
position: relative;
}
#contact {
background: #F9F9F9;
padding: 25px;
margin: 150px 0;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
</style>
<script type="text/javascript" src="js/libs/require/require.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
AJAX POST
$( document ).ready(function() {
$("#teamForm").submit(function(event) {
event.preventDefault();
ajaxPost();
});
function ajaxPost(){
var formData = {
playerName : $("#playerName").val(),
playerSurname : $("#playerSurname").val(),
playerAge : $("#playerAge").val(),
teamName : $("#teamName").val(),
teamCountry : $("#teamCountry").val()
}
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080" + "/createNewTeam",
data : JSON.stringify(formData),
dataType : 'json',
success: function(result){
alert("Teams loaded!");
console.log(result);
$('#getResultDiv3 ul').empty();
var tableTitle = "<h2><strong>Team List</strong></h2>";
var teamList = "<table border='1'>";
teamList += "<tr><td><strong>Team Name</strong></td><td><strong>Team Country</strong></td><td><strong>Player Name</strong></td><td><strong>Player Surname</strong></td><td><strong>Player Age</strong></td></tr>";
$.each(result, function(i, teams){
teamList +="<tr>";
teamList +="<td>"+teams.teamName +"</td>";
teamList +="<td>"+teams.teamCountry+"</td>";
teamList +="<td>"+teams.player.playerName+"</td>";
teamList +="<td>"+teams.player.playerSurname+"</td>";
teamList +="<td>"+teams.player.playerAge+"</td>";
teamList +="</tr>";
});
teamList +="</table>";
$('#getResultDiv3').append(tableTitle, teamList)
console.log("Success: ", result);
},
error : function(e) {
$("#getResultDiv3").html("<strong>Error</strong>");
console.log("ERROR: ", e);
}
});
resetData();
}
function resetData(){
$("#playerName").val("");
$("#playerSurname").val("");
$("#playerAge").val("");
$("#teamName").val("");
$("#teamCountry").val("");
}
})
MainController.js
/**
* #license
* Copyright (c) 2014, 2019, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
/*
* Your application specific code will go here
*/
define(['ojs/ojresponsiveutils', 'ojs/ojresponsiveknockoututils', 'knockout', 'ojs/ojknockout'],
function(ResponsiveUtils, ResponsiveKnockoutUtils, ko) {
function ControllerViewModel() {
var self = this;
// Media queries for repsonsive layouts
var smQuery = ResponsiveUtils.getFrameworkQuery(ResponsiveUtils.FRAMEWORK_QUERY_KEY.SM_ONLY);
self.smScreen = ResponsiveKnockoutUtils.createMediaQueryObservable(smQuery);
// Header
// Application Name used in Branding Area
self.appName = ko.observable("Oracle JET + REST API");
// User Info used in Global Navigation area
self.userLogin = ko.observable("admin#oracle.com");
// Footer
function footerLink(name, id, linkTarget) {
this.name = name;
this.linkId = id;
this.linkTarget = linkTarget;
}
self.footerLinks = ko.observableArray([
new footerLink('About Oracle', 'aboutOracle', 'http://www.oracle.com/us/corporate/index.html#menu-about'),
new footerLink('Contact Us', 'contactUs', 'http://www.oracle.com/us/corporate/contact/index.html'),
new footerLink('Legal Notices', 'legalNotices', 'http://www.oracle.com/us/legal/index.html'),
new footerLink('Terms Of Use', 'termsOfUse', 'http://www.oracle.com/us/legal/terms/index.html'),
new footerLink('Your Privacy Rights', 'yourPrivacyRights', 'http://www.oracle.com/us/legal/privacy/index.html')
]);
}
return new ControllerViewModel();
}
);
Picture 1:
Adding Player
Picture 2:
ERROR log After add player
Picture 3:
MySQL player table did not any change
Answering your question, it is not doing anything because you are not sending the parameter Player (that must be valid) due you are using a form this is not the way you should do it. (request params are send via url and your form should do it via #RequestBody)
Check this post for information. Can I use #Requestparam annotation for a Post request?
I would do something like this:
On my controller due I can have only one #RequestBody but my form sends an object containing data for multiple types of an object I would do a Dto
Something like this:
#PostMapping(value="/createNewTeam")
public Team createNewTeam(#Valid #RequestBody PayloadDto payloadDto) {
final Player player = new Player();
player.setPlayerName(payloadDto.playerName);
// fill player information
final Team team = new Team();
// fill team information...
playerRepository.save(player);
return teamRepository.save(team);
}
Your PayloadDto object must contain all attributes you are sending..
public class PayloadDto{
#JsonProperty("playerName")
public String playerName;
#JsonProperty("playerSurname")
public String playerSurname;
// .. more player and team properties
}
Be sure that the jsonProperty("propertyName) holds the same name you are using when sending the information

How to check login with Ajax?

I am a student who has just studied Ajax.
I have been constantly worried, but I have not been able to solve the problem.
So, I want to get some advice from you.
First, I will show the loginPage.jsp code and the MemberController.java code and the MemberService.java code.
It is loginPage.jsp code.
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/swiper.min.css">
<link rel="stylesheet" href="css/loginPage.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/swiper.jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="loginPage_main">
<div class="pageName">
<img class="pageName_image" src="images/greeting_title.jpg">
<div class="pageName_explanation">
<p>로그인</p>
</div>
</div>
<div class="location">
</div>
<div class="loginForm_area">
<div class="hidden_area">
<div class="img_lock_area">
<img src="images/lock.png" class="img_lock">
</div>
<form action="loginOK.do" id="login_frm" name="frm" method="post" onsubmit="return checkValue()">
<div class="input_zone">
<div class="input_id">
<span> ID</span><input type="text" placeholder="아이디를 입력하세요" style="width:280px;margin-left: 10px;" name="id">
</div>
<div class="input_pw">
<span>PW</span><input type="password" placeholder="비밀번호를 입력하세요" style="width:280px;margin-left: 10px;" name="pw">
</div>
</div>
</form>
<div class="loginBtn" onclick="document.getElementById('login_frm').onsubmit();">
<div style="margin-top: 22px;">
<span class="loginOK">Login</span>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function checkValue()
{
var form = document.frm;
if(!form.id.value || !form.pw.value)
{
alert('아이디 혹은 비밀번호를 입력하세요.');
return false;
}
$.ajax
({
type: 'POST',
url: 'loginOK.do',
success: function()
{
alert('success');
},
error: function()
{
alert('error');
}
})
}
</script>
</body>
</html>
It is MemberController.java code.
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.MemberService;
#Controller
public class MemberController
{
#Autowired
public MemberService mService;
// 로그인
// 전송된 ID,PW값과 DB에 있는 ID,PW값 비교
// 맞으면 alert 창으로 " 로그인 성공 " 메세지 표출 + mainPage 이동
// 틀리다면 alert 창으로 " 로그인 실패 " 메세지 표출 + loginPage로 리다이렉트
#RequestMapping("loginOK.do")
public String login(String id, String pw,HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException
{
HashMap<String, Object> loginIdentify = mService.login(id,pw);
System.out.println("ID is : " + id + " / " + "PW is : " + pw);
if(loginIdentify != null)
{
System.out.println("loginIdentify is true : " + loginIdentify);
session.setAttribute("id", id);
session.setAttribute("pw", pw);
/*
- 오류로 인한 일시 보류 -
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<script type='text/javascript'>");
writer.println("alert('로그인 성공!');");
writer.println("</script>");
writer.flush();
*/
}
else
{
System.out.println("loginIdentify is false : " + loginIdentify);
/*
- 오류로 인한 일시 보류 -
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<script type='text/javascript'>");
writer.println("alert('로그인 실패!');");
writer.println("</script>");
writer.flush();
*/
return "redirect:move_loginPage.do";
}
return "redirect:main.do";
}
// 로그아웃
// 세션과 쿠키 제거 + mainPage로 리다이렉트
#RequestMapping("logout.do")
public String logout(HttpSession session, HttpServletResponse response)
{
session.removeAttribute("id");
Cookie cookie = new Cookie("id", null);
cookie.setMaxAge(0);
response.addCookie(cookie);
// 세션 삭제 확인
System.out.println("session is delete It's really? : " + session.getAttribute("id"));
return "redirect:main.do";
}
}
It is MemberService.java code.
package service;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
public HashMap<String, Object> login(String id,String pw)
{
HashMap<String, Object> result = memberDao.selectOne(id);
System.out.println(result);
if(result != null)
{
String opwd = (String) result.get("pw");
if(opwd.equals(pw))
{
return result;
}
else
{
return null;
}
}
else
{
return null;
}
}
}
When the form tag is executed, the ID value and PW value entered are compared with the ID value and PW value stored in the DB.
If the values ​​match, go to the main page.
If the values ​​do not match, you will not be able to log in without reloading the page! I want to print a message. How can I get it to work the way I want?
I do not know where to start.... I need your help vigorously.
Please advice to me your plan.
You're almost there.
Uncomment the code in MemberController.java that uses response to send data back to the client JavaScript. Something like—
PrintWriter writer = response.getWriter();
writer.println("login succeeded");
writer.flush();
—and similarly for the failure case.
Then, in loginPage.jsp, read the first argument in $.ajax's success function to get that same data back:
$.ajax
({
type: 'POST',
url: 'loginOK.do',
success: function(returnData)
{
console.log(returnData); // <---
},
error: function()
{
alert('error');
}
})
That way, the client will know whether the login succeeded or not, and you can call the appropriate JavaScript functions to open a different page, show an error, clear the password box, or whatever you want to do.
Tangential application security critiques:
I hope you're using HTTPS. If not, user credentials are easy for an attacker to steal.
It seems you are storing your users' passwords in plain text in your database. Consider salting them to protect them in case your database is compromised.

Jquery ajax form submission and spring MVC

I am testing some form submission code using spring MVC in the book "professional java for web applications". You can find the complete code in chapter 13 the spring-forms project
http://www.wrox.com/WileyCDA/WroxTitle/Professional-Java-for-Web-Applications.productCd-1118656466,descCd-DOWNLOAD.html
It works fine without the ajax part in the .jsp below. But when I add the jquery ajax part in the jsp, it does not work. The alert shows name to be undefined.
What did I do wrong?
Here is the code in the controller that binds the userForm object to the form in the .jsp below.
#RequestMapping(value = "user/add", method = RequestMethod.GET)
public String createUser(Map<String, Object> model)
{
model.put("userForm", new UserForm());
return "user/add";
}
#RequestMapping(value = "user/add", method = RequestMethod.POST)
public View createUser(#ModelAttribute("userForm") UserForm form)
{
User user = new User();
user.setUserId(this.getNextUserId());
user.setUsername(form.getUsername());
user.setName(form.getName());
this.userDatabase.put(user.getUserId(), user);
return new RedirectView("/user/list", true, false);
}
Here is the .jsp file
<%--#elvariable id="userForm" type="com.wrox.site.UserForm"--%>
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<script src="http:////code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitForm').submit(function(e) {
var frm = $('#submitForm');
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data : frm.serialize(), //JSON.stringify(data),
success : function(callback){
alert("Response: Name: "+callback.name);
$(this).html("Success!");
},
error : function(){
$(this).html("Error!");
}
});
});
});
</script>
</head>
<body>
<h1>${title}</h1>
<form:form method="post" modelAttribute="userForm" id = "submitForm">
<form:label path="username">Username</form:label><br />
<form:input path="username" /><br />
<br />
<form:label path="name">Name:</form:label><br />
<form:input path="name" /><br />
<br />
<input type="submit" value="Save" />
</form:form>
</body>
</html>
Here is the userForm
package com.wrox.site;
public class UserForm
{
private String username;
private String name;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Here is the list.jsp
<%--#elvariable id="userList" type="java.util.Collection<com.wrox.site.User>"--%>
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h2>Users</h2>
[new user]<br />
<br />
<c:forEach items="${userList}" var="user">
${user.name} (${user.username})
[edit]<br/>
</c:forEach>
</body>
</html>

How to send data in json format in jquery ajax for restfull web services

I am sending the json format data in jquery ajax for restful web services but It is not sending. I am new in web technology, so please help me. I write the script for sending the JSON data using following link
how to pass JSON data to restful web services through ajax and also how to get JSON data?
My javascript code is
<script type="text/javascript">
$(document).ready(function(){
$('#btnBooking').click(function(){
var serviceCategory=document.getElementById("services").value;
var availDate=document.getElementById("scheduledDate").value;
var custName=document.getElementById("userName").value;
var custMobile=document.getElementById("userContactNumber").value;
var custEmail=document.getElementById("addressemailId").value;
var custAddress=document.getElementById("address1").value;
var JSONObject= {"serviceCategory":serviceCategory, "availDate":availDate, "custName":custName, "custMobile":custMobile, "custEmail":custEmail, "custAddress":custAddress};
var jsonData = JSON.stringify( JSONObject );
$.ajax({
url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
type: "POST",
dataType: "json",
data: jsonData,
contentType: "application/json",
success: function(response){
alert(JSON.stringify(response));
},
error: function(err){
alert(JSON.stringify(err));
}
});
});
});
</script>
My Html code is
<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm" action="#" method="post">
<div class="col-lg-8">
<div class="alert alert-danger alert-dismissable" style="display: none;" id="errorMessageDiv">Error
Message Goes Here</div>
<div class="form-group">
<label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input class="form-control" id="userName" name="userName" placeholder="Full Name" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Services:</label>
<div class="col-lg-9">
<select class="form-control" id="services" name="subService">
<option>Select Service</option>
<option value="1">Carpenter</option>
<option value="2">Mobile SIM services</option>
</select>
</div>
</div>
<div class="form-group">
<label for="schedule-tme" class="col-lg-3 control-label">Schedule Date:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<div class="input-group date form_datetime" data-date="dd-M-yyyy">
<input placeholder="Choose Date" class="form-control" value="" onchange="timeValidate()" id="scheduledDate" name="scheduledDate" readonly="readonly" type="text"> <span class="input-group-addon"> <span class="glyphicon glyphicon-th calender-click"></span></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Address:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input class="form-control" name="address1" id="address1" placeholder="Full address" value="" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">City:</label>
<div class="col-lg-9">
<input class="form-control" id="" value="Bangalore" name="" placeholder="City Name" readonly="readonly" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input class="form-control" id="userContactNumber" name="userContactNumber" placeholder="Mobile Number" onkeypress="enableKeys(event);" maxlength="10" type="text">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
<div class="col-lg-9">
<input class="form-control" name="addressemailId" id="addressemailId" placeholder="you#example.com" value="" type="text">
</div>
</div>
<div class="form-group marg-bot-45">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-9">
Confirm Booking <span class="glyphicon glyphicon-ok"></span>
</div>
</div>
</div>
</form>
Booking.java
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Booking generated by hbm2java
*/
#Entity
#Table(name = "booking", catalog = "service4homes")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Booking implements java.io.Serializable {
private Integer BId;
private ServiceProviderStatus serviceProviderStatus;
private ServiceCategory serviceCategory;
private Date availDate;
private String custName;
private String custMobile;
private String custEmail;
private String custAddress;
private Set<Allocation> allocations = new HashSet<Allocation>(0);
private Set<SuperAdmin> superAdmins = new HashSet<SuperAdmin>(0);
public Booking() {
}
public Booking(ServiceProviderStatus serviceProviderStatus,
Customer customer, ServiceCategory serviceCategory, Date availDate,
String custEmail) {
this.serviceProviderStatus = serviceProviderStatus;
this.serviceCategory = serviceCategory;
this.availDate = availDate;
this.custEmail = custEmail;
}
public Booking(ServiceProviderStatus serviceProviderStatus,
Customer customer, ServiceCategory serviceCategory, Date availDate,
String custName, String custMobile, String custEmail,
String custAddress, Set<Allocation> allocations,
Set<SuperAdmin> superAdmins) {
this.serviceProviderStatus = serviceProviderStatus;
this.serviceCategory = serviceCategory;
this.availDate = availDate;
this.custName = custName;
this.custMobile = custMobile;
this.custEmail = custEmail;
this.custAddress = custAddress;
this.allocations = allocations;
this.superAdmins = superAdmins;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "b_id", unique = true, nullable = false)
public Integer getBId() {
return this.BId;
}
public void setBId(Integer BId) {
this.BId = BId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "sps_id", nullable = false)
#JsonIgnore
public ServiceProviderStatus getServiceProviderStatus() {
return this.serviceProviderStatus;
}
public void setServiceProviderStatus(
ServiceProviderStatus serviceProviderStatus) {
this.serviceProviderStatus = serviceProviderStatus;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "sc_id", nullable = false)
#JsonIgnore
public ServiceCategory getServiceCategory() {
return this.serviceCategory;
}
public void setServiceCategory(ServiceCategory serviceCategory) {
this.serviceCategory = serviceCategory;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "avail_date", nullable = false, length = 19)
public Date getAvailDate() {
return this.availDate;
}
public void setAvailDate(Date availDate) {
this.availDate = availDate;
}
#Column(name = "cust_name", length = 50)
public String getCustName() {
return this.custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "cust_mobile", length = 13)
public String getCustMobile() {
return this.custMobile;
}
public void setCustMobile(String custMobile) {
this.custMobile = custMobile;
}
#Column(name = "cust_email", nullable = false, length = 50)
public String getCustEmail() {
return this.custEmail;
}
public void setCustEmail(String custEmail) {
this.custEmail = custEmail;
}
#Column(name = "cust_address", length = 100)
public String getCustAddress() {
return this.custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
public Set<Allocation> getAllocations() {
return this.allocations;
}
public void setAllocations(Set<Allocation> allocations) {
this.allocations = allocations;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
#JsonIgnore
public Set<SuperAdmin> getSuperAdmins() {
return this.superAdmins;
}
public void setSuperAdmins(Set<SuperAdmin> superAdmins) {
this.superAdmins = superAdmins;
}
}
I think you will have to add contentType also to the ajax request call,because you are trying to send json format data to server,like below.
var request = $.ajax({
url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
type: "POST",
data: jsonData,
contentType: "application/json",
dataType: "json"
});
dataType : data format, you are expecting form server
contentType : data format ,you are sending to server
Are you sure its not working ? I copied the same code as yours and tried executing on my domain and its just fine. here is the code, I replaced the variables with some hardcoded numbers.
var jsonData = JSON.stringify({"serviceCategory": 4, "availDate":2, "custName":4, "custMobile":4, "custEmail":4, "custAddress":4});
$.ajax({
url: "http://cloudpanel.abstractdns.com",
type: "POST",
dataType: "json",
data: jsonData,
contentType: "application/json",
success: function(response){
alert(JSON.stringify(response));
},
error: function(err){
alert(JSON.stringify(err));
}
});
And here is the screenshot from firefox console that shows JSON data was sent properly.
The screenshot above clearly says its sending the correct data in the format specified. And if its not working can paste the screenshot from firebug so we can understand if its really not working, I'm saying this as you have already told that your new to web technologies. In case you don't know, you can install firebug on mozilla and chrome and do the inspecting yourself that will give you the insights of errors in any.
With respect to your comment, you have stated that you get an error regarding CORS. So this could be solved by replacing dataType: json with dataType: "jsonp". That should solve your problem if your app that has ajax and the app that ajax sends requests are on different servers.
Hope that helps
You have mixed up JSON.parse() and JSON.stringify()
JSON.parse():
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.
JSON.stringify():
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
So in your code, you have to change JSON.parse to JSON.stringify
You have to send a string which is Json data. So convert your javascript object "JSONObject" with JSON.stringify
var JSONObject= ...;
var jsonData = JSON.stringify( JSONObject );
Here you can find an example how u can extend jquery to have a postJSON function if you need this functionality more often.

Implementing Ajax in spring MVC

Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST

Categories