HttpSession Java EE - java-ee-7

Everyone!
So I have a little problem with httpsession and I don't know how to fixed it. here is the problem.
I have a Class Person which has aset<Product> and I set that class person into
the request.getSession like this.
String email = getRequest().getParameter("email");
String credential = getRequest().getParameter("credential");
validEmail(email);
validCredential(credential);
if(existError()){
setValues(email, credential);;
forward(login);
return;
}
PersonService ps = serviceFactory.getService(PersonService.class);
boolean success = ps.validatePasswordAndEmail(email, credential);
if(success){
Person person = ps.getPersonByEmail(email);
getSession().setAttribute("person", person); here you can see the object person into the session
forward("/packed.jsp");
}else{
addError("Email or Credential is not valid!");
setValues(email, credential);
forward(login);
return;
}
After that if the users put their correct information they will come to another
file called packed.jsp and they are logged.
My problem is when I edit a product's person who are logged into the system. let me show my code here
The page called packed.jsp has a buttom where the person who are logged click
and then he comes to this servlet below
public class EditProductAction extends Action {
private String editProduct = "/edit_product.jsp";
private String packed = "/packed.jsp";
#Override
public void process() throws Exception {
Integer id = Integer.parseInt(getRequest().getParameter("id"));
String brand = getRequest().getParameter("brand");
String model = getRequest().getParameter("model");
String name = getRequest().getParameter("name");
String quantity = getRequest().getParameter("quantity");
String color = getRequest().getParameter("color");
String info = getRequest().getParameter("info");
ProductService ps = serviceFactory.getService(ProductService.class);
Product product = ps.getProductByID(id);
if(name == null){
getRequest().setAttribute("product",product);
forward(editProduct);
return;
}
product.setBrand(brand);
product.setModel(model);
product.setName(name);
product.setQuantity(Integer.parseInt(quantity));
product.setColor(color);
product.setInfo(info);
ps.update(product);
getResponse().sendRedirect(getRequest().getContextPath()+packed);
}
}
As you can see everything works fine but when I come back to the page packed.jsp
it doesn't show the product modyfied but in the database works fine, I mean the product has been modyfied. here packed.jsp
<div class="mainDiv">
<table border="1px" width="80%">
<tr>
<th>BRAND</th>
<th>MODEL</th>
<th>NAME</th>
<th>QUANTITY</th>
<th>COLOR</th>
<th>INFO</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<c:choose>
<c:when test="${empty person.products}">
<tr>
<td colspan="8" align="center"><span>You don't have any product yet!</span></td>
</tr>
</c:when>
<c:otherwise>
<c:forEach var="p" items="${person.products}">
<c:url var="urlDel" value="servlet">
<c:param name="id" value="${p.id}" />
</c:url>
<c:url var="urlEdit" value="EditProduct.action">
<c:param name="id" value="${p.id}" />
</c:url>
<tr>
<td>${p.brand}</td>
<td>${p.model}</td>
<td>${p.name}</td>
<td>${p.quantity}</td>
<td>${p.color}</td>
<td>${p.info}</td>
<td><img src="<%=request.getContextPath()%>/images/edit.png"></td>
<td><img src="<%=request.getContextPath()%>/images/delete.png"></td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
I would like to change the product and then when I back to packed.jsp I want to see the product modyfied. Thank you very much everyone.

I found a solution by creating another class with those objects and then put it the session. It works.

Related

Riot API With Angular 2

