Print output in TextArea(append-way) from different class in JSP/Servlet - java

I have below Dynamic web project setup
Index.jsp
<form action="submitClick" method ="post"
<textarea> id="textarea" name="textarea" rows="25" cols="100">${result}</textarea>
<input type="submit">
SubmitClick.java //servlet class
public class SubmitClick extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response){
MainLogicClass mainLogic = new MainLogicClass(username,password); //let's suppose hardcoded
request.setAttribute("result", "Hello");// Hello is getting printed on textarea, but I want to print output text on textarea from MainLogicClass.
getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
MainLogicClass//different class, present in same package
public class MainLogicClass{
public MainLogicClass(String username, String password){
//DB Connection logic
System.out.println("Database Connection successful");
/* I want to print "Database Connection successful" on textarea which presents on index.jsp
And after that, I need to print few more output so that the text gets appended to textarea like-
"Database Connection successful
DB query executed
DB connection closed"
*/
}
}
How can I print text from MainLogicClass to Servlet using request.setAttribute method or any other workaround.

Constructor doesn't have any return type so instead of constructor you can create a method and put your logic code there and return some value from there . So , your method inside MainLogicClass will look like somewhat below :
public String Something(String username, String password){
String msg = "" ;
msg +="Something to return";
msg +="soemthing more";
//your logic code
return msg;//return back
}
And then in your servlets doPost method do like below :
MainLogicClass mainLogic = new MainLogicClass();
String message = mainLogic.Something(String username, String password);//call that function
request.setAttribute("result", message );

Related

How to call action after selecting values from dynamically created dropdown list using struts2

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.

Servlet with jdbc response to client [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have a database with houses, and HTML page with <SELECT>, where user need to select a district where the houses are located.
Servlet:
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
String choice = request.getParameter("district");
//Database parameters
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
Connection conn;
try {
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = conn.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = " + choice);
}catch (SQLException ex) {
System.out.println("Fail to connect with base");
}
}
}
How can I put SQL select results into HTML page and give it back to client?
I created class House
public class Hosue implements Serializable {
private String price;
private String square;
private String RoomNumbers;
public String getPrice() {
return price;
}
public String getSquare() {
return square;}
public String getRoomNumbers() {
return RoomNumbers;}
public void setPrice(String price) {
this.price = price;
}
public void setSquare(String square) {
this.square = square;
}
public void setRoomNumbers(String roomNumbers) {
RoomNumbers = roomNumbers;
}
}
and houses
public class Houses {
public List<House> getList() {
}
}
and add script to my html. What next, how to add information from select to this list?
You can solve your problem as said by Jeed in the previous answer. However, it would be better if you model your db entities with Java objects and use them to encapsulate information from and towards the db. You may also use the DAO programming pattern to better organize your code, thus you can define simple objects (beans) to model data (your database entities) and data access object (DAO object) in which you would encode interaction with the db (your jdbc code).
Then you will have something like this to query your db (this code will be in your servlet):
HouseDAO h=new HouseDAO(db connection param...)
ArrayList<House> list=h.selectHouses();
In the HouseDAO object you will create a method selectHouse in which you will basically move the jdbc code you have in your servlet right now. By the way, your are missing a part in which you call the method execute query from the ps object. This method returns a ResultSet object which contains the query result.
With the code above, you will have your data in the ArrayList list, and you can use the code suggested by Jeed to output it.
Clearly, if you want to avoid using jsp, you can print your html code directly in your servlet. I do not recommend this as you would merge view details with control and model code. This is not good especially if you are planning to change your view in the future.
Add result of your query to some List or custom object and set it as attribute in your request object.
request.setAttribute("result", result);
and then forward to your next page using RequestDispatcher.
Use Gson external Library for sending java-List into String form to
HTML,
Your Servlet Code looks likewise,
List<House> listofHouses = getList from Database;
Gson gson = new Gson();
String json_obj = gson.toJson(listofHouses);
response.getWriter().println(json_obj);
Your HTML(use Jquery-ajax for Handling result & send Request to
Servlet ) Code looks some what nearer likewise......
<script>
$.ajax({
url: 'Servlet.do?distinct=YOUR_SELECTED_district_NAME',
type: "POST/GET",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
var returnedData = JSON.parse(data);
alert(data);
$.each(data, function(index, value) {
('#your_drop_down_tag_id').append($('<option>').text(value).attr('value', index));
});
}
});
</script>
NOTE: jquery-XXX.js file must be inclue into your project and into your html file properly.

Issue while passing the parameters from action class to view page in Liferay

