HttpServletRequest getting request - java

I need really help. I have a login.jsp page
<html>
<head></head>
<body>
<form method="post" action="j_security_check">
<table>
<tr>
<td>
<input type="text" name="j_username" autofocus="autofocus" required="required" />
</td>
</tr>
<tr>
<td>
<input type="password" name="j_password" required="required" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Login" />
</tr>
</table>
</form>
</body>
</html>
this is my web.xml
All Pages
/*
MY_User
<security-role>
<role-name>MY_User</role-name>
</security-role>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>myRealm</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
In my filter I get the Principal. But somehow when I get into my main Class. The request is gone!
How can I pass my Request to another Java class?

1) As per your query in comments, you can convert Command.java to a servlet just by extending it with the HttpServlet class. Then you can have access to request and response objects in Command.java class.
2) other way to pass request and response objects to your Command.java class is as below:
Let's say you have a servlet MyServlet from where you want to call the methods of Command.java class
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
Command c =new Command();//object creation depends on your project. e.g you can create it using beans of spring
c.doSomething(request, response);
}catch(Exception e){
e.printStackTrace();
}
}
}
Then, your Command class methods should have below parameters:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Command {
public void doSomething(HttpServletRequest request,HttpServletResponse response) {
System.out.println("doing something");
}
}
Remember, Servlet request and response are just objects of a simple java class. They does not depend on any api like servlet, you can pass these objects to any java class and their properties will remain same, no matter its servlet or a java class.

Related

Servlet mapping in web Applications

Currently I'm working for web application. Actually my code looks like below
<div class="article">
<form action="currentcondition.do" method="post">
<table>
<tr><td>Disease Name</td><td><input type="text" name="disease" required/></td></tr>
<tr><td>Status</td><td><select name="status"><option>-Select-</option>
<option>Current : Currently has this</option>
<option>Intermittent : Comes and Goes</option>
<option>Past : No longer has this</option>
</select> </td></tr>
<tr><td>Start Date</td><td><input type="date" name="sdate"/></td><td>End Date</td><td><input type="date" name="edate"/></td></tr>
<tr><td>Hospital Name</td><td><input type="text" name="hname" /></td><td>Dr Phone</td><td><input type="text" name="dphone" maxLength="10"/></td></tr>
<tr><td>Note</td><td><textarea name="note"></textarea></td></tr>
<tr><td>Click here to</td><td><input type="submit" value="save"/></td></tr>
</table>
</form>
</div>
here calling action as currentcundition.do. I think this is servlet program which naming as currentcondition.java. how to map this servlet program to my web application. please help I'm stuck here
This is my servlet code it named as currentcundition.java
#WebServlet(name = "currentcondition", urlPatterns = {"/currentcondition.do"})
public class currentcondition extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String disease= request.getParameter("disease");
String abedisease= attributebasedencryption.getattributebasedencryptionInstance().stringToHex(disease);
request.setAttribute("abedisease", abedisease);
RequestDispatcher go = request.getRequestDispatcher("/savecurrentcondition.jsp");
go.forward(request, response);
}
Edit:
my web.xml code
<servlet>
<servlet-name>PHP</servlet-name>
<servlet-class>com.controller.currentcondition</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PHP</servlet-name>
<url-pattern>/PHP/currentcondition.do</url-pattern>
</servlet-mapping>
It is not showing what what I'm expecting. please guide me
If you could use annotations like this
#WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
//your code
}
on your servlet code, then you can directly define the action="loginServlet"
Your code should be in doPost instead of processRequest method, as doPost will be called because you are using method="post" in your form.

Java Servlet supports POST, but form returns an error anyhow

I have a form that calls the post method in a servlet. I keep getting the "HTTP Status 405 - HTTP method POST is not supported by this URL" error, but I have been staring at it for a long time now and I can't see what is wrong. I have overidden the doPost method.
This is the form from my JSP
<%-- View all Users Section --%>
<div class="generalDisplay" id="AllUsers">
<table class="generalTable">
<tr>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
<th>User Power</th>
<th></th>
<th></th>
</tr>
<c:forEach var="user" items="${AllUsers}" varStatus="loopStatus">
<form method="post" action="UserEditServlet">
<tr class="${loopStatus.index % 2 == 0 ? '' : 'alt'}" id="${user.userName}">
<td>${user.userName}<input type="hidden" value="${user.userName}" name="userName" /></td>
<td><input class="hidableButton" disabled type="text" name="FirstName" value="${user.firstName}"</td>
<td><input class="hidableButton" disabled type="text" name="LastName" value="${user.lastName}"</td>
<td><input class="hidableButton" disabled type="text" name="UserPower" value="${user.userPower}"</td>
<td class="buttonColumn"><button type="button" id="EditChangesButton" class="openInputFields">Edit User</button></td>
<td class="buttonColumn"><button class="hidableButton" disabled id="SaveChangesButton" type="submit">Save Changes</button></td>
</tr>
</form>
</c:forEach>
</table>
</div>
This is my Servlet
package cellar.servlets;
import cellar.models.User;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserEditServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Checks for user first
HttpSession session = request.getSession();
User user = (User) session.getAttribute("User");
if((user != null) && (user.getUserPower() == 1 )) {
// user loged in, so continue
User UserChanged = new User();
UserChanged.setUserFromDB(request.getParameter("userName").toUpperCase());
UserChanged.changeThisUser(request.getParameter("FirstName"), request.getParameter("LastName"), Integer.parseInt(request.getParameter("UserPower")));
String url = "/RefreshAdminMenu";
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = "/index.jsp";
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
And here is the pertinent lines from my web.xml
<session-config>
<servlet>
<servlet-name>UserEditServlet</servlet-name>
<servlet-class>cellar.servlets.UserEditServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserEditServlet</servlet-name>
<url-pattern>/UserEditServlet</url-pattern>
</servlet-mapping>
</session-config>
Any input you can help would be great. I am struggling with this today. This app is fairly large now and this is the only function that isn't working. I have a similar screen to edit another DB object and it works fine. Thanks a lot for your help.

Put name into a list on the same HTML file with servlet

I use a html page with a textfield where you have to enter your name and then click on a login button.
On the same page is a list with all names.
Now I have to send the name by clicking on the login button to a servlet. The servlet have to add the name into the playerlist.
The servlet already receives the entered name but it post it on hole new HTML page. How do I have to change the code so that name will be added to playerlist on the same HTML page not on new page?
#WebServlet("/Playerlist")
public class Playerlist extends HttpServlet {
private static final long serialVersionUID = 1L;
public Playerlist() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println("<html><Body>Hallo" + name + "</body></html>");
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
Textfield:
<div id= "loginFormular" >
<form action="Playerlist" method="get" >
<label>
Name:
<input class="textbox" id="loginbox" type="text" name="name" size="30" maxlength="30">
</label>
<br>
<input id=buttonLogin class="loginbutton" type="submit" value="Login" name="loginname" />
<input id=startButton class="loginbutton" type="submit" value="Start" onclick="showQuestion()" />
</form>
</div>
Playerlist:
<div class="highscore" style="float:right">
<h4>
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
<span>Highscore</span>
</h4>
<hr/>
<table id="highscoreTable" class="table table-hover">
<thead>
<tr>
<td>Player</td>
<td>Score</td>
</tr>
</thead>
<tbody id="tablePlayerlistBody">
</tbody>
</table>
</div>
I konw there are better ways instead of using a servlet, but I have to it this way.
Your page is too static for what you want to do. I am assuming that you are doing this for practice.
What you are doing is
submitting your name from a static page.
Getting the submitted name on servlet side.
Sending new content to client.
Instead what you need to do is
Create a dynamic page (JSP) with a text field and list.
Submit the field value to servlet.
Receive the value and persist it on server side. Maintain some type of list on server side and add this value to it and set it on either of the servlet contexts.
redirect to the same page using request dispatcher and then iterate over the list of values maintained on server side.
Something as below.
Servlet
String name = request.getParameter("name");
serverSideList.add(name );
JSP
<table id="highscoreTable" class="table table-hover">
<thead>
<tr>
<td>Player</td>
<td>Score</td>
</tr>
</thead>
<tbody id="tablePlayerlistBody">
<% for(int i=0 ; i< serverSideList.size(); i++){ %>
<tr>
<td>
<%=serverSideList.get(i)%>
</td>
<td>Some Score</td>
</tr>
<%}%>
</tbody>
</table>
For persisting you can do two things.
Simple : Maintain server side list in Application Context
Standard : Persist player detail in database.
Please feel free to ask if you have any questions.

httpservlet parameter are null [duplicate]

This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}

JSP Servlet displaying inexisting data

I created a simple servlet which was printing some message like this:
#WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello there");
}
Everything worked well.
Then i created 2 jsp pages like this:
<body>
<form method="post" action="servletExample">
<table border="0">
<tr>
<td>
First name:
</td>
<td>
<input type="text" name="firstname"/>
</td>
</tr>
<tr>
<td>
Last name:
</td>
<td>
<input type="text" name="lastname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
and
<body>
<%
String firstName = (String)request.getAttribute("firstname");
String lastName = (String)request.getAttribute("lastname");
out.println(firstName+ " "+lastName);
%>
</body>
The servlet looks like this now:
#WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
if(firstName == null || lastName==null){
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
request.setAttribute("firstname", firstName);
request.setAttribute("lastname", lastName);
getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
}
}
When i run it i see that form but when i submit i see "Hello there" from the example i did 2 days ago. Whatever i do i see that.
What do i have to clean?
What am i missing?
Edit: I use eclipse and tomcat 7
Assuming you are in Eclipse, stop your Tomcat server, select your project, in Eclipse's menu select Project and Clean and then Build Project. Then restart your Tomcat server and try again.
Eclipse uses the last built project version with Tomcat every time you run. You need to clean up the project and rebuild it for Eclipse and Tomcat to refresh the changes.

Categories

Resources