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>
Related
my java code is not working when pulling data in database.
Where am I going wrong? I tried many times but it didn't work.
I'm looking at debug mode mastercontroller. data is not coming.
I have jquery.min.js attached on my layout page.
I tried another js code as a trial, it works. I'm waiting for your help
My java code is not working when adding category array to mvc using jquery
//categoryaddt.js
$(document).ready(function () {
$("#categoryform").validate({
rules: {
Name: { required: true },
},
messages: {
Nanem: "Please Enter a Valid Name."
},
submitHandler: function (e) {
var chk = 0;
if ($("#closeButton").prop('checked') == true) {
chk = 1;
}
var RequestCls = {
Name: $("#txtName").val(),
Active: chk
}
var UrlApi = '#Url.Content("~")' + "Master/AddCategory";
$.ajax({
url: UrlApi,
type: 'POST',
data: JSON.stringify(RequestCls),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert(data.message);
}
});
}
})
});
//Category.cshtml
#{
ViewBag.Title = "Category";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="row">
<div class="card">
<div class="card-body">
<form id="categoryform" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="Name">Name</label>
<input id="txtName" name="Name" type="text" class="form-control" autocomplete="off" />
</div>
<div class="custom-control custum-checkbox mb-2">
<input type="checkbox" class="custom-control-input input-mini" id="closeButton" value="checked" />
<label class="custom-control-label" for="closeButton">Is Active</label>
</div>
</div>
</div>
<button type="submit" id="btnSave" class="btn btn-primary mr-1 waves-effect waves-light"></button>
</form>
</div>
</div>
</div>
</div>
#section scripts{
<script src="~/Scripts/categoryaddt.js"></script>
}
//MasterCls.cs
using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls
{
public class MasterCls : IMaster
{
QrperidEntities dbEntity;
public MasterCls()
{
dbEntity = new QrperidEntities();
}
public ResponseCls AddCategory(RequestCls obj)
{
ResponseCls result = new ResponseCls();
result.message = "Kayıt Başarı ile Yapıldı...!";
result.status = "succes";
result.flag = 1;
try
{
using (var db = dbEntity)
{
Category _category = new Category();
_category.Name = obj.Name;
_category.Active = obj.Active;
db.Category.Add(_category);
db.SaveChanges();
}
}
catch (Exception ex)
{
result.message = ex.Message.ToString();
result.status = "error";
result.flag = 0;
}
return result;
}
}
}
//IMaster.cs
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nero_Medya_Inventory_Management_System.BusinessLogic.IService
{
public interface IMaster
{
ResponseCls AddCategory( RequestCls obj );
}
}
//Category.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Nero_Medya_Inventory_Management_System
{
using System;
using System.Collections.Generic;
public partial class Category
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Active { get; set; }
}
}
//MasterController.cs
using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Nero_Medya_Inventory_Management_System.Controllers
{
public class MasterController : Controller
{
// GET: Master
IMaster _master;
public MasterController()
{
_master = new MasterCls();
}
public ActionResult Category()
{
return View();
}
[HttpPost]
public JsonResult AddCategory(RequestCls obj)
{
var result = _master.AddCategory(obj);
return Json(result,JsonRequestBehavior.AllowGet);
}
}
}
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
I'am a newbie with signalR in ASP.NET C#.
the problem , I uses state management instead of Group property in Person class.
public class Person
{
public string Name { get; set; }
public string Message { get; set; }
// public string Group { get; set; }
}
Client Code to Pass the State
<script src="scripts/jquery-1.6.4.min.js"></script>
<script src="scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var broadcaster = $.connection.firstHub;
broadcaster.client.displayText = function (name, message) {
$('#messages').append('<li>' + name + ' said: ' + message + '</li>');
};
$.connection.hub.start().done(function () {
$("#broadcast").click(function () {
broadcaster.server.join($('#groupName').val());
broadcaster.state.GroupName = $('#groupName').val();
broadcaster.server.broadcastMessage({ Name: $('#name').val(),Message: $('#message').val() });
broadcaster.server.leave($('#groupName').val());
});
});
});
</script>
<div>
<input type="text" id="groupName" />
<input type="text" id="name" />
<input type="text" id="message" />
<input type="button" id="broadcast" value="Broadcast" />
<ul id="messages"></ul>
</div>
Hub Implementation to Use the State Values
[HubName("firstHub")]
public class Chapter3Hub : Hub
{
public void BroadcastMessage(Person person)
{
Context.ConnectionId).displayText(person.Name, person.Message);
Clients.Group(Clients.Caller.GroupName).displayText(person.Name, person.Message);
}
public Task Join(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task Leave(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
}
When i run , VS bugs this. 'Microsoft.AspNet.SignalR.Hubs.IHubCallerConnectionContext' does not contain a definition for 'Group'
hjk , I have modified this line .
Clients.Group((string)Clients.Caller.GroupName).displayText(person.Name, person.Message);
and run successfully.
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.
I am attempting to using knockout to create a client side model so client side validation can be done on the needed attributes, some of which are nested and or in nested lists of other models.
In following some guides and patterns, I have tried to map a test list from the main view model and send it back to the controller when the form submits, with validation that would prevent the form from being submitted if the value is null.
When the form is submitted, not only does it fail to validate with the current set up, the edited values (which are correctly populated in the view on load, so some type of binding is correctly working) return as null in the controller.
namespace KnockoutDemo.Models
{
public class XmlParameter
{
public HttpPostedFileBase XmlValue;
public string Name;
}
}
public class TestStepViewModel
{
public int TestStepId { get; set; }
public string TestStepName { get; set; }
public string Message { get; set; }
public List<XmlParameter> XmlParameters { get; set; }
}
View
#using System.Web.Mvc.Ajax
#using System.Activities.Expressions
#using System.Web.Script.Serialization
#model KnockoutDemo.Models.TestStepViewModel
#{ string data = new JavaScriptSerializer().Serialize(Model);}
#section scripts
{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/teststepviewmodel.js"></script>
<script type="text/javascript">
var testStepViewModel = new TestStepViewModel(#Html.Raw(data));
ko.applyBindings(testStepViewModel);
</script>
}
<form>
<div>
<div class="form-group">
<label class="control-label" for="TestStepName">Test Step Name:</label>
<input class="form-control" name="TestStepName" id="TestStepName" data-bind="value: TestStepName"/>
</div>
<div class="form-group">
<label class="control-label" for="TestStepName">Test Step Id:</label>
<input class="form-control" name="TestStepId" id="TestStepId" data-bind="value: TestStepId" disabled="disabled"/>
</div>
<table class="table table-striped">
<tr>
<th>Product Code</th>
</tr>
<tbody data-bind="foreach: XmlParameters">
<tr>
<td class="form-group"><input name="Name" class="form-control input-sm" data-bind="attr: {'id': 'Name_' + $index()}, value: Name"/></td>
</tr>
</tbody>
</table>
</div>
<p><button class="btn btn-primary" data-bind="click: save" type="submit" >Save</button></p>
</form>
teststepviewmodel.js + validation
TestStepViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/Home/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json"
});
}
}
var XmlParameter = function(data) {
var self = this;
ko.mapping.fromJS(data, mapping, self);
}
var mapping = {
'XmlParameters': {
key: function (xmlParameters) {
return ko.utils.unwrapObservable(xmlParameters.Name);
},
create: function (options) {
return new XmlParameter(options.data);
}
}
};
$("form").validate({
submithandler: function () {
testStepViewModel.save();
},
rules: {
TestStepName: {
required: true,
maxlength: 30
},
Value: {
required: true
},
XmlValue: {
required: true
}
},
messages: {
TestStepName: {
required: "A Test Step must have a non-null value, please enter a name"
},
Value: {
required: "The parameter can't be null/empty"
}
}
});
The JsonResult Save() controller correctly populates the Id and Test Step Name, however the XmlParameters are both null.
Controllers (Like I said, this is simply a test to return knockout model with client side validation, so I'm simply populating a view model on load and setting a breakpoint on the JsonResult to see the contents of the model)
public ActionResult Index(TestStepViewModel ts)
{
TestStepViewModel testStepViewModel = new TestStepViewModel
{
TestStepName = "Editing A Test Step",
TestStepId = 10,
Message = "Hello, this is a message"
};
testStepViewModel.XmlParameters = new List<XmlParameter>();
testStepViewModel.XmlParameters.Add(new XmlParameter
{
Name = "Xml P1"
});
testStepViewModel.XmlParameters.Add(new XmlParameter
{
Name = "Xml P2"
});
return View("Index", testStepViewModel);
}
public JsonResult Save(TestStepViewModel testStepViewModel)
{
return null;
}