I have a view page where I have button to import the users from an excel sheet, So on click of import users button I am calling the following method in my portlet action class, Here I am iterating the list and calling the user creation method to create the users. Now I am able to create the users in the database. But I need to show which users are created and which users are not created in my status.jsp, I.e; After user creation I need to navigate to status page and display the which are created and which are not.
So I have declared two array lists globally and and added success user creation in one list and failed user list in another list as shown below, But I am getting error and not able to add to arraylist and not able to pass the arraylist to status page,
My action class,
static ArrayList<String> successList;
static ArrayList<String> failureList;
public void addUser(ActionRequest request, ActionResponse response)
throws IOException, PortalException, SystemException {
successList = new ArrayList<String>();
failureList = new ArrayList<String>();
while (iterator.hasNext()) {
userCreation(themeDisplay, serviceContext, values.get(Field.Project_Name), values.get(Field.Project_Status), values.get(Field.Start_Date),
values.get(Field.End_Date), values.get(Field.Company_Name), values.get(Field.PM_FirstName), values.get(Field.PM_MiddleName),
values.get(Field.PM_LastName), values.get(Field.PM_Email), values.get(Field.PM_Password), values.get(Field.PM_Role), values.get(Field.PM_Status));
}
request.setAttribute("successList", successList); request.setAttribute("failureList", failureList); response.setRenderParameter("mvcPath","/html/status.jsp");
}
public static void userCreation(ThemeDisplay themeDisplay, ServiceContext serviceContext,
String Project_Name, String Project_Status, String Start_Date, String End_Date, String Company_Name,
String FirstName, String MiddleName, String LastName, String Email, String Password,
String Role, String Status) throws PortalException, SystemException
{
String result = null;
try {
System.out.println("Try Bolck Start");
User newUser = UserLocalServiceUtil.addUser(creatorUserId, companyId, autoPassword, Password,
Password, autoScreenName, screenName, Email, facebookId, openId,
locale, FirstName, MiddleName, LastName, prefixId, suffixId, male,
birthdayMonth, birthdayDay, birthdayYear, role, groupIds,
organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
long newUserID = newUser.getUserId();
result = "The User "+ Email + " is created ";
successList.add(result);
} catch(Exception e){
result = "The User "+ Email + " is not created ";
failureList.add(result);
}
}
Status.jsp:
<%#page import="java.util.ArrayList"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<portlet:defineObjects />
<%
String success = (String)request.getAttribute("successList");
String failure = (String)request.getAttribute("failureList");
if(success!= null && !success.isEmpty())
{
out.println("Following users are created successfully");
out.println(success);
out.println();
}
if(failure!= null && !failure.isEmpty())
{
out.println("Following users are not created ");
out.println(failure);
out.println();
}
%>
Also How can I send my list as list instead string, so that I can iterate the list in status.jsp and display in table format.
Thanks in advance
The two static lists in the portlet class can lead to contention problems when more than one users try to add users via this action.
A good suggestion is to redirect the user after the action is finished so that the action cannot be triggered again by refreshing the page.
Therefore, you cannot pass the two lists as a request attribute because the rendering that happens after the redirect will trigger a new request and therefore the attributes you have set are gone.
Liferay passes success and error messages from actions to the subsequent portlet rendering after a redirect by using the user session objects. I guess that using the session is a good option to pass your two lists to the rendering phase.

taking servlet information with submit button [duplicate]

This question already has answers here:
How to call servlet class from HTML form
(2 answers)
Closed 7 years ago.
Im trying to create a Servlet application. When I hit the submit button I want to clear the forms and add the information to a unordered list and store the data. The issue is that I do not know how to evaluate when the button is pushed.
package org.gephi.demos;
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
// Extend HttpServlet class
#WebServlet(name = "HelloWorld", urlPatterns = {"/test"}, loadOnStartup=1)
public class HelloWorld extends HttpServlet {
private String message;
private File f;
private GephiBuilder gb;
//private Main m;
public void init() throws ServletException
{
gb = new GephiBuilder();
System.out.println("Initialized");
// Do required initialization
message = "Hello World for sure";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
//m = new Main(gb);
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println(HTMLUserInput("do you want a Nodes(n) or auto(a)", "directory", "d"));
String directory = request.getParameter("d");
// do some processing here...
// build HTML code
if(request.getParameter("button")!=null)
{
System.out.println("Hello");
//response.getParameter("d").valu;
String htmlRespone = "<html>";
htmlRespone += "<h2>Your directory is: " + directory + "<br/>";
htmlRespone += "</html>";
// return response
out.println(htmlRespone);
}
//out.println(addJSCode());
}
public String HTMLUserInput(String question, String id, String name){
String htmlOutput = "<form action=\"HelloWorld\"><label>"+question+"</label>"
+"<input name = \""+name+"\" id=\""+id+"\" type=\"text\"/>"
+"<input id=\"button\" type=\"button\">Submit</form>";
return htmlOutput;
}
public void destroy()
{
// do nothing.
}
}
If I press the button nothing changes, I imagine because this code is only evaluated on startup, how do I get it evaluated anytime I press my submit button.
1.You have to use URL for your servlet(wich was specified in servlet mapping) in action attribute . For example: <form action='/test'>
2.There is several way how to submit the form to the server. You can use <input type="submit">Submit</input> inside form tag .
Or if you want to use tag button you have to set id attribute for the form (<form id='myform' .../>) and connect button with the form specifying this id in form attribute:
<button type="submit" form="myform">Submit</button>
And button tag does not have to be located within form tag.
3.After that you can get the content of your form using request.getParameter("input name") and handle these data.
Use <input type="submit" /> instead of <button>
Your urlPatterns = {"/xxxxx"}, should match form action="xxxxx"

Unable to set the value for running the java file

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.

Categories