`I am a new to java and to servlet topic.
I write a little web application. it's collect some data from web-form and add it into a LinkedList.
But my debugger shown me that adding to LL doesnt occur. HELP PLEASE!
Here some code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String fatherName = request.getParameter("fathername");
String department = request.getParameter("department").toLowerCase();
Integer age = Integer.valueOf(request.getParameter("age"));
System.out.println(name);
System.out.println(surname);
System.out.println(fatherName);
responseToUser(addEmployee(name,surname,fatherName,department, age),response);
}
public boolean addEmployee(String name, String surname, String fathername, String department, Integer age) {
AllWorkers workers = new AllWorkers();
if (!name.equals("") && !surname.equals("") && !fathername.equals("") && !dep artment.equals("") && age != null) {
Person person = new Person(surname, name, fathername, department, age);
Departments dep = Departments.valueOf(person.getDepartment());
if (dep == Departments.логистика) {
workers.addLogistic(person);
} else if (dep == Departments.продажи) {
workers.addSales(person);
}
return true;
} else {
return false;
}
}
public void responseToUser(boolean boo, HttpServletResponse response) throws IOException {
Gson gson = new Gson();
response.setContentType("application/json");
if(boo == true){
response.getWriter().write(gson.toJson(true));
}else if(boo == false){
response.getWriter().write(gson.toJson(false));
}
}
Departments:
public enum Departments {
логистика,продажи
}
AllWorkers.java
public class AllWorkers {
LinkedList<Person> logistic = new LinkedList<Person>();
LinkedList<Person> sales = new LinkedList<Person>();
public void addLogistic(Person person){
logistic.add(person);
}
public void addSales(Person person){sales.add(person);}
public LinkedList<Person> getLogistic() {
return logistic;
}
public LinkedList<Person> getSales() {
return sales;
}
}
Person.java
public class Person {
private String name;
private String surname;
private String fatherName;
private String department;
private int age;
Person(){
}
Person(String name, String surname, String fatherName,String department, int age){
this.name = name;
this.surname = surname;
this.fatherName = fatherName;
this.department = department;
this.age = age;
}
public String getDepartment() {
return department;
}
public String getFatherName() {
return fatherName;
}
public int getAge() {
return age;
}
public String getSurname() {
return surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setDepartment(String department) {
this.department = department;
}
}
(I assume you have checked your variables name, surname, fatherName, department and age have correct values)
I have tested your code and persons are added to LinkedLists contained in AllWorkers correctly. However, in method addEmploye() you do this:
AllWorkers workers = new AllWorkers();
which means you create a new workers every time you comsume the servlet, and each time that workers will be empty since it's a new object. Maybe that is the reason it seems that persons are not added to lists.
Regards,
Related
I'm new to java reflexion and I'm trying to integrate SQLite with java.
I have 2 objects Person and Department. There is relation OneToMany between them.
As I'm working on save functionality (SQLite) I want to extract field names and its values so I can build full query. I have no problem with extracting names and values of fields that are of primitive type (String, int etc.). I have problem with type of Object (in this case it is Department field in Person object).
I'm able to print object but unable to access its fields (namely pk).
Could you help me please?
METHOD FOR EXTRACTING FIELDS
// method for extracting fields
private StringBuilder getFieldsWithValues(Object entity) throws IllegalAccessException, NoSuchFieldException {
StringBuilder query = new StringBuilder();
for (Field field : entity.getClass().getDeclaredFields()) {
System.out.print((field.getName() + " - "));
field.setAccessible(true);
// TODO: eliminate if statement from for cycle
if (field.isAnnotationPresent(ManyToOne.class)) {
// HERE I want to extract the pk value from Department object
System.out.println(field.get(entity));
} else {
System.out.println(field.get(entity));
}
}
return query;
}
DEPARTMENT OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Department {
#Id
private long pk;
private String name;
private String code;
public Department() {
}
public Department(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String toString() {
return String.format("Department %d: %s (%s)", pk, name, code);
}
}
PERSON OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Person {
#Id
private long id;
private String surname;
private String name;
private int age;
#ManyToOne
private Department department;
public Person(String surname, String name, int age) {
this.surname = surname;
this.name = name;
this.age = age;
}
public Person() {
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getId() {
return id;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return String.format("Person %d: %s %s (%d)", id, surname, name, age);
}
}
Create a class that represents an employee. This class will have three constructors to initialize variables. If the constructor doesn't provide a parameter for a field, make it either "(not set)" or "0" as appropriate.
Name:
Employee
Fields:
name : String
idNumber : int
department : String
position : String
Methods:
Employee()
Employee(name : String, idNumber : int)
Employee(name : String, idNumber : int, department : String, position : String)
getName() : String
getDepartment() : String
getPosition() : String
getIdNumber() : int
My issue is that I don't know if the Employee() field is a void
Also not sure why public class Employee is included in the comment rather than the code.
public class Employee {
private String name;
private int idNumber;
private string department;
private string position;
/* public void setEmployee (String n)
{
name = n;
if (n == null)
{
n = "(not set)";
}
}
public void Employee (string n, int id)
{
name = n;
idNumber =id;
}
public void Employee (string n, int id, string d, string p)
{
name = n;
idNumber = id;
department = d;
position = p;
} */
public String getName ()
{
return name;
}
public string getDepartment ()
{
return department;
}
public string getPosition ()
{
return position;
}
public int getIdNumber ()
{
return idNumber;
}
}
Also having an issue with this second part
Not sure where to go from here
import java.util.Scanner;
public class EmployeeDem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String option;
do {
System.out.println("-- Employee ID Menu --\n Enter 'exit' to quit");
option = keyboard.nextLine();
System.out.println("What is your name?");
String name = keyboard.nextLine();
System.out.println("What is your ID number?");
int idNumber = keyboard.nextInt();
System.out.println("What is your department?");
String department = keyboard.nextLine();
System.out.println("What is your position?");
String position = keyboard.nextLine();
} while (option != "exit");
//class obj instance
Employee myEmployee = new Employee();
myEmployee.
}
}
You can initialize the variables first when creating the class, if you don't change them using setters or constructors they will have the initial value that you setted. I initialized them with "(not set)" and 0
public class Employee {
private String name = "(not set)";
private int idNumber = 0;
private String department = "(not set)";
private String position = "(not set)";
public Employee() {}
public Employee(String name, int idNumber) {
this.name = name;
this.idNumber = idNumber;
}
public Employee(String name, int idNumber, String position) {
this.name = name;
this.idNumber = idNumber;
this.position = position;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
Hope this is what you want :)
In an ArrayList I have two different objects,
Student and Employee. I want to iterate through them one by one. I am able to iterate through the list and use the Employee objects but not the Student objects.
I have the following code:
package javaCollections;
import java.util.ArrayList;
import java.util.Iterator;
class Employee {
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class Student {
#Override
public String toString() {
return "student [stud_name=" + stud_name + ", rollNumber=" + rollNumber
+ "]";
}
String stud_name;
int rollNumber;
public Student(String stud_name, int rollNumber) {
super();
this.stud_name = stud_name;
this.rollNumber = rollNumber;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
}
public class Arraylist {
ArrayList<Object> emparray;
public void addemp() {
Employee emp = new Employee("abc", 12);
emparray = new ArrayList<Object>();
emparray.add(emp);
Employee emp1 = new Employee("def", 12);
emparray.add(emp1);
Student std = new Student("efg", 123);
Student std1 = new Student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
/*
* Iterator<Object> itr=emparray.iterator();
*
* while(itr.hasNext()) { System.out.println(itr.next()); }
*/
for (Object e : emparray) {
System.out.println(((Employee) e).getAge());
System.out.println(((Employee) e).getName());
}
}
public static void main(String[] args) {
Arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
can someone please help me on this?
What you need to do is check the instance of the object.
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
// do something else
}
}
}
IMO this is a bad design.
The best practice is to create common base called Person that has shared fields like name. Then you can replace Object with Person in the loop.
import java.util.ArrayList;
import java.util.Iterator;
interface Person{
public String getName();
public void setName(String name);
}
class employee implements Person{
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class student implements Person{
#Override
public String toString() {
return "student [stud_name=" + name + ", rollNumber=" + rollNumber
+ "]";
}
String name;
int rollNumber;
public student(String stud_name, int rollNumber) {
super();
this.name = stud_name;
this.rollNumber = rollNumber;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name=name;
}
}
public class arraylist {
ArrayList<Person> emparray;
public void addemp() {
employee emp = new employee("abc", 12);
emparray = new ArrayList<Person>();
emparray.add(emp);
employee emp1 = new employee("def", 12);
emparray.add(emp1);
student std = new student("efg", 123);
student std1 = new student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
for (Person e : emparray) {
if (e instanceof employee) {
System.out.println(((employee) e).getAge());
}else{
/// do for student
}
System.out.println(e.getName());
}
}
public static void main(String[] args) {
arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
System.out.println(((student) e).getRollNumber());
System.out.println(((student) e).getStud_name());
}
}
}
Can someone help me i have those classes, and i want read out the getAllCustomer(), but i have no idea how i can implent it in my main method.
I tried already several things, but it didn't work well. Can anyone help me? :P
public static ArrayList<Customer> getAllCustomer() throws ClassNotFoundException, SQLException {
Connection conn=DBConnection.getDBConnection().getConnection();
Statement stm;
stm = conn.createStatement();
String sql = "Select * From Customer";
ResultSet rst;
rst = stm.executeQuery(sql);
ArrayList<Customer> customerList = new ArrayList<>();
while (rst.next()) {
Customer customer = new Customer(rst.getString("id"), rst.getString("name"), rst.getString("address"), rst.getDouble("salary"));
customerList.add(customer);
}
return customerList;
}
this is my model class
public class Customer {
private String id;
private String name;
private String salary;
private String address;
public Customer (String pId, String pName, String pSalary, String pAddress) {
id = pId;
name = pName;
salary = pSalary;
adress = pAddress;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Assuming that your getAllCustomer() method is in class A . then in your main method, you do as follows
public void main(String[] args){
List<Customer> customers = A.getAllCustomer();
}
Based on the nature of your question, this JDBC tutorial will help you
The data type of your Salary field is String but you are getting the value as double.
All you need to do is to change the rst.getDouble("salary") to rst.getString("salary")
To call the method:
public static void main(String[] args)
ArrayList<Customer> customers = YourDALClass.getAllCustomer();
for(Customer c : customers){
System.out.println(c.getName());
}
}
Say I have a Yaml file like this,
people:
- name : Joe
surname : Barber
age : 16
- name : Andy
surname : Lots
age : 17
And I have a class like this,
public class people {
private String name;
private String surname;
private String age;
<!-- With getters and setters -->
}
How would i go about getting a list of people objects from the Yaml file?
Just getting the value from a key in the file is fairly simple but mapping it to a collection of objects is not.
I am using the snakeYaml lib.
i hope this can help you.
public class StackOverflow {
public static void main(String[] args) {
final URL resource = StackOverflow.class.getResource("people.yaml");
final Constructor peopleContructor = new Constructor(Group.class);
final TypeDescription peopleDescription = new TypeDescription(People.class);
peopleDescription.putMapPropertyType("people", People.class, Object.class);
peopleContructor.addTypeDescription(peopleDescription);
final Yaml yaml = new Yaml(peopleContructor);
try {
final Group group = (Group) yaml.load(resource.openStream());
for (final People people : group.getPeople()) {
System.out.println(people);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static class People {
private String name;
private String surname;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "People: {name: " + this.name + ", surname: " + this.surname + ", age: " + this.age + "}";
}
}
public static class Group {
private List<People> people;
public List<People> getPeople() {
return people;
}
public void setPeople(List<People> people) {
this.people = people;
}
}}