I got table in JSP, which is table's mirror image from database (all records and columns are displayed), and next to each row I got button "delete" which deletes row from database by ID. But when I click "delete" button then nothing happens in database, it seems like selected row's ID is null, but at address bar selected ID is displayed. What am I doing wrong?
Controller:
#RequestMapping(value="/checkout.html", method = RequestMethod.POST)
public ModelAndView checkOut(Model model, #RequestParam(value = "id", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
DAO:
public void deletePatient(String id) throws SQLException {
String query = "delete FROM virtualclinic.patient WHERE idpatient=?";
Connection con = null;
PreparedStatement ps = null;
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, id);
int out = ps.executeUpdate();
}
Service:
public void deletePatient(String id) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("clinicconfig.xml");
patientDAO = ctx.getBean("patientDAO", PatientDAOImpl.class);
patientDAO.deletePatient(id);
}
JSP file:
<c:forEach items="${patients}" var="patient">
<tr style="font-size: 10">
<td>${patient.id}</td>
<td>${patient.name}</td>
<td>${patient.lastName}</td>
<td>${patient.gender}</td>
<td>${patient.age}</td>
<td>${patient.phoneNumber}</td>
<td>${patient.address}</td>
<td>${patient.disease}</td>
<td>${patient.condition}</td>
<td>${patient.roomType}</td>
<td>${patient.roomNumber}</td>
<td>${patient.date}</td>
<td><form action="/VirtualClinic/checkout.html?selectedPatient=${patient.id}" method="post"><input type="submit" value="Delete"/></form></td>
</tr>
</c:forEach>
Error(?):
INFO: Mapped "{[/checkout.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.infoPatient(org.springframework.ui.M odel) throws java.sql.SQLException
lut 17, 2016 3:16:57 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMa pping register
INFO: Mapped "{[/checkoutPatient.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.checkOut(org.springframework.ui.Model,java.lang.String) throws java.sql.SQLException
Use and GET rather than a POST and because on the url you are using the parameter selectedPatient rather than your expected id - change either/or
Make your controller method get
#RequestMapping(value="/checkout.html", method = RequestMethod.GET)
public ModelAndView checkOut(Model model, #RequestParam(value = "selectedPatient", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
change your delete link as follow
<td>delete</td>
I dont see anyreason to make the request by post it is just one parameter, you dont need the form
Related
public class UpdateEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out= response.getWriter();
EmployeeDetails emp = new EmployeeDetails();
SessionFactory fact=new Configuration().configure().buildSessionFactory();
Session ses = fact.openSession();
int emp_id = Integer.parseInt(request.getParameter("emp_id"));
int new_emp_id = Integer.parseInt(request.getParameter("new_emp_id"));
String emp_name = request.getParameter("name");
String emp_designation_id = request.getParameter("designationid");
String emp_skills = request.getParameter("skills");
String emp_department_id = request.getParameter("departmentid");
String emp_notes = request.getParameter("notes");
String emp_email = request.getParameter("email");
String emp_phone = request.getParameter("phone");
String emp_username = request.getParameter("username");
String emp_password = request.getParameter("password");
emp.setEmp_department_id(emp_department_id);
emp.setEmp_designation_id(emp_designation_id);
emp.setEmp_email(emp_email);
emp.setEmp_id(new_emp_id);
emp.setEmp_join_date(null);
emp.setEmp_name(emp_name);
emp.setEmp_notes(emp_notes);
emp.setEmp_password(emp_password);
emp.setEmp_phone(emp_phone);
emp.setEmp_skills(emp_skills);
emp.setEmp_username(emp_username);
Query query = ses.createQuery("update EmployeeDetails emp set emp_id=:new_emp_id,emp_name=:emp_name,emp_designation_id=:emp_designation_id,emp_skills=:emp_skills,emp_department_id=:emp_department_id,emp_notes=:emp_notes,emp_email=:emp_email,emp_phone=:emp_phone,emp_username=:emp_username,emp_password=:emp_password where emp_id=:emp_id");
query.setParameter(emp_id, emp_id);
query.setParameter(new_emp_id, new_emp_id);
query.setParameter(emp_name, emp_name);
query.setParameter(emp_designation_id, emp_designation_id);
query.setParameter(emp_skills, emp_skills);
query.setParameter(emp_department_id, emp_department_id);
query.setParameter(emp_notes, emp_notes);
query.setParameter(emp_email, emp_email);
query.setParameter(emp_username, emp_username);
query.setParameter(emp_password, emp_password);
int result = query.executeUpdate();
out.print(result);
}
}
My result when i try to update:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:55)
org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:61)
org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:382)
org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:362)
com.unisys.servlets.UpdateEmployee.doPost(UpdateEmployee.java:59)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I'm new to hibernate. I've looked up lot of references, any sort of guidance regarding updation would be much appreciated.
I'm trying to update one value in the row using emp_id value and updating all the other columns in the database.
Yes, you are correct. But here the guy is mixed up the "Named" parameters with indexed parameter concepts.
query.setParameter("emp_id", emp_id);
query.setParameter("new_emp_id", new_emp_id);
query.setParameter("emp_name", emp_name);
query.setParameter("emp_designation_id", emp_designation_id);
query.setParameter("emp_skills", emp_skills);
query.setParameter("emp_department_id", emp_department_id);
query.setParameter("emp_notes", emp_notes);
query.setParameter("emp_email", emp_email);
query.setParameter("emp_username", emp_username);
query.setParameter("emp_password", emp_password);
query.setParameter("emp_phone", emp_phone);
int result = query.executeUpdate();
The main purpose of named parameter is we don't worry about the order and it is easily understandable and maintainable.
The java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based! is misleading.
In your JPQL query, you use this condition emp_phone=:emp_phone with the emp_phone parameter but the parameter value is never set in the query :
Query query = ses.createQuery(
"update EmployeeDetails emp set..emp_phone=:emp_phone");
query.setParameter(emp_id, emp_id);
query.setParameter(new_emp_id, new_emp_id);
query.setParameter(emp_name, emp_name);
query.setParameter(emp_designation_id, emp_designation_id);
query.setParameter(emp_skills, emp_skills);
query.setParameter(emp_department_id, emp_department_id);
query.setParameter(emp_notes, emp_notes);
query.setParameter(emp_email, emp_email);
query.setParameter(emp_username, emp_username);
query.setParameter(emp_password, emp_password);
int result = query.executeUpdate();
So, Hibernate throws an exception.
Here I have created dynamic dropdown list using this link, but when I select some value from available list it should be called in action class.
The dropdown list which can be seen in the image ,here the values are loaded dynamically from the database and now what I want is when I select any value from that two dropdown list that values (I mean text value) should be sent to the action class and there I will execute one JDBC select query on the basis of this two values and will display in the table shown in the image but everything should be on load.Action should be on selecting values from dropdown list not on any button click .With static values I am able to call value from dropdown list into action class with name attribute.But in this case I cannot :(
I hope I am clear now .
I have tried calling select tag using listkey,name and id but none of them worked .
Below is my JSP code:
<div>
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:form action="ActionSelect">
<s:submit value=" Click Here"/>
</s:form>
<div>
Action class for loading dynamic dropdown list :
package com.ca.actions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ca.database.Database;
import com.ca.pojo.Event;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
List<Event> dataForBillsJspList;
private List state = new ArrayList();
private List status = new ArrayList();
String eventName;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public RetrieveEvNaCoNaAction() {
// TODO Auto-generated constructor stub
}
public List<Event> getDataForBillsJspList() {
return dataForBillsJspList;
}
public void setDataForBillsJspList(List<Event> dataForBillsJspList) {
this.dataForBillsJspList = dataForBillsJspList;
}
public List getStatus() {
return status;
}
public void setStatus(List status) {
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_NAME,COMPANY_NAME,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo FROM EVENT");
ResultSet rs = ps.executeQuery();
//dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
/*dataForBillsJspList.add(new Event(rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo")));
System.out.println(rs.getString("EVENT_NAME"));*/
status.add(rs.getString("COMPANY_NAME"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
}
public List getState() {
return state;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
setState(this.state);
setStatus(this.status);
return "success";
}
public String showEventDetails(){
System.out.println("Hi.."+eventName);
return SUCCESS;
}
public void setState(List state) {
//implement the application specific logic to
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME FROM EVENT");
ResultSet rs = ps.executeQuery();
dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"),rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),rs.getString("EVENT_VENUE"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo"),rs.getString("EVENT_TIME")));
//System.out.println(rs.getString("EVENT_NAME"));
state.add(rs.getString("EVENT_NAME"));
System.out.println(rs.getString("EVENT_ID"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
//Here for displaying the data on UI, we are using few hardcoded values//
}
}
After loading dynamic dropdown list now i am trying to call selected value in action class by S.O.P but it gives null pointer exception. Below is my POJO class:
package com.ca.pojo;
public class Dropdown
{
private String eventState;
private String companyState;
public Dropdown() {
// TODO Auto-generated constructor stub
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
public String getCompanyState() {
return companyState;
}
public void setCompanyState(String companyState) {
this.companyState = companyState;
}
}
and below is action class where I am trying to call that selected value by using name attribute :
package com.ca.actions;
import com.ca.pojo.Dropdown;
import com.opensymphony.xwork2.ActionSupport;
public class DropdownAction extends ActionSupport
{
Dropdown dp;
public DropdownAction() {
// TODO Auto-generated constructor stub
}
public Dropdown getDp() {
return dp;
}
public void setDp(Dropdown dp) {
this.dp = dp;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(dp.getEventState());
return "success";
}
}
struts.xml is properly configured. Now after selecting two values I want to display data in the below table accordingly without any button click but in jsp i have created button just to see whether i am getting the selected value in action class but in actual i want it without any button click.
Well, there is a huge mess here :D
First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form.
You should enclose them in the form like this for them to be sent to the ActionSelect action:
<s:form action="ActionSelect">
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:submit value=" Click Here"/>
</s:form>
Solved the mistery, this doesn't solve your problem, though.
You have two main ways to contact actions from a page:
Using a standard submit (as you're doing):
you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.
Using AJAX:
you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...
You then can choose what to do with the returned data, for example load it inside a <div> that before was empty, or had different content.
Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the "success" result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.
Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.
That said,
avoid putting logic in getters and setters;
avoid calling methods that are not setter as setters (setState, setStatus...);
always make your attributes private;
try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");
consider loading informations like selectbox content in a prepare() method, so they will be available also in case of errors;
you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)
The following is a refactoring of your code to make it achieve the goal. I'll use #Getter and #Setter only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):
<head>
<script>
$(function(){
$("#event, #company").on('change',function(){
$("#myForm").submit();
});
});
</script>
</head>
<body>
<form id="myForm">
<div>
...
<s:select id="event" name="event" list="events" />
...
<s:select id="company" name="company" list="companies" />
...
</div>
</form>
<div>
...
Table - iterate **dataForBillsJspList** here
...
</div>
</body>
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
#Getter private List<Event> dataForBillsJspList = new ArrayList<Event>();
#Getter private List<String> events = new ArrayList<String>();
#Getter private List<String> companies = new ArrayList<String>();
#Getter #Setter private String event = null;
#Getter #Setter private String company = null;
#Override
public void prepare() throws Exception {
Connection con;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) { companies.add(rs.getString("company_name")); }
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) { events.add(rs.getString("event_name")); }
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() {
Connection con;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " +
"date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " +
"FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (event!=null && company!=null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length()>0) {
ps.setString(1,event);
ps.setString(2,company);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"),
rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),
rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"),
rs.getString("EVENT_TIME")));
}
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
}
It is a kickoff example, but it should work.
The next steps are:
create a POJO with id and description, show the description in the select boxes, but send the id
use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)
PAGINATION
Good luck
Using Javascript/jQuery you can do this, it depends on what you want to do after reached action class.
If you want to navigate to another page use the code below.
Add onchange event as an attribute to your dropdown,
onchange="customFunction(this.value)"
create customFunction in header part,
function customFunction(selectedValue){
window.location="Action_URL?myValue="+selectedValue;
}
Or if you want to return back the same page use jQuery ajax,
$("#eventName").change(function(e){
var selectedValue = $(this).val();
$.ajax({
type : 'post',
url : 'Action_URL',
data: { myValue: selectedValue},
success : function(data) {
alert(data);
console.log(data);
}
});
});
Hope this helps.
I'm writing my first bigger app and I have one issue, my code below:
InitDB.java
public void requestInitialized(ServletRequestEvent arg0) {
EntityManager em = DBConfig.createEntityManager();
BooksDAO booksDAO = new BooksDAO(em);
CategoryDAO categoriesDAO = new CategoryDAO(em);
ServletRequest req = arg0.getServletRequest();
req.setAttribute("booksDao", booksDAO);
req.setAttribute("categoriesDao", categoriesDAO);
}
BooksDAO.java
EntityManager em = DBConfig.createEntityManager();
public BooksDAO(EntityManager em) {
this.em = em;
}
public List<Books> getBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
List<Books> booksByCategory = q.getResultList();
return booksByCategory;
}
booksCategoryServlet.java
#WebServlet("/booksCategory")
public class booksCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String category = request.getParameter("category");
if (category != null) {
BooksDAO dao = (BooksDAO) request.getAttribute("booksDao");
List<Books> booksByCategory = dao.getBooksByCategory(category);
request.setAttribute("booksByCategory", booksByCategory);
request.getRequestDispatcher("/booksCategory.jsp").forward(request, response);
} else
response.sendRedirect(request.getContextPath() + "/");
}
bookCategory.jsp
<c:forEach var="book" items="${booksDao.booksByCategory}">
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.description}</td>
<td>${book.category}</td>
<td>${book.year}</td>
<td>show details</td>
</tr>
</c:forEach>
index.jsp
<c:forEach var="category" items="${categoriesDao.categories}">
<li>${category}</li>
</c:forEach>
In index page I have listed categories, and when i want go to choosen category and display books for this category i got this exception:
org.apache.jasper.el.JspPropertyNotFoundException: /booksCategory.jsp(40,4) '${booksDao.booksByCategory}' Property 'booksByCategory' not found on type DAO.BooksDAO
Can someone tell me what I did wrong?
You're calling a method thinking you're calling for an actual object.
I'd create a List<Books> object in DAOBooks and send it with the request to the JSP.
Solution
DAOBooks
EntityManager em = DBConfig.createEntityManager();
List<Books> booksByCategory = new ArrayList<>(); // Or whatever list type you need.
public BooksDAO(EntityManager em) {
this.em = em;
}
public void setBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
booksByCategory = q.getResultList();
}
public List<Books> getBooksByCategory(){
return booksByCategory;
}
And in your JSP
<c:forEach var="book" items="${booksByCategory}">
Make a direct reference to the List<Books> object because it is the one you're sending via the request.
EDIT
Try to have a distinct setter and getter method. It'll help you have a more readable code and will solve those type of problems instantly.
I made an example in my post but it is not necessarily a correct one, you have to find the ways to implement them following your application logic.
I can't delete a user. This is the error i get when i click the delete button. org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [DELETE FROM users WHERE id = '1']; Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). Please help thanks a lot
Jdbc function of delete
public int deleteUser(int id){
String SQL = "DELETE FROM users WHERE id = '"+id+"'";
System.out.print(SQL);
int user = jdbcTemplateObject.update(SQL, id);
return user;
}
delete controller
RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView delete(#ModelAttribute("SpringWeb")User user, ModelMap model, HttpServletRequest request)
{
try
{
SyntacksJdbc syntacksJdbc = (SyntacksJdbc)context.getBean("syntacksJdbc");
System.out.println(request.getParameter("id"));
int id = Integer.parseInt(request.getParameter("id"));
int user1 = syntacksJdbc.deleteUser(id);
model.addAttribute("message", "Questions updated successfully.");
}
catch(Exception e)
{
System.out.print(e);
model.addAttribute("message", "Error occured in posting question.");
}
return new ModelAndView("users");
on my jsp button
<a href="/Project/delete?id=${user.id}" name="delete"><button type= submit>Delete</button>
change query to
DELETE FROM users WHERE id = ?
since you are trying to set parameter value
I'm working in Google gcm application,and here I'm authenticating the app user by correct Id & password.Authentication is working properly.
My I'm running this page by Run as -> Run on Server(Homeservlet.java),even for the correct employee and password,it's not showing the written jsp code(which is written in the if condition) and going to the else-part.
In the eclipse console : I can see the employee name and it's password.But my question is how to set the values sothat when I will run this page it'll show that jsp page inside.
I'm using set parameter to set the value,but whenever I'm running this page in Tomcat server,it's showing IllegalArgumentException.I found it's quiet relevant because when I'm running the value's are not set.
Actually I want ,for the correct employee and corresponding password,...it'll show that jsp page; otherwise(i mean in else-part,it'll not)
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
private static final int HTTP_STATUS = 200;
// private static final String HTTP = "OK";
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException {
PreparedStatement stmt = null;
String employee=req.getParameter("employeeid"); //getting the value from app User
String password=req.getParameter("password"); //corresponding password
req.setAttribute(employee, employee);
req.setAttribute(password, password);
try {
String url="jdbc:mysql://localhost/apps";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url,"root","root");
stmt = con.prepareStatement("select * from regid where emp_id=? and password=?");
stmt.setString(1, employee);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
System.out.println("2> Employee Id : "+employee+" && Password : "+password);
System.out.println("3> This employee "+employee+" exsists in the database and will be there");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html>"); //1> want to run this portion from here
out.print("<head>");
out.print("<title>Policy Page</title>");
out.print("<link rel='icon' href='../images/favicon.png'/>");
out.print("</head>");
out.print("<body>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null)
{
out.print("Status : "+status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty())
{
out.print("<h2>No devices registered!</h2>");
}
else
{
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='text' name='policy'>");
resp.setStatus(HttpServletResponse.SC_OK);
out.print("<input type='submit' value='Apply Policy'>");
out.print("</form>");
// getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
out.print("</body></html>"); //2> to here
resp.setStatus(HttpServletResponse.SC_OK);
}
else { //else-part
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
System.out.println(HttpServletResponse.SC_BAD_REQUEST);
System.out.println("4> This employee "+employee+" does not exsist in the database");
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
} catch(Exception x) {}
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
When the app user giving the id-password,the output in the console is:
2> Employee Id : P1 && Password : ppp
3> This employee P1 exsists in the database and will be there
but I'm running the page(run as->run on server-tomcat-6),it is showing this(instead of showing the jsp page)
HTTP Status 500
java.lang.IllegalArgumentException: Cannot call setAttribute with a null name
at org.apache.catalina.connector.Request.setAttribute(Request.java:1431)
at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:50
any idea....... where I'm going wrong.
2 things observed.
1)
Use
req.setParameter("employee", employee);
req.setParameter("password", password);
instead
req.setAttribute(employee, employee);
req.setAttribute(password, password);
2)
The next page you are showing is not a JSP. It is plain html created in servlet.
The set content type is html.
If you want to display employee in html,
you can write code like this,
out.print("<body>");
out.print("Welcome to this site Mr."+ employee);
If you still want to use the employee as a variable on that html, you have to embed Javascript in this page.