Registration page in string, handle data from the JSON and response something? - json

My task is to create user account in Spring. This is an excerpt from index.jsp.
Submitting to /register sends Name, Surname, Login and Email using POST. My task is to receive this data and send it to the database. When data is registered in database I must return status code: "1" for success or "0" if no users were added.
When I execute /register I have information that "Required param GET". What is the problem?
<div id="register">
<div class="top-bar">
<header class="page-title">Zarządzanie projektami studenckimi</header>
</div>
<header class="section-title">Rejestracja</header>
<table cellspacing="0" cellpadding="0">
<tr> <td colspan="2" class="info" /> </tr>
<tr>
<td class="param">Imię:</td>
<td class="value">
<input type="text" id="register-firstname" />
</td>
</tr>
<tr>
<td class="param">Nazwisko:</td>
<td class="value">
<input type="text" id="register-surname" />
</td>
</tr>
<tr>
<td class="param">Adres email:</td>
<td class="value">
<input type="text" id="register-email" />
</td>
</tr>
<tr>
<td class="param">Nazwa użytkownika:</td>
<td class="value">
<input type="text" id="register-user" />
</td>
</tr>
<tr>
<td style="text-align: left;" />
<td style="text-align: right;">
<input type="button" id="register-button" value="Zarejestruj" />
</td>
</tr>
</table>
</div>
And this is my code from the logincontroller.java in Spring:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public #ResponseBody Integer addProwadzacy(
#RequestParam(value = "firstname", required = true) String imie,
#RequestParam(value = "surname", required = true) String nazwisko,
#RequestParam(value = "email", required = true) String mail,
#RequestParam(value = "user", required = true) String login,
Model model) {
Date data = new Date();
String haslo = null;
// RandomPassword.
Prowadzacy prowadzacy = new Prowadzacy();
prowadzacy.setImiona(imie);
prowadzacy.setNazwisko(nazwisko);
prowadzacy.setEmail(mail);
prowadzacy.setLogin(login);
prowadzacy.setDataDodania(data);
prowadzacy.setWaznosc(true);
prowadzacy.setAktywowany(false);
prowadzacy.setHaslo(Encryption.encrypt(haslo));
loginService.addProwadzacy(prowadzacy);
List<Prowadzacy> registerlist = loginService.validateRegister(imie,
nazwisko, mail, login);
if (registerlist.size() > 0) {
return 1;
} else {
return 0;
}
}

Related

Angular : Not Able to Auto populate radio button field Based on other date fields

