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.
Related
Goal:
I have only one page and when page loads, it should run the query from servlet and display all values on index.jsp page.
Existing problem:
when i am submitting the page from "Submit" button to another page, it works fine but when i load page index.jsp with values, its gives NullPointerException because servlet didn't run before the index.jsp page.
My Servelet:
public class GetStudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao sd = new StudentDao(); // model
StudentInfo si = sd.getInfo();
request.setAttribute("si", si);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
my JSP:
<body>
<form action="displayStud"> <--my servlet controller name -->
Student id <input type="text" name = "sid">
<button name="test" type="submit"">Primary Button</button>
</body>
</html>
<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
<!-- <input type ="submit" value ="Submit"> -->
</form>
StudentDao has query in there
Again:
I just want it to run the same code on page load and all data should load(without click on submit)
Thanks for the help
You can use the value set in the request scope using jstl or expression language.
request.setAttribute("si", si);
Something like:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");
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.
I am trying to create a login service but my pages are not redirecting properly. I have following:
login.jsp
<form action="login" method="post">
User Name
<br>
<input type="text" name="userId"/>
<br><br>
Password
<br>
<input type="password" name="password"/>
<br><br>
<input type="submit"/>
</form>
LoginServlet.java
package org.sohail.javabrains;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId, password;
userId=request.getParameter("userId");
password=request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if (result) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java - has a authenticate(userId, password) method which connects to database, verifies userId and pass and returns a boolean value.
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.sohail.javabrains.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
from login.jsp page, doesn't matter what I put I get following error:
HTTP Status 404 - /LoginApp/login
It should redirect the page to success.jsp if authenticate() reutrns true.
I am pretty new to this so please feel free to provide any other suggestions.
Thank you Birgit Martinelle for following answer:
change your web.xml servlet mapping to
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and remove the WEB-INF part from your redirect url:
RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
– Birgit Martinelle 50 mins ago
I am new to programming and i have written two pieces of code to learn urlrewriting in servlet:
My html form is :
<form action="loginhidden" method="get">
Login ID:<input name="login" ><br>
Password:<input name="pass" type="password"><br>
<input type="submit" >
</form>
My web.xml file is :
<web-app>
<servlet>
<servlet-name>loginhidden</servlet-name>
<servlet-class>loginhidden</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden</servlet-name>
<url-pattern>/loginhidden</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loginhidden1_name</servlet-name>
<servlet-class>loginhidden1_name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden1_name</servlet-name>
<url-pattern>/loginhidden1_name/*</url-pattern>
</servlet-mapping>
</web-app>
The pieces of code are as follows:
1.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String login= req.getParameter("login");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
out.println(login);
out.println(pass);
out.println("<html><head><form action=loginhidden1_name?
mylogin="+login+">");
out.println("Your Name:<input type=text name=myname><br>");
out.println("<input type=submit>");
out.println("</body></head></html>");
}
}
}
2.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden1_name extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res )throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(req.getParameter("mylogin"));
out.println(req.getParameter("myname"));
}
}
I am able to get the value of name in my second servlet(loginhidden1_name) but i am not able to get the value of login id("mylogin") through urlrewriting.I am getting null value for it.Please Help.
Thanks a lot in Advance.
If you're just looking to transfer control from one servlet to another, it's a simple matter of forwarding the request to the other servlet. A "forward" in this case does not go back to the client.
In your original servlet, at the end, you'll want to get a RequestDispatcher, and forward to the new URL.
e.g.
getServletContext().getRequestDispatcher("/modified/url").forward(request, response);
The thread of control will transfer to the other servlet. IIRC, you will still finish out the method call in the first servlet. i.e. it doesn't return from your method and then call the other servlet.
You can take advantage of this if you need post processing of the request for some reason. Although a ServletFitler would be a more appropriate way to handle this case.
You cannot can use URL rewriting in a form action. Any parameters after ? will be dropped by the browser. Instead you can add the login as a hidden form field in your second form:
...
out.println("<input type=hidden name=\"mylogin\" value=\""+login+"\">");
...
This will be passed through to your second Servlet in the same way as the other fields.
See submitting a GET form with query string params and hidden params disappear