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.
Related
my Task ist to test a HttpServlet written in Java, which connects to a database and has the following methods implemented:
doGet(), doPost(), doDelete(), doOptions()
To test the functionality independently from the database connection I've implemented an InMemoryDao which populates a H2 database with test data from a Json file and gets injected into my ServletTest class.
Here's an example of the doGet() Method:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
boolean all = req.getParameter("all") != null;
boolean specific = req.getParameter("songId") != null;
if (all == specific) {
resp.setStatus(400);
writePlaintext(resp, "Specify either 'all' or 'songId'.");
return;
}
if (all) doGetAll(req, resp);
if (specific) doGetSpecific(req, resp);
}
My InMemorySongDao class looks like this:
public class InMemorySongDao extends MysqlSongDao {
public InMemorySongDao() throws SQLException {
super(new ComboPooledDataSource());
UUID uuid = UUID.randomUUID();
// Connect to a unique in-memory database identified by a random uuid
this.dataSource.setJdbcUrl("jdbc:h2:mem:" + uuid);
try (PreparedStatement st = this.dataSource.getConnection().prepareStatement(
"CREATE TABLE songs (" +
"id int not null primary key auto_increment," +
"title varchar(100) not null," +
"artist varchar(100)," +
"label varchar(100)," +
"released int" +
")")) {
st.execute();
}
}
/**
* Creates a songs dao prefilled with the songs from the given resource.
*/
public InMemorySongDao(String resourceName) throws SQLException, IOException {
this();
final ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(getClass().getResource(resourceName));
// Read array node or use empty node
ArrayNode array = (rootNode.isArray()) ? (ArrayNode) rootNode : mapper.createArrayNode();
try (PreparedStatement st = this.dataSource.getConnection().prepareStatement("INSERT INTO songs (id, title, artist, label, released) values (?,?,?,?,?)")) {
// Iterate over the array and populate the database with the songs
Iterator<JsonNode> elements = array.elements();
while (elements.hasNext()) {
JsonNode node = elements.next();
if (!node.isObject()) continue;
st.setInt(1, node.get("id").asInt());
st.setString(2, node.get("title").asText());
st.setString(3, node.get("artist").asText());
st.setString(4, node.get("label").asText());
st.setInt(5, node.get("released").asInt());
st.addBatch();
}
st.executeBatch();
}
}
}
Would be very thankful if somebody could provide me any help with this. Unfortunately I couldn't find any proper examples by research...
Kind Regards,
Mic
UPDATE: The return statement is still not working as expected to show single user detail by id in the DAO. I could only use for loop to iterate through the _id to match the userId, but when I click the edit button for the number of user will show all previous user Id in the console.
Another problem is when I call this method in the Service class, the output is null. Still crave for the solution to help me get over it.
#Override
public User get(Object userId) {
User user = new User();
FindIterable<Document> userTbl = database.getCollection("User").find();
for (Document doc : userTbl) {
String id = doc.getObjectId("_id").toString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return user;
}
}
return null;
}
edit user in Service class
public void editUser() throws ServletException, IOException {
Object userId = request.getParameter("id"); // get query string from the jsp
User user = userDAO.get(userId);
System.out.println("User full name is? " + user.getFullName());
}
After getting hints from #Smutje and think through it again, finally figured it out at my 2nd weeks of learning MongoDB. At my level I need to iterate the user document then find the id and return it.it
#Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc;
}
}
return null;
}
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 );
I am trying to pass value from database to drop down menu using getAttribute(). However, it returns null.
This is my jsp (updateLecturer.jsp) file:
<form action="updateLecturer" class="sky-form">
<header>Update Lecturer Information</header>
<center>
<fieldset>
<section>
<label class="select">
<select name="selectLecturer" id="lecturerFullname">
<option value="0" selected disabled>Lecturers Name</option>
**<option name="lecturerFullname"><%=((LecturerBean)request.getAttribute("LecturerFullname"))%></option>**
</select>
</label>
</section>
</center>
<footer>
<center><button type="submit" class="button">Update</button></center>
</footer>
</form>
This is my servlet UpdateLecturerServlet.java) :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String lecturerFullname = request.getParameter("LecturerFullame");
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(lecturerFullname);
request.setAttribute("LecturerFullname",lecturerFullname);
RequestDispatcher view = getServletContext().getRequestDispatcher("/updateLecturer.jsp");
view.forward(request,response);
}
This is my UpdateLecturerDAO :
static Connection currentCon = null;
static ResultSet rs = null;
public static LecturerBean selectlecturer(LecturerBean Lbean) {
// preparing some objects for connection
System.out.println("JIJIJI");
Statement stmt = null;
String lecturerFullname = Lbean.getLecturerFullname();
System.out.println("j444444");
String searchQuery = "select lecturerfullname from lecturer";
System.out.println("Your lecturer is " + lecturerFullname);
System.out.println("Query: " + searchQuery);
try {
// connect to DB
currentCon = JavaConnectionDB.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
// boolean more = rs.next();
while(rs.next())
{
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(rs.getString("LecturerFullname"));
lecturer.add(lecturer);
}
}
catch (Exception ex) {
System.out.println("Select failed: An Exception has occurred! " + ex);
}
PLEASEEEE HELP :( thank you very much
If you set some attribute in request like this
request.setAttribute("key",obj);
You can get it display in jsp by a scriplet like this
<%=request.getAttribute("key")%>
In your case please check the following points
Check whether the following code is giving you a null.
String lecturerFullname = request.getParameter("LecturerFullame");
If this gives you null then check whether your passing parameter LecturerFullame in url.
In the jsp please cast the following to correct object
<option name="lecturerFullname"><%=((String)request.getAttribute("LecturerFullname"))%></option>
And let me know.
I've never worked with any of this type of code before, so I'm not sure how the attribute system works, but I noticed an anomaly in your code:
Where you are setting:
request.setAttribute("LecturerFullname",lecturerFullname);
Where you are getting:
lecturer.setLecturerFullname(request.getAttribute("lecturerFullname",lecturer));
Notice it yet? Where you are setting it, you put a capital "L" and I believe it's case sensitive. Doesn't hurt to try.
In UpdateLecturerServlet.java.
//calling selectlecturer() to retrieve list full names and store it in session
request.setAttribute("LecturerFullname",selectlecturer());
RequestDispatcher view = getServletContext().getRequestDispatcher("/updateLecturer.jsp");
view.forward(request,response);
Now selectlecturer() method.
public static List<LecturerBean> selectlecturer() {
//DB query to retrieve all lecturer fullnames
List<LecturerBean> lecturers = new ArrayList<LecturerBean>();
while(rs.next())
{
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(rs.getString("LecturerFullname"));
lecturers.add(lecturer);
}
return lecturers;//return the list lecturer fullnames
}
In updateLecturer.jsp.
<%
java.util.List<LecturerBean> lists = (java.util.List<LecturerBean>)request.getAttribute("LecturerFullname"));
for(LecturerBean bean:lists)
{
%>
<option name="lecturerFullname"><%=bean.getLecturerFullname()%></option>
<%
}
%>
But you should avoid Java code in JSP. Just for the reference here I'm giving this code.
I have this jsp document (below). Basically, when user types in the textbox, I want to show an error if the username exists in the database/ length<5, etc.
I want these errors to be simultaneously displayed without any refresh through jQuery/AJAX. I did this but it doesn't seem to be working. Here, CheckAvailability and Success are servlets and CheckAVailability checks the existence in database.
the JSP file:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.11.3.js"></script>
<script>
$(document).ready(function() {
$('#username').keyup(function() {
var name = $('#username').val();
$.get('CheckAvailability?username='+name,function(responseText){
$('#status').text(responseText);});});
</script>
</head>
<body>
<form id="login_form" ><input type="text" placeholder="username" name="username" class="style-4" required="required" action="Success"/>
<div id="status"> </div>
CheckAvailability Servlet
public class CheckAvailability extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn=null;
Statement s=null;
ResultSet rs=null;
PreparedStatement ps;
try {
//make connection
String userid = request.getParameter("username");
String arr;
Class.forName("oracle.jdbc.OracleDriver");
if (userid.equals("")) {
arr = "Error: User name cannot be empty";
} else if(userid.length()<5){
arr="Error: Username cannot be less than 5 characters.";
}
else
{
String table="user1.app_users";
String p = "alpha";//database password
String query = "select userid from " + table + " where userid='" + userid + "'";
String url = "jdbc:oracle:thin:system/" + p + "#localhost:1521:XE";
conn = DriverManager.getConnection(url);
s = conn.createStatement();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
if (!rs.next()) {
arr="UserID <b>" + userid + "</b> is available.";
} else {
arr= "Error: UserID <b>" + userid + "</b> is already in use.";
}
}
response.setContentType("text/plain");
response.getWriter().write(arr);
}catch (SQLException se) {
out.println("Error ->" + se.getMessage());
} catch(ClassNotFoundException ce)
{
out.println("Error ->" + ce.getMessage());
}finally {
out.close();
}
}
}
But this isn't displaying anything as I type in the text box. The servlet did fire on hitting on submit. What didn't happen was that the text didn't display alongside. The code executes, no error in my IDE on that. I can't exclusively run the servlet, it gives the error: 'HTTP method GET is not supported by this URL', i.e. when I run it with parameters. I took the input inside as in, String username="user12", and that didn't run either. Can anybody point out my mistake? I'm new to jQuery/AJAX.
This worked for me:
$(document).ready(function() {
$('#userid').keyup(function(event) {
var user=$('#userid').val();
$.get('CheckValidity',{username:user},function(responseText) {
$('#status').text(responseText);
});
});
});
Had to use a different JQuery.
Overrride doGet, because javax.servlet.http.HttpServlet doesn't have any processRequest method.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("hi " + req.getParameter("username"));
}
Read this
Anyway.. how are you declaring your servlet? Through annotations? In web.xml? And what's the URL pattern?
if using web.xml:
<servlet>
<servlet-name>CheckAvailability Servlet</servlet-name>
<servlet-class>your.package.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability Servlet</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
if using annotations:
#WebServlet("/CheckAvailability")
public class Serv extends HttpServlet {
// ...
}