There are two date fields plannedRatingDate and PlannedRatingCommitteeDate on my UI.
If the user fills in plannedRatingDate field,rcReview field should be set to 'No'.
If the user fills in plannedRatingCommitteeDate field,rcReview field should be set to 'Yes'.
rcReview field is a radio button field on my UI.
In app.component.html:
<tr>
<td colspan="2"></td>
<td style="width:500px">
<label for="PlannedReviewDate">Planned Review Date</label>
<input id="PlannedReviewDate" name="PlannedReviewDate" (change)="basedOnRatingDate($event)" [(ngModel)]="deal.plannedReviewDate" placement="right" type="text" bsDatepicker [bsConfig]="datePickerConfig" class="form-control">
</td>
</tr>
<br>
<tr>
<td colspan="3"></td>
<td><label for="isReviewComplete">Is Review Complete?</label>
<input id="isReviewComplete" name="isReviewComplete" [(ngModel)]="deal.isReviewComplete" type="radio" class="form-control" value="Complete">
Complete<br></td>
</tr>
<tr>
<td colspan="3"></td>
<td><input id="isReviewComplete" name="isReviewComplete" [(ngModel)]="deal.isReviewComplete" type="radio" class="form-control" value="Not Complete">
Not Complete<br></td>
</tr>
<br>
<tr>
<td colspan="3"></td>
<td style="width:500px">
<label for="PlannedRatingCommitteeDate">Planned rating committee date</label>
<input id="PlannedRatingCommitteeDate" name="PlannedRatingCommitteeDate" (change)="populateRCReview($event)" [(ngModel)]="deal.plannedRatingCommitteeDate" placement="right" type="text" bsDatepicker [bsConfig]="datePickerConfig" class="form-control">
</td>
</tr>
<br>
<tr>
<td colspan="3"></td>
<td>
<label>RC Review</label>
<input id="rcReview" name="rcReview" [(ngModel)]="deal.rcReview" type="radio" class="form-control" value="Yes">
Yes<br>
</td>
</tr>
<tr>
<td colspan="3"></td>
<td>
<input id="rcReview" name="rcReview" [(ngModel)]="deal.rcReview" type="radio" class="form-control" value="No">
No<br>
</td>
</tr>
In app.component.ts:
export class AppComponent implements OnInit {
title = 'angular-app';
name = 'angular-app';
datePickerConfig: Partial<BsDatepickerConfig>;
dropdownList = [];
selectedItems: any;
selected:any;
dropdownSettings:IDropdownSettings;
dealid : number;
isReviewComplete: any;
plannedRatingCommitteeDate: Date;
plannedReviewDate: Date;
ExpectedReleaseDate: Date;
ReleaseTimeCriteria: any;
SubsequentRating: any;
Priority: any;
rcReview: any;
ApplicationReceived: any;
subsequentRating: any;
deal:DealApi= new DealApi();
constructor(private service:HttpclientService) {}
ngOnInit(){
this.datePickerConfig = Object.assign({},{ containerClass:'theme-dark-blue', showWeekNumbers: false});
};
public savenow(){
this.service.getdeals(this.deal).subscribe((data:any)=>{alert("Deal added successfully.");});
}
basedOnRatingDate(event:any){
this.deal.rcReview = "No";
}
populateRCReview(event:any){
this.deal.rcReview = "Yes";
}
Above code is not autopopulating rcReview field with 'No' if user enters plannedRatingDate field.
What changes should be done?
Any Help will be appreciated!
I resolved the issue by using ngModelChange event instead of change event.

updating Table from Form data input using Spring MVC+JDBC

I am having issue with updating records on a table using jdbcTemplate.
here is my jsp form
<form:form method="post" action="edit" modelAttribute="Student">
<table>
<tr>
<td>id:</td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation:</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
update method in StudentDaoImpl class is:
public void update(Student s) {
String sql = "UPDATE Student set name=?, salary=?, designation=? where id=?";
jdbcTemplate.update(sql,s.getId(),s.getName(),s.getSalary(),s.getDesignation());
System.out.println("-- Student list is Updated---" );
int status =jdbcTemplate.update(sql);
System.out.println("-------status---"+status);
}
controller method for updating is:
#RequestMapping(value =("/edit"), method= RequestMethod.POST)
public ModelAndView editStudent(#ModelAttribute("Student") Student student,BindingResult result, ModelMap map){
#SuppressWarnings("resource")
ApplicationContext ac = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
StudentDAO dao = (StudentDAO) ac.getBean("studentDao");
// map.addAttribute("id", student.getId());
map.addAttribute("name", student.getName());
map.addAttribute("salary", student.getSalary());
map.addAttribute("designation", student.getDesignation());
dao.save(student);
return new ModelAndView("redirect:/viewstudent");
}
I want to update record by id on my student table...I get sql query error.
What I am doing wrong? please suggest.

Delete multiple records from MySql by using check box in JSP

I am trying to delete multiple row from MySql database using checkbox. Here is my code. I only can delete row by row without checkbox.
displayfood.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet_2.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="validation.js"> </script>
<title>All Food Menu</title>
</head>
<body>
<!--############# HEADER ############# -->
<table id="t1Body_food">
<tr><td colspan="5">
<table class="table_header" align="center" >
<tr> <td class="tbody-logo_food" align="right" valign="bottom">
<form name="myForm" action="searchFood.jsp" onsubmit="return searchvalidate()" method="post">
<input type="text" name="type" placeholder="Search">
<input name="search" type="submit" value="search">
<input type="button" value="Logout" onclick="logoutpage()"/>
</form></td></tr>
</table> </td> </tr>
<tr>
<td class="td1-header"id="rice" > Home </td>
<td class="td1-header"> Food </td>
<td class="td1-header"> Reservation </td>
<td class="td1-header"> About Us </td>
<td class="td1-header"> Contact us </td>
</tr>
</table>
<table id="t2Body" >
<tr><td colspan="5" id="rice"><hr color="orange" size="13"></td>
</tr>
<tr> <td class="td_2header" > Name</td>
<!-- <td class="td_2header" > Type</td>
<td class="td_2header" > Picture </td> -->
<td class="td_2header" > Description </td>
<td class="td_2header" > Price </td>
<td align="right" colspan="4"> <a target="_blank" href="addItem_Form.jsp">
<button name="AddItem" > +Add New Food Menu </button> </a>
</td>
</tr>
<tr><td colspan="5" id="rice"><hr color="orange" size="13"></td>
</tr>
<%
String id= request.getParameter("hiddenID");
try {
// Step1: Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL ="jdbc:mysql://localhost/restaurant?user=root& password=Password";
// Step 3: Establish connection to URL
Connection conn = DriverManager.getConnection(connURL);
// Step 4: Create Statement object
Statement stmt = conn.createStatement();
// Step 5: Execute SQL Command
PreparedStatement pstmt =conn.prepareStatement("Select * from food");
ResultSet rs=pstmt.executeQuery();
// out.println("<table id='t2Body' >");
while (rs.next())
{ id=rs.getString("ID");
String name=rs.getString("name");
String type=rs.getString("type");
String pic=rs.getString("picture");
int price=rs.getInt("price");
String desc=rs.getString("description");
// out.println("<tr> <td class=td_2border><div class=food_name>"+id+" </div>");
out.println(" <tr>s<td class=td_2border><div class=food_name>"+name+"</div>");
out.println(" <div><img src=\" " + pic+"\" "+"/></div>");
out.println("<div>"+type+"</div><br>");
out.println("<div><hr color=orange></div> ");
out.println("</td>");
out.println("<td class=td2_desc><br>"+ desc+"</td>");
out.println("<td class=td_2border><br> $"+price+"</td>");
%>
<td class=td_2border>
<br>
<form action="delete.jsp" method="get">
<input type="checkbox" name="hiddenID" value="<%=id%>">
<input type="hidden" name="hiddenID" value="<%=id%>">
<input type="submit" Value="Delete" name ="delete"/>
<%-- <input type="submit" value="<%=id %>" name="check" /> --%>
</form>
</td>
<td class=td_2border><br>
<form action="update_Form.jsp" method="get">
<input type="hidden" name="hiddenID" value="<%=id%>" />
<input type="submit" value="Update" name="updateBtn" />
</form>
</td>
</tr>
<%
}
%>
<tr>
<td colspan="5" align="right">
<form action="delete.jsp" method="get">
<%-- <input type="hidden" name="hiddenID" value="<%=id%>" > --%>
<input type="submit" name="submit" value="confirm" >
</form>
</td>
</tr>
</table>
<%
}
catch(Exception e ){
out.println(e);}
%>
</body>
</html>
delete.jsp:
<%#page import="java.sql.*"%>
<%
String [] id = request.getParameterValues("hiddenID");
// String id= request.getParameter("hiddenID");
if (id != null && id.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < id.length; i++) {
out.println(id[i]);
} //end for loop
}// end if
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/restaurant?user=root&password=Password";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
String sqlStr = "Delete from food WHERE id =?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
//pstmt.setArray(1,Integer.parseInt(id));
//pstmt.setInt(1,Integer.parseInt(id));
// for (int i = 0; i < id.length; i++)
//if (id !=null){
// for (int i = 0; i < id.length; i++){
// pstmt.setString(1, id[i]);
pstmt.setString(1, id[i]);
int rec=pstmt.executeUpdate();
conn.close();
if (rec>0){
%>
<script>
alert("record is deleted!");
window.location.reload("allFood2.jsp");
</script>
<%
} //end if
else{
%>
<script>
alert(" no record is deleted!");
window.location.reload("allFood2.jsp");
</script>
<%
} //end else
}//end try
catch (Exception e) {
out.println(e.getMessage());
}
%>
You can create a string parameter to hold CSV values for the ids and modify the query to use then as parameter.
String ids = "";
if (id != null && id.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < id.length; i++) {
ids += id[i] +",";
out.println(id[i]);
} //end for loop
}// end if
if (ids .endsWith(","))
ids = ids.substring(0, ids .length() - 1);
try {
if (!"".equals(ids){
String sqlStr = "Delete from food WHERE id in (?)";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setString(1, ids);
int rec=pstmt.executeUpdate();
conn.commit();
}
} finally {
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
}

What is the syntax of replace statement?

This is my controller
#RequestMapping(value = "/deleteMultiple", method = RequestMethod.POST)
public ModelAndView deleteEmp(#ModelAttribute("employee") Employee emp,#RequestParam(value="Id",required=false) String Id,Model model) {
List<Employee> empList = empService.getEmpList();
List<Employee> empListById = empService.getemp_IdDetails(Id);
empList=empService.searchEmpDetails(emp);
empList.addAll(empListById);
Employee emp1=new Employee();
if(empList!=null){
model.addAttribute("delete", empList);
if(empList.isEmpty()){
model.addAttribute("message","This Employee Details are not present");
}
}
model.addAttribute("employee", emp1);
return new ModelAndView("delete","empList",empList);
}
This is my sql
#Override
public List<Employee> getemp_IdDetails(String emp_Ids){
List<Employee> empList = new ArrayList<Employee>();
String sql="select * from EmpDetails where emp_Id IN" + " ("+emp_Ids+") ";
sql.replace("emp_Id", emp_Ids);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
empList = jdbcTemplate.query(sql, new EmployeeRowMapper());
System.out.println("empList:"+empList.size());
return empList;
}
This is my jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Drop down</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#delete").click(function(){
var d = [];
$.each($("#delete option:selected"), function(){
d.push($(this).val());
});
var s=(d.join(", "));
console.log(s);
$("#delete_empId").val(s);
console.log($("#delete_empId").val());
});
});
</script>
</head>
<body>
<div align="center">
<form:form method="post" action="${pageContext.request.contextPath}/deleteMultiple" modelAttribute="employee">
<table>
<tr>
<td>First Name :</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Last Name :</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td>emp_Id :</td>
<td><form:input path="emp_Id" /></td>
</tr>
<tr>
<td>email_Id :</td>
<td><form:input path="email_ID"/></td>
</tr>
<tr>
<td>phone_No :</td>
<td><form:input path="phone_No"/></td>
</tr>
<tr>
<td>City :</td>
<td><form:input path="city"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
<input type= "hidden" id="delete_empId" name="delete_empId" />
</form:form>
</div>
<div align="center">
<h2 style="color:blue">SelectBox:</h2>
<form:form method="post" action="${pageContext.request.contextPath}/deleteMultipleEmpDetails">
<select id="delete" multiple name="employees">
<c:forEach items="${empList}" var="employee">
<option value= "${employee.emp_Id}" >${employee.firstName}</option>
${msg}
</c:forEach>
</select>
<input type="submit" name="delete" value="delete">
</form:form>
</div>
<div>
<h4 style="color:red">${message}</h4>
</div>
</body>
</html>
This is my code i am retriving the values from jsp and passing the values to my controller.So i need to replace the values of emp_Id by emp_Ids.I have wriiten the replace function in sql is that coorect.I am getting null pointer exception.