I trying to use the Riot API for Champions in this code
--Service
#Injectable()
export class ChampionService {
private riotUrl = 'https://br1.api.riotgames.com/lol/static-
data/v3/champions?api_key=myApiKey';
constructor(private _http: Http) { }
getChampion(): Observable<Champion[]> {
return this._http.get(this.riotUrl)
.map((res:Response) => <Champion[]>[res.json()])
.do(data => console.log(JSON.stringify(data)));
}}
-- Component
export class ChampionListComponent{
errorMessage: string;
champions: Champion[];
constructor(private _ChampionService: ChampionService){}
ngOnInit():void{
this._ChampionService.getChampion()
.subscribe(champions => this.champions = champions,
error => this.errorMessage = <any>error);}
--HTML
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let champion of champions'>
<td>{{champion.id}}</td>
<td>{{champion.name}}</td>
</tr>
</tbody>
</table>
In the console that's appears correctly.. but nothing happen with my table
--- My Console Show This
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
champion-list.service.ts:18 [{"type":"champion","version":"7.8.1","data":{"Jax":{"id":24,"key":"Jax","name":"Jax","title":"o Grão-Mestre das Armas"},"Sona":{"id":37,"key":"Sona","name":"Sona","title":"a Mestra das Cordas"},"Tristana":{"id":18,"key":"Tristana","name":"Tristana","title":"a Artilheira Yordle"},"Varus":{"id":110,"key":"Varus","name":"Varus","title":"a Flecha da Vingança"},"Fiora":{"id":114,"key":"Fiora","name":"Fiora","title":"a Grande Duelista"},"Singed":{"id":27,"key":"Singed","name":"Singed","title":"o Químico Louco"},"TahmKench":{"id":223,"key":"TahmKench","name":"Tahm Kench","title":"o Rei do Rio"},"Leblanc":{"id":7,"key":"Leblanc","name":"LeBlanc","title":"a Farsante"},"Thresh":{"id":412,"key":"Thresh","name":"Thresh","title":"o Guardião das Correntes"},"Karma":{"id":43,"key":"Karma","name":"Karma","title":"a Iluminada"},"Jhin":{"id":202,"key":"Jhin","name":"Jhin","title":"o Virtuoso"},"Rumble":{"id":68,"key":"Rumble","name":"Rumble","title":"a Ameaça Mecânica"},"Udyr":{"id":77,"key":"Udyr","name":"Udyr","title":"o Andarilho Espiritual"},"LeeSin":{"id":64,"key":"LeeSin","name":"Lee Sin","title":"o Monge Cego"},"Yorick":{"id":83,"key":"Yorick","name":"Yorick","title":"Pastor de Almas"},"Kassadin":{"id":38,"key":"Kassadin","name":"Kassadin","title":"o Andarilho do Vazio"},"Sivir":{"id":15,"key":"Sivir","name":"Sivir","title":"a Mestra da Batalha"},"MissFortune":{"id":21,"key":"MissFortune","name":"Miss Fortune","title":"a Caçadora de Recompensas"}...
someone can help me ? Sorry for the long post
Even though you are setting your response in an array:
.map((res:Response) => <Champion[]>[res.json()])
This still means that your array just contains one object, that contains objects (which you want to iterate). So first let's remove the assignment to an array, and instead step into the JSON and extract the object that contains your objects that you want:
.map((res:Response) => res.json().data)
This means you end up with an object with your objects. Since object cannot be iterated, we need to use a pipe:
#Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args?: any[]): any[] {
// create instance vars to store keys and final output
let keyArr: any[] = Object.keys(value),
dataArr = [];
// loop through the object,
// pushing values to the return array
keyArr.forEach((key: any) => {
dataArr.push(value[key]);
});
// return the resulting array
return dataArr;
}
}
Then apply that pipe in your template:
<tr *ngFor='let champion of champions | keys'>
<td>{{champion.id}}</td>
<td>{{champion.name}}</td>
</tr>
That should do the trick! :)
As a sidenote, this means your response is not an Array of Champion, so assigning it <Champion[]> is inaccurate. However your interface is built, you need to make the appropriate changes.
Demo

How to get element with specific value in htmlagilitypack

I have ASP.NET MVC4 project where try to parse html document with HtmlAgilityPack. I have the following HTML:
<td class="pl22">
<p class='pb10 pt10 t_grey'>Experience:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='t_grey pb10 pt10'>Education:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='pb10 pt10 t_grey'>Schedule:</p>
<p class='bold'>part-time</p>
<p class='text_12'>2/2 (day/night)</p>
</td>
I need to get values:
"any" after "Experience:"
"any" after "Education:"
"part-time", "2/2 (day/night)" after "Schedule:"
All what I imagine is that
HtmlNode experience = hd.DocumentNode.SelectSingleNode("//td[#class='pl22']//p[#class='bold']");
But it get me different element, which place in the top of the page. My Experience, Education and Schedule is static values. In additional my any, any part-time day/night is the dynamic values. Can anybody help me?
Below is an alternative which is more focused on the table headers (Experience, Education and Schedule), instead of the node classes:
private static List<string> GetValues(HtmlDocument doc, string header) {
return doc.DocumentNode.SelectNodes(string.Format("//p[contains(text(), '{0}')]/following-sibling::p", header)).Select(x => x.InnerText).ToList();
}
You can call that method like this:
var experiences = GetValues(doc, "Experience");
var educations = GetValues(doc, "Education");
var schedules = GetValues(doc, "Schedule");
experiences.ForEach(Console.WriteLine);
educations.ForEach(Console.WriteLine);
schedules.ForEach(Console.WriteLine);
You could do it something like this if you want to keep the XPath
var html = "<td class='pl22'><p class='pb10 pt10 t_grey'>Experience:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='t_grey pb10 pt10'>Education:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='pb10 pt10 t_grey'>Schedule:</p><p class='bold'>part-time</p><p class='text_12'>2/2 (day/night)</p></td> ";
var doc = new HtmlDocument
{
OptionDefaultStreamEncoding = Encoding.UTF8
};
doc.LoadHtml(html);
var part1 = doc.DocumentNode.SelectSingleNode("//td[#class='pl22']/p[#class='bold']");
var part2 = doc.DocumentNode.SelectNodes("//td[#class='pb10 pl20']/p[#class='bold']");
foreach (var item in part2)
{
Console.WriteLine(item.InnerText);
}
var part3 = doc.DocumentNode.SelectSingleNode("//td[#class='pb10 pl20']/p[#class='text_12']");
Console.WriteLine(part1.InnerText);
Console.WriteLine(part3.InnerText);
Output :
any
part-time
any
2/2 (day/night)

grid.selection.getSelected().length on selecting one row

I have created a dojox.grid.DataGrid and i want to perform some operations on the rows selected by the user, so, i have placed an alert to get the no. of rows selected by the user.
I am using :
var noofrows=grid.selection.getSelected().length;
alert(noofrows);
to get the number of rows selected by the user in the grid.
When the user selects one row the above statement alerts 0 but it should pop-up 1 as 1 row is selected by user.
When user selects multiple rows it pop-ups the correct number of rows selected by the user.
After selecting multiple rows(right result is getting poped-up) when user selects one row it pop-ups the correct output i.e.: 1.
So, basically the issue is when user selects one row for the first time it pop-ups the wrong output(i.e :0).
Here is the grid creation code :
<table id="AA.FavouritesGrid" dojoType="dojox.grid.DataGrid"
region="center"
jsId="table"
id="table"
store="AAFavouritesStore" style="font-size:30px;width:100%;padding:0px;display:0px;">
<thead>
<tr>
<%
String userCode ="";
userCode = request.getUserPrincipal().getName();
try {
Map<String,String> columnNameLabelMap=model.getDynamicNameLabelmap("Favourites", userCode, locale);
// Loop round columns ordered by user
for (Map.Entry<String, String> entry : columnNameLabelMap.entrySet()){
int width = columnDataById.get(entry.getKey()).getWidth();
columnDataById.remove(entry.getKey());
%>
<th field=<%=entry.getKey() %> width="<%=width%>" height="22px" nowrap="nowrap"><%=entry.getValue()%></th>
<%
}
} catch (Exception e) {
System.out.println(e);
}
// Present any left over columns in default order
for (ColumnData entry : columnDataById.values()){
%>
<th field=<%=entry.getId() %> width="<%=entry.getWidth()%>" height="22px" nowrap="nowrap"><%=entry.getName()%></th>
<%
}
%>
<th field="path" hidden="true"></th>
<th field="underwritingYear" hidden="true" ></th>
<th field="lpRCTLobDesc" hidden="true" ></th>
<th field="lpRCTLob" hidden="true" ></th>
</tr>
</thead>
</table>
favContextMenu = dojo.connect(dijit.byId("AA.FavouritesGrid"),"onCellContextMenu", favouritesGridOnContextMenu );
function favouritesGridOnContextMenu(e) {
alert(table.selection.getSelected().length);
}
Please help to resolve the problem
Thanks
Try below 2 ways to get selected item and items.
var e = dijit.byId("addressMapStoreGrid");
if (e.focus.rowIndex < 0) {
alert('Please select one row!');
return;
}
-
var items = grid.selection.getSelected();

How to Update All Rows of Table SQL

Below is my code:
#{
Layout = "/_SiteLayout.cshtml";
var db = Database.Open("MyDatabase");
var query = "SELECT * FROM Team";
var Teams = db.Query(query);
}
<form>
<table>
<tr>
<td>Team Name</td>
<td>Played</td>
<td>Points</td>
</tr>
#{ foreach(var Team in Teams){
<tr>
<td>#Team.TeamName</td>
<td><input type="text" value="#Team.Played" name="Played"/></td>
<td><input type="text" value="#Team.Points" name="Points"/></td>
</tr>
}
}
</table>
</form>
This is the result:
So what I want to do is update my whole table.
What is the SQL query to do this? I want to update Points and Games Played in my database for all teams once the form is posted.
I don't actually understand what exactly you are trying to achieve (update your whole table with what?), but here is some information you might find useful:
SQL Update Tutorial, SQL Update, Update from Select
Following is My Solution. Anyone have an efficient Solution?
#{
var db = Database.Open("MYDATABSE");
var query = "SELECT * FROM Team";
var Teams = db.Query(query);
var InsertQuery = "";
if(IsPost){
foreach(var Team in Teams){
var Points = Request[Team.TeamName];
var TeamId = Team.TeamId.ToString();
var Played = Request[TeamId];
var executeQueryString="UPDATE Team Set Points=#0, Played=#1 WHERE TeamId=#2";
db.Execute(executeQueryString, Points, Played, Team.TeamId);
}
Response.Redirect("~/UpdateTable.cshtml");
}
}
<br /><br />
<form action="" method="post">
<table>
<tr>
<td><h5>Team Name</h5></td>
<td><h5>Played</h5></td>
<td><h5>Points</h5></td>
</tr>
#{ foreach(var Team in Teams){
<tr>
<td>#Team.TeamName</td>
<td><input type="text" value="#Team.Played" name="#Team.TeamId"/></td>
<td><input type="text" value="#Team.Points" name="#Team.TeamName"/></td>
</tr>
}
}

how to get the class name through selenium

<table >
<tr class="odd First"><td>1one Cell</td><td>2one Cell</td><td>3one Cell</td><td>4one Cell</td> </tr>
<tr class="even Second"><td>Two Cell</td><td>2Two Cell</td><td>3Two Cell</td><td>4Two Cell</td></tr>
<tr class="odd Thrid"><td>1Three Cell</td><td>2Three Cell</td><td>3Three Cell</td><td>4Three Cell</td></tr>
<tr class="even Fourth"><td>1Five Cell</td><td>2Five Cell</td><td>3Five Cell</td><td>4Five Cell</td></tr>
</table>
How can i get the class names of the tr. Please suggest me.
To get the class names of all the tags using java.
List<WebElement> list = driver.findElements(By.tagName("tr"));
for(WebElement ele:list){
String className = ele.getAttribute("class");
System.out.println("Class name = "+className);
}
This will print all the class names to the console for all the tags on the web page.
String className = selenium.getAttribute("//html/body/table/tbody/tr[1]/#class");
May be this code might get you the value of the first tag's class name. Let me know if this works.
List0 = []
List1 = driver.find_elements(By.XPATH, '/table/tr')
for element in List1:
name = element.get_attribute('class')
List0.append(name)
print(List0)