Wicket Modal dialog, form validation in AjaxBootstrapTabbedPanel - java

I've to create a modal dialog which contains a AjaxBootstrapTabbedPanel with two or more tabs. All tabs belong to the same form.
Each tab contains required input fields, select boxes or drop down choices. Until now,
I don't use own validators, but this is a future task.
I was able to trigger the validation when switching between the tabs.
When I use the dialog like variant A and B, I get proper feedback from validation.
Variant A
open the dialog
closing the dialog via submit button immediately results in feedback message "please enter a value in field..."
Variant B
open the dialog
switch to another tab without filling required fields on initial tab gives
also "please enter a value in ..."
Variant C - validation problem
But using the dialog in this way doesn't result in feedback messages:
open the dialog
enter all required values on the initial tab
don't enter values in required fields on another tab
use the submit button to close the diaolg: no feedback message!!, but there has to be one or more
In Variant C, no logging output from the method BootstrapAjaxButton#onError() is printed.
I'm using Wicket 7.6.0 and Wicket-Bootstrap 0.10.11
Class for modal dialog
public abstract class OwsDetailsDialog extends Modal<Ows>
{
private static final long serialVersionUID = -8110788978602397064L;
private BootstrapAjaxButton createOwsBtn;
private BootstrapForm<Ows> owsForm;
public OwsDetailsDialog(String id,
IModel<Ows> owsModel)
{
super(id, owsModel);
setOutputMarkupPlaceholderTag(true);
setDefaultModel(owsModel);
owsForm = new BootstrapForm<>("owsForm");
owsForm.setOutputMarkupId(true);
add(owsForm);
List<ITab> tabs = createTabs(owsModel);
MyAjaxTabbedPanel tabbedPanel = new MyAjaxTabbedPanel("tabbedPanel", tabs);
owsForm.add(tabbedPanel);
createOwsBtn = new BootstrapAjaxButton("submitOws",
Model.of("Create"), Buttons.Type.Default)
{
#Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
super.onError(target, form);
target.add(form, tabbedPanel);
System.out.println("onError() at form ID " + form.getId() + " target.getPage() "
+ target.getPage());
}
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
System.out.println("click on create");
createOws(target, owsModel);
}
};
owsForm.add(createOwsBtn);
BootstrapAjaxButton cancelBtn = new BootstrapAjaxButton("cancelOws",
Model.of("Cancel"), Buttons.Type.Default)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
cancel(target);
}
};
cancelBtn.setDefaultFormProcessing(false);
owsForm.add(cancelBtn);
//FeedbackPanel feedbackOwsDialog = new FeedbackPanel("feedbackOwsDialog");
//add(feedbackOwsDialog);
}
private List<ITab> createTabs(IModel<Ows> owsModel)
{
List<ITab> tabs = new ArrayList<>();
tabs.add(new AbstractTab(Model.of("Data 1"))
{
private static final long serialVersionUID = -9107223557866453561L;
#Override
public WebMarkupContainer getPanel(String panelId)
{
return new OwsMainInfoContainer(panelId, owsModel);
}
});
tabs.add(new AbstractTab(Model.of("Data 2"))
{
private static final long serialVersionUID = -7323530522820254738L;
#Override
public WebMarkupContainer getPanel(String panelId)
{
return new OwsSecondaryInfoContainer(panelId, owsModel);
}
});
return tabs;
}
protected class OwsMainInfoContainer extends Panel
{
private static final long serialVersionUID = -2965824809083715016L;
public OwsMainInfoContainer(
String panelId, IModel<Ows> owsModel)
{
super(panelId, owsModel);
add(new RequiredTextField<>("title"));
add(new RequiredTextField<>("url"));
List<OwsType> types = Arrays.asList(OwsType.values());
DropDownChoice<OwsType> dropDownChoice = new DropDownChoice<>("category", types,
new ChoiceRenderer<OwsType>()
{
private static final long serialVersionUID = 8139757791037487164L;
#Override
public Object getDisplayValue(OwsType owsType)
{
return owsType.getName();
}
});
add(dropDownChoice.setRequired(true));
add(new FeedbackPanel("feedbackMain"));
}
}
protected class OwsSecondaryInfoContainer extends Panel
{
private static final long serialVersionUID = -7396160769731997541L;
public OwsSecondaryInfoContainer(
String panelId, IModel<Ows> owsModel)
{
super(panelId, owsModel);
add(new DateTextField("firstPublished"));
add(new TextField<>("provider").setRequired(true));
add(new TextField("price").setRequired(true));
add(new FeedbackPanel("feedbackSecondary"));
}
}
protected abstract void createOws(AjaxRequestTarget target
, IModel<Ows> owsWithUtilDateIModel);
protected abstract void cancel(AjaxRequestTarget target);
// http://www.volkomenjuist.nl/blog/2009/12/01/ajaxtabbedpanel-store-state-when-switching-tabs/
class MyAjaxTabbedPanel extends AjaxBootstrapTabbedPanel<ITab>
{
private static final long serialVersionUID = 1513951445901529991L;
public MyAjaxTabbedPanel(String id, List<ITab> tabs)
{
super(id, tabs);
}
#Override
protected WebMarkupContainer newLink(String linkId, final int index)
{
return new AjaxSubmitLink(linkId, owsForm)
{
private static final long serialVersionUID = 7049548660275591812L;
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
setSelectedTab(index);
if (target != null)
{
target.add(form);
}
onAjaxUpdate(target);
System.out.println("onSubmit() on target.getPage(): " + target.getPage());
}
#Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
MyAjaxTabbedPanel component = MyAjaxTabbedPanel.this;
target.add(component);
System.out.println("in onError() , target.add() on " + component.getId());
}
};
}
}
}
Class extending WebPage
public class MyPage extends WebPage
{
private static final long serialVersionUID = 6826446949682313116L;
public MyPage()
{
Form<Void> form = new Form<Void>("buttonForm");
add(form);
form.setOutputMarkupId(true);
OwsDetailsDialog owsDialog = new OwsDetailsDialog("owsDialog"
, new CompoundPropertyModel<Ows>(new Ows()))
{
#Override
protected void createOws(AjaxRequestTarget target,
IModel<Ows> model)
{
Ows ows = model.getObject();
System.out.println("object: "+ ows);
close(target);
}
#Override
protected void cancel(AjaxRequestTarget target)
{
System.out.println("click auf abbrechen");
close(target);
}
};
add(owsDialog);
BootstrapAjaxButton createOwsButton = new BootstrapAjaxButton("createOwsButton",
Model.of("OWS neu"), Buttons.Type.Default)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
super.onSubmit(target, form);
owsDialog.setDefaultModelObject(new Ows());
target.add(owsDialog);
TabbedPanel tabbedPanel = (TabbedPanel) owsDialog.get("owsForm:tabbedPanel");
tabbedPanel.setSelectedTab(0);
owsDialog.show(target);
}
};
form.add(createOwsButton);
}
}
PoJo
package example.tryOut.ows;
import java.util.Date;
public class Ows
{
private Integer index=0;
private String title = "";
private String provider = "";
private String url = "";
private OwsType category;
private Date firstPublished =null;
private Double price=0.0;
public Integer getIndex()
{
return index;
}
public void setIndex(Integer index)
{
this.index = index;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getProvider()
{
return provider;
}
public void setProvider(String provider)
{
this.provider = provider;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public OwsType getCategory()
{
return category;
}
public void setCategory(OwsType category)
{
this.category = category;
}
public Date getFirstPublished()
{
return firstPublished;
}
public void setFirstPublished(Date firstPublished)
{
this.firstPublished = firstPublished;
}
public Double getPrice()
{
return price;
}
public void setPrice(Double price)
{
this.price = price;
}
#Override
public String toString()
{
return "Ows{" +
"index=" + index +
", title='" + title + '\'' +
", provider='" + provider + '\'' +
", url='" + url + '\'' +
", category=" + category +
", firstPublished=" + firstPublished +
", price=" + price +
'}';
}
}
Markup
Page
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<form wicket:id="buttonForm">
<button wicket:id="createOwsButton"></button>
</form>
<div wicket:id="owsDialog"></div>
</body>
</html>
Dialog
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:extend>
<form wicket:id="owsForm">
<div wicket:id="tabbedPanel" class="container" style="width: inherit"></div>
<button type="submit" wicket:id="submitOws" class="btn btn-main">Anlegen</button>
<button type="reset" wicket:id="cancelOws" class="btn btn-main">Abbrechen</button>
</form>
</wicket:extend>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:panel>
<div class="form-group">
<label wicket:for="url">URL</label>
<div class="controls">
<input type="text" wicket:id="url" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="title">Title</label>
<div class="controls">
<input type="text" wicket:id="title" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="category">OWS Category</label>
<div class="controls">
<select wicket:id="category">
<option value="">dummy1</option>
<option value="">dummy2</option>
</select>
</div>
</div>
<div wicket:id="feedbackMain"></div>
</wicket:panel>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<wicket:panel>
<div class="form-group">
<label wicket:for="price">Price</label>
<div class="controls">
<input type="text" wicket:id="price" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="provider">Provider</label>
<div class="controls">
<input type="text" wicket:id="provider" class="form-control"/>
</div>
</div>
<div class="form-group">
<label wicket:for="firstPublished">First published</label>
<div class="controls">
<input type="date" wicket:id="firstPublished" class="form-control"/>
</div>
</div>
<div wicket:id="feedbackSecondary"></div>
</wicket:panel>
</body>
</html>

Related

how to associate checkbox with text box, so that selected checkbox and corresponding value of text box gets updated in database

I want to associate checkbox id(which is dynamically created) with text box.
For Example : If 5 check boxes are appearing along with 5 text boxes, i want that the check box i select the corresponding value will get update in database.
Problem : if 5 check boxes are appearing on jsp page and if i select 2, 4 and 5th checkboxes, then corresponding text box values i.e. 2,4 and 5th value should be inserted in database.
But in my case checkboxes are inserted correctly but values are not inserting. it is inserting like for 2nd check box ---> it is selecting first textbox,
and for 4th checkbox ----> it is selecting 2nd textbox value and for 5th checkbox it is selecting -----> 3 textbox value.
I known that it is because of this code : Here Attribute List contains three selected checkBox but attribute value contains 5 elements. and it will pick only three.
List<Object[]> inputList = new ArrayList<Object[]>();
for (int i = 0; i < qualification.getAttributeList().length; i++) {
Object[] tmp = {newCompanyId,qualification.getAttributeList()[i],qualification.getAttributeValue()[i]};
inputList.add(tmp);
Can anyone please let me know ho to solve the issue. Please find the attached pics.
Qualification Controller
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(ModelAndView model, HttpServletRequest req, HttpServletResponse res,
#ModelAttribute Qualification qualification, HttpSession session) throws AppException {
String userId = session.getAttribute("loggedInUserId").toString();
qualificationDAO.save(qualification, userId);
model.setViewName("qualification");
return model;
}
Qualification.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="tg" tagdir="/WEB-INF/tags"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<jsp:useBean id="pagedListHolder" scope="request" class="org.springframework.beans.support.PagedListHolder" />
<!-- Main Body Section Start -->
<main class="container padContnr">
<div class="row">
<div class="col-md-12">
<h1>Qualification Rules</h1>
</div>
</div>
<div class="bg-ltgreen padding-10 margin-t-10" id="QualEdit">
<form:form class="form-horizontal" action="save" modelAttribute="qualification" method="post" >
<div class="row">
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<label class="label-bg col-xs-12">Company <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="company" class="form-control" path="company">
<form:option value="Select" />
<form:options items="${companyList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
<div class="form-group">
<label class="label-bg col-xs-12">Class <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="companyClass" class="form-control" path="companyClass" onchange="switchOption();">
<form:option value="Select" />
<form:options items="${classList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<%-- <div class="form-group">
<label class="label-bg col-xs-12">Status <span class="red">*</span></label>
<div class="col-xs-12">
<form:select class="form-control" path="status" >
<form:option value="Select"></form:option>
<form:options items="${statusList}" itemValue="id" itemLabel="dropdownValue" />
</form:select>
</div>
</div> --%>
<div class="form-group">
<label class="label-bg col-xs-12">Rule <span class="red">*</span></label>
<div class="col-xs-12">
<form:input path="rule" class="form-control" type="text" />
</div>
</div>
</div>
</div>
<div id="QualAtt"class="row margin-t-10">
<div id="QualAtt1" class="col-md-6">
<!-- table data -->
</div>
</div>
<div class="row">
<div class="col-xs-12 margin-t-10">
<!-- <button class="btn btn-primary btnSubmit" type="submit" id="QualSav">Save</button> -->
<button type="submit" class="btn btn-primary btnSubmit"> </button>
<button class="btn btn-default btnCancel" type="button" id="QualCanl">Cancel</button>
</div>
</div>
</form:form>
</div>
</main>
Qualification Model
package com.hcl.ne.model;
import java.util.HashMap;
import java.util.Map;
/**
* #author diwakar_b
*
*/
public class Qualification {
private int id;
private String company;
private String companyClass;
private String rule;
private String lastModifiedOn;
private String lastModifiedBy;
private String status;
private String[] attributeList;
private String[] attributeValue;
private int pagesize;
private String ruleId;
private String[] attributeListNames;
private String[] attributeValueNames;
private String classId;
private String attributeId;
private String attributeName;
private String attributeValues;
public String[] getAttributeValue() {
return attributeValue;
}
public void setAttributeValue(String[] attributeValue) {
this.attributeValue = attributeValue;
}
public String getAttributeValues() {
return attributeValues;
}
public void setAttributeValues(String attributeValues) {
this.attributeValues = attributeValues;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeId() {
return attributeId;
}
public void setAttributeId(String attributeId) {
this.attributeId = attributeId;
}
public String[] getAttributeList() {
return attributeList;
}
public void setAttributeList(String[] attributeList) {
this.attributeList = attributeList;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCompanyClass() {
return companyClass;
}
public void setCompanyClass(String companyClass) {
this.companyClass = companyClass;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(String lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRuleId() {
return ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public String[] getAttributeListNames() {
return attributeListNames;
}
public void setAttributeListNames(String[] attributeListNames) {
this.attributeListNames = attributeListNames;
}
public String[] getAttributeValueNames() {
return attributeValueNames;
}
public void setAttributeValueNames(String[] attributeValueNames) {
this.attributeValueNames = attributeValueNames;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
}
PLugin.js
$('#QualSav, #QualCanl').on('click', function() {
$("#QualEdit").hide();
$("#QualRules").hide();
$("#QualSerch").show();
});
// Qualification -- Edit
$('#EditBtnQualification').on('click', function() {
var ruleId=$('table.trClick tbody tr.trActive td:first').html();
$('#ruleId').val(ruleId);
document.qualificationEditForm.submit();
});
function switchOption() {
var selectedValue= $("#companyClass").val();
$.ajax({
type: "GET",
url: "getClass",
data:'classId='+selectedValue,
success: function(data){
var tablebody = $('<tbody>');
var tablerow = "";
$(data.resultMenuForLocation).each(function(index){
tablerow = $('<tr>')
.append($('<td>').append($('<input>').attr({type :'checkbox'}).attr('class','checkBoxSize').attr({value : ''+$(this)[0].id}).attr('id','attributeList').attr('name','attributeList')))
.append($('<td>').append($(this)[0].dropdownValue+''))
.append($('<td>').append($('<input>').attr({type :'text'}).attr('class','form-control').attr('id','attributeValue').attr('name','attributeValue')))
$(tablebody).append(tablerow);
});
$('<table>')
.attr('id','master_table')
.attr('class','myAttr f-size-16')
.html('<thead><tr><th> </th><th>Attribute</th><th>Value</th></tr></thead>')
.append(tablebody)
.appendTo('div#QualAtt1');
}
});
};

Wicket - Trouble with submit button function when value is null

This is my yesNoPanel class, extending Panel :
public class YesNoPanel extends Panel {
/**
*
*/
private String password = "Password";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private static final long serialVersionUID = -8356163236155431543L;
public String getPw()
{
String pw=ConfigurationHelper.getConfigurationProperty("REFRESH_CACHE_PASSWORD", "");
return pw;
}
public YesNoPanel(String id, String message, final ModalWindow modalWindow, final ConfirmationAnswer answer) {
super(id);
final Form yesNoForm = new Form("yesNoForm");
final String wrongPw = "Wrong Password";
final TextField<String> passwordString = new RequiredTextField<String>("password", new PropertyModel(this, password));
passwordString.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
}
});
MultiLineLabel messageLabel = new MultiLineLabel("message", message);
yesNoForm.add(messageLabel);
final Label wrongPW = new Label("WrongPassword", wrongPw );
modalWindow.setTitle("Please confirm");
modalWindow.setInitialHeight(200);
modalWindow.setInitialWidth(350);
AjaxButton yesButton = new AjaxButton("yesButton", yesNoForm) {
private static final long serialVersionUID = -3827487963204274386L;
#Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
if (target != null && password.equals(getPw())) {
answer.setAnswer(true);
modalWindow.close(target);
}else if(target != null && !password.equals(getPw())){
answer.setAnswer(false);
wrongPW.setVisible(true);
target.add(wrongPW);
}
}
};
AjaxButton noButton = new AjaxButton("noButton", yesNoForm) {
#Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
if (target != null) {
answer.setAnswer(false);
modalWindow.close(target);
wrongPW.setVisible(false);
}
}
};
yesNoForm.add(yesButton);
yesNoForm.add(noButton);
yesNoForm.add(passwordString);
add(yesNoForm);
wrongPW.setOutputMarkupPlaceholderTag(true);
wrongPW.setVisible(false);
add(wrongPW);
}
}
and the HTML in question :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:wicket>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
</head>
<body>
<wicket:panel>
<form wicket:id="yesNoForm" action="">
<span wicket:id="message">Are you sure?</span>
<table style="width: 65%;" align="center">
<tr>
<td align="left">
<input type="submit" wicket:id="noButton" value="No" />
</td>
<td align="right">
<input type="text" wicket:id="password" size = "20" />
</td>
<td align="right">
<input type="submit" wicket:id="yesButton" value="Yes" />
</td>
</tr>
</table>
</form>
<font color="red"><p align="center" wicket:id="WrongPassword"></p> </font>
</wicket:panel>
</body>
As it is now, when the user opens the modal window the input box is filled with the wicket id password - which is simply the string "Password". The Yes or No buttons don't do anything if the input if left blank (or a placeholder is used, which is preferable). Why is this and how can I work around it?
You should use a TextField rather than a RequiredTextField.
Using a RequiredTextField with blank input, the buttons don't do anything.

Web app using java and angularjs

i'm trying to create simple market web application. I want to add a sign-in functionality to add users in my db, but i can't understand, how can i "call" my registration method (from java) in js script. Currently, the only thing that my web-app actually does is show records(which i added manually) from users-table.
Here is my db-manager:
`public class DatabaseManager {
public static String host = "localhost";
public static String port = "5432";
public static String dbname = "market";
public static String user = "postgres";
public static String pass = "123456";
public static String url = "jdbc:postgresql://"+host+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
static {
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Can not connect to the database:\n"+e.getMessage());
}
return null;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
Auth - dto:
public class Auth {
public static class RegisterReq {
public String name;
public String lastname;
public String login;
public String pass;
public int age;
public String gender;
public RegisterReq(String name, String lastname, String login, String pass, int age, String gender) {
this.name = name;
this.lastname = lastname;
this.login = login;
this.pass = pass;
this.age = age;
this.gender = gender;
}
}
public static class RegisterResp {
public boolean status;
public RegisterResp(boolean status) {
this.status = status;
}
}
public static class LoginReq {
public String login;
public String pass;
public LoginReq(String login, String pass) {
this.login = login;
this.pass = pass;
}
}
public static class LoginResp {
public boolean status;
public LoginResp(boolean status) {
this.status = status;
}
}
}
Auth-class with sign-up method:
`
import static dto.Auth.*;
#Path("/auth")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class Auth {
#POST
#Path("/register")
public RegisterResp register(RegisterReq req) {
boolean result = false;
//sql
Connection connection = null;
try {
connection = DatabaseManager.getConnection();
Statement stmt = connection.createStatement();
String checkSql = "select e_mail from users";
ResultSet resultSet=stmt.executeQuery(checkSql);
while (resultSet.next()) {
if(req.login.equals(resultSet.getString(1))) return new RegisterResp(result);
}
//unsafe query
String sql = "INSERT INTO users" +
" (u_name, u_lastname, e_mail, password, age, gender, reg_date)" +
" VALUES (" +
req.name + ","+
req.lastname + ","+
req.login + ","+
req.pass + "," +
req.age + ","+
req.gender + ","+
new java.sql.Timestamp(new java.util.Date().getTime()) + ")";
result = stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) DatabaseManager.closeConnection(connection);
}
return new RegisterResp(result);
}`
Main page HTML file:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Market start page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="./resources/css/app.css">
</head>
<body ng-controller="UserController">
<div style="background: #8fb9ee" class="jumbotron">
<h1>Market homepage</h1>
<h2>Welcome!</h2>
<p align="center">
Register
Log in
</p>
</div>
<hr>
<div >
<ul>
<p style="font-size: xx-large" >Total user count: {{users.length}} </p>
<table class="TableStyle">
<tr class="RowHeaderStyle">
<th >Firstname</th>
<th >Lastname</th>
<th >E-mail</th>
<th >Age</th>
<th >Gender</th>
</tr>
<tr ng-repeat="user in users" class="RowStyle">
<td >{{user.name}}</td>
<td >{{user.lastname}}</td>
<td >{{user.e_mail}}</td>
<td >{{user.age}}</td>
<td >{{user.gender}}</td>
</tr>
</table>
</ul>
</div>
<input type="checkbox" ng-model="value"> admin ?
<div ng-if="value">Admin</div>
<div ng-if="!value">User</div>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.js"></script>
<script src="./resources/js/app.js"></script>
</body>
</html>
Register HTML-file:
<h2>Register</h2>
<div ng-controller="RegisterController" align="center" class="container-fluid">
<table >
<tr>
<td>First name</td>
<td><input type="text" ng-model="fname"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" ng-model="lname"></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" ng-model="uemail"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="text" ng-model="upass"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select ng-model="ugend" >
<option>male</option>
<option>female</option>
</select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" ng-model="uage"></td>
</tr>
</table>
<button role="button" ng-click="AddUser()"> Confirm </button>
</div>
And app JS file with my silly tries to do something:
`angular.module('app', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: './resources/partials/login.html',
controller: 'RegisterController'
}).
when('/register', {
templateUrl: './resources/partials/register.html',
controller: 'LoginController'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('UserController', ['$scope', '$resource', function($scope, $resource) {
var User = $resource('/r/users');
var users = User.query(function() {
$scope.users = users;
});
}])
.controller('LoginController', ['$scope', '$resource', function($scope, $resource) {
}])
.controller('RegisterController', ['$scope', '$resource',"$http", function($scope,$http, $resource) {
//here should be something smart
$scope.AddUser = function() {
};
}]);`
I'm working in Intellij, and this is my first try to do something, so don't stone me =).
Roughly, your RegisterController should look like this:
.controller('RegisterController', ['$scope', '$resource', function($scope, $resource) {
var auth = $resource('/auth/:action', null, {
login: {
method: 'POST',
params: {
action: 'login'
},
},
register: {
method: 'POST',
params: {
action: 'register'
}
}
});
$scope.AddUser = function() {
// your data consumed from UI
var data = {
name: $scope.name
lastname: $scope.lastname,
login: $scope.login,
pass: $scope.pass,
age: $scope.age,
gender: $scope.gender
};
auth.register(null, data, function(resp) {
// your callback when response is received
// resp variable contains response data sent from server
if (resp.status) {
// registered successfully
} else {
// some error occurred
}
});
};
}]);
If i understood your question correcty. One way to go about that is to create an angular service to perform the ajax post ill paste an example from a current spring-boot angular app im developping. im using es6 but the conecpt is the same
So here is a snippet of the service
class UserService
{
constructor($http)
{
HTTP.set(this, $http);
}
// getGroups(groupId){
// return HTTP.get(this).get(`/api/v1/group/group/?id=${groupId}`).then(result => result.data.objects );
// }
//
// createUserInGroup(groupId,user){
// return HTTP.get(this).post(`/api/v1/group/user/${groupId}`,user);
// }
updateUser(userId,user){
return HTTP.get(this).put(`/api/v1/user/${userId}`, user);
}
You can tell im injecting the $http angular object to be able to perform the request, you'll have to do the same thing if you decide to go with making a service
In The controller, Im injecting the service
class NewGroupController{
constructor($timeout,$modalInstance, groupSvc,currentGroup){
GROUP_SERVICE.set(this, groupSvc);
MODAL_INSTANCE.set(this,$modalInstance);
TIMEOUT.set(this, $timeout);
CURRENT_GROUP.set(this,currentGroup);
With the Group Service in i can call the method and thats it.
Hope it helps

How can I make Ajax and Struts2 together?

I am a newbie and this is my first post, I am doing a simple project that combine ajax and struts. My code as below, my question is : After I got correct value(department) from Action on jsp page, the correct result will be refresh because of "return query;" in QueryAction.java, however, if I have to use "return query;" to get value for query.jsp....How can I solve it ?
query.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
<title>Query Page</title>
<h1 align="center" id="h1"></h1>
</head>
<body>
<p id="demo"></p>
<s:include value="/msg.jsp" />
<s:form action="query" id="form">
<s:textfield name="name" id="name" label="Search the Department" />
<s:submit value="Search" onclick="return myFunction()" id="submitRowAdd" />
</s:form>
<table border="1" id="depTable">
<tr>
<td>Department ID</td>
<td>Department Name</td>
<td>Manager ID</td>
<td>Repeal</td>
</tr>
</table>
<br>
<script type="text/javascript">
var btnAdd = document.getElementById("form");
btnAdd.onsubmit = function(){
var txtTd = document.createTextNode("<s:property value="did"/>");
var eleTd = document.createElement("td");
eleTd.appendChild(txtTd);
var txtTd1 = document.createTextNode("<s:property value="dname"/>");
var eleTd1 = document.createElement("td");
eleTd1.appendChild(txtTd1);
var txtTd2 = document.createTextNode("<s:property value="mid"/>");
var eleTd2 = document.createElement("td");
eleTd2.appendChild(txtTd2);
var txtTd3 = document.createTextNode("<s:property value="rep"/>");
var eleTd3 = document.createElement("td");
eleTd3.appendChild(txtTd3);
var eleTr = document.createElement("tr");
eleTr.appendChild(eleTd);
eleTr.appendChild(eleTd1);
eleTr.appendChild(eleTd2);
eleTr.appendChild(eleTd3);
var theTable = document.getElementById("depTable");
theTable.appendChild(eleTr);
}
</script>
QueryAction.java
package actions;
import com.Department;
import com.opensymphony.xwork2.ActionSupport;
import service.DepartmentService;
import net.sf.json.JSONObject;
public class QueryAction extends ActionSupport {
private String name;
DepartmentService ds;
long did;
String dname;
String mid;
char rep;
private String result;
public String execute() {
if(name != null && !"".equals(name)) {
Long lname = Long.valueOf(name.trim());
Department ppp = ds.findById(lname);
if(ppp==null) {
return "sss";
}
//did = ppp.getDepartmentId();
//dname = ppp.getDepartmentName();
//mid = ppp.getManagerId();
//rep = ppp.getRepeal();
JSONObject json=JSONObject.fromObject(ppp); //I run debug it fail on here !
result=json.toString();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + result);
} //return "result";
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DepartmentService getDs() {
return ds;
}
public void setDs(DepartmentService ds) {
this.ds = ds;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public char getRep() {
return rep;
}
public void setRep(char rep) {
this.rep = rep;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}

Is a custom JSF converter needed for this simple class?

I have been trying with limited success to code a JSF application. In one section of the application, I need users to select from a select menu which displays a list of selectable status values. The Status class (presented below), which is used to populate the List that is displayed in the select menu, is a simple class made up of two Strings: one is the code used to look up the description in the database, the other is the human-readable description. I am trying to find out if I need a converter here at all, and if so, how best to implement the converter. This is a JSF 1.1 project using Java 1.5
I am using the following code in the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<h:graphicImage id="image" url="/images/appname.jpg"
alt="app name" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<jsp:include page="/jsp/menu.jsp" />
</head>
<body>
<h:outputText
value="Add Value"
style="font-size:20px;" />
<h:messages errorStyle="color: red" infoStyle="color: green"
layout="table" />
<h:form id="statusReasonEditForm">
<table>
<tr>
<td><h:outputText id="txtvalue" value="Status" /></td>
<td><h:selectOneMenu id="selectStatus"
value="#{pc_statusReasonBacker.status}"
binding="#{pc_statusReasonBacker.selectItem}">
<f:selectItems value="#{pc_statusReasonBacker.selectStatuses}" />
<f:converter converterId="statusConverter" />
</h:selectOneMenu>
<td><h:outputText id="txtvaluereason" value="Status Reason" /></td>
<td><h:inputText id="txtinputreason"
value="#{pc_statusReasonBacker.statusReason.statusReason}"
maxlength="100" size="40" /></td>
<td><h:outputText id="txtvaluereasondesc"
value="Status Reason Desc" /></td>
<td><h:inputText id="txtinputreasondesc"
value="#{pc_statusReasonBacker.statusReason.statusReasonDesc}"
maxlength="100" size="40" /></td>
</tr>
</table>
<tr>
<td><h:commandButton id="savebutton" value="Save"
action="#{pc_statusReasonBacker.save}" /></td>
<td><h:commandButton id="cancelbutton" value="Cancel"
action="#{pc_statusReasonBacker.cancel}" /></td>
</tr>
</h:form>
<hr />
</body>
</html>
</f:view>
The backing bean is shown here (some non-related sections, such as paging, removed for clarity):
public class StatusReasonBacker {
private List<StatusReason> statusReasonList;
private List<Status> statusList;
private List<SelectItem> selectStatuses;
private StatusReason statusReason;
private StatusDao sDao;
private Status status;
private UIData statusReasonTable;
private HtmlSelectOneMenu selectItem;
private String selectedStatus = "";
public StatusReasonBacker() {
sDao = new StatusDao();
statusReason = new StatusReason();
selectStatuses = new ArrayList<SelectItem>();
status = new Status();
selectItem = new HtmlSelectOneMenu();
}
public String insert() {
status.setStatusCde("");
statusReason.setStatus(status);
statusReason.setStatusReason("");
statusReason.setStatusReasonCde("");
statusReason.setStatusReasonDesc("");
return "success";
}
public String edit() {
this.statusReason = (StatusReason) statusReasonTable.getRowData();
selectItem.setValue(statusReason.getStatus().getStatusCde());
return "success";
}
public String update() {
if ("".equalsIgnoreCase(statusReason.getStatusReason().trim())) {
Message
.addErrorMessage("You must enter a value for the status reason.");
return "failure";
} else if (("".equalsIgnoreCase(statusReason.getStatusReasonDesc()
.trim()))) {
Message
.addErrorMessage("You must enter a value for the status reason description.");
return "failure";
}
sDao.updateStatusReason(statusReason);
return "statusreasons";
}
public String delete() {
StatusReason statReason = (StatusReason) statusReasonTable.getRowData();
sDao.deleteStatusReason(statReason);
return "statusreasons";
}
public String cancel() {
return "statusreasons";
}
public String save() {
statusReason.setStatus(status);
sDao.insertStatusReason(statusReason);
return "statusreasons";
}
...
public StatusDao getSDao() {
return sDao;
}
public void setSDao(StatusDao dao) {
sDao = dao;
}
public List<StatusReason> getStatusReasonList() {
statusReasonList = sDao.getStatusReasons();
return statusReasonList;
}
public void setStatusReasonList(List<StatusReason> statusReasonList) {
this.statusReasonList = statusReasonList;
}
public UIData getStatusReasonTable() {
return statusReasonTable;
}
public void setStatusReasonTable(UIData statusReasonTable) {
this.statusReasonTable = statusReasonTable;
}
public StatusReason getStatusReason() {
return statusReason;
}
public void setStatusReason(StatusReason statusReason) {
this.statusReason = statusReason;
}
public List<Status> getStatusList() {
statusList = sDao.getStatuses();
return statusList;
}
public void setStatusList(List<Status> statusList) {
this.statusList = statusList;
}
public List<SelectItem> getSelectStatuses() {
selectStatuses.clear();
if (statusList == null) {
statusList = this.getStatusList();
}
for (Status sr : statusList) {
SelectItem si = new SelectItem();
si.setValue(sr.getStatusCde());
si.setLabel(sr.toString());
si.setDescription(sr.toString());
selectStatuses.add(si);
}
return selectStatuses;
}
public void setSelectStatuses(List<SelectItem> selectStatuses) {
this.selectStatuses = selectStatuses;
}
public String getSelectedStatus() {
selectedStatus = statusReason.getStatusDesc();
return selectedStatus;
}
public void setSelectedStatus(String selectedStatus) {
this.selectedStatus = selectedStatus;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public HtmlSelectOneMenu getSelectItem() {
return selectItem;
}
public void setSelectItem(HtmlSelectOneMenu selectItem) {
this.selectItem = selectItem;
}
}
Thanks!
I am trying to find out if I need a converter here at all, and if so, how best to implement the converter.
You need a converter whenever you want to pass non-standard Java Objects from a HTTP request to another HTTP request. With non-standard I mean not a String, Number or Boolean. This all simply because HTTP request parameters can only be Strings. That Number and Boolean works is because EL can recognize them and has built-in coercions for it.
For non-standard Java Objects you need to implement a javax.faces.convert.Converter which converts the Object to a String (or a Number so you want, for example a Long id which can be the PK of the associated row in database table) inside the getAsString() method before displaying in HTML. You do the other way round in the getAsObject() method during processing of the request parameters (e.g. get the associated object from DAO by its id).
You can find here an example of how to use a Converter for a h:selectOneMenu. You see that this article also contains an alternative, but you'll need to do a bit more work in the backing bean to convert (map) the objects yourself.

Categories

Resources