Geting the first line in the textarea from database

I am trying to retrieve the value of an HTML textarea in jsp page from mysql database.The problem I am having is that I only can get he first line in the textarea(When I'm saving address in databse, It's retrieving first line only). This is happening for text box also, where data has space in the database, it's only getting first line of the data.
Thanks in advance.
HTML Code:
<div class="container2">
<table>
<tr>
<td align="right">TPO Name</td>
<td><input type="text" readonly name="tponame" value=<%=rs.getString("tponame")%>></td>
</tr>
<tr>
<td align="right">Name of College</td>
<td><input type="text" readonly name="college_name" value=<%=rs.getString("college_name")%>></td>
</tr>
<tr>
<td align="right">Contact Number</td>
<td><input type="text" name="contactno" value=<%=rs.getString("contactno")%>></td>
</tr>
<tr>
<td align="right">Contact Email</td>
<td><input type="text" name="contactemail" value=<%=rs.getString("contactemail")%>></td>
</tr>
<tr>
<td align="right">Address</td>
<td><input type="text" name="address" value=<%=rs.getString("address")%>></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="button" value="Update" style="float:right;"></input></td>
</tr>
JSP code:
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/FMS","root","root");
Statement st=con.createStatement();
String tponame= request.getParameter("tponame");
String college_name=request.getParameter("college_name");
String contactno=request.getParameter("contactno");
String contactemail=request.getParameter("contactemail");
String address=request.getParameter("address");
String sql = ("update tpo_details set contactno='"+contactno+"',contactemail='"+contactemail+"',address='"+address+"' where tponame='"+tponame+"'");
st.executeUpdate(sql);
response.sendRedirect("update_tpo_network_data.jsp");
%>