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
Related
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.
So this is my project:
Where Registro.java is:
package Ejer2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And registro.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
When I run registro.html everything goes as expected:
But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:
What can be the problem?
I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
<servlet-name>RegistroServlet</servlet-name>
<servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistroServlet</servlet-name>
<url-pattern>/Registro</url-pattern>
</servlet-mapping>
I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem
This question already has answers here:
How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?
(16 answers)
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I'm using Tomcat8 server and i'm getting following error.
It's url is http://localhost:8080/WeatherWebApp When i'm submitting the details then it's giving this error.
Here is WeatherServlet.java class
package org.akshayrahar;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
WeatherServlet(){
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Here is web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee">
<display-name>WeatherWebApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>
</web-app>
Here is index.html file too:-
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script >
function initMap() {
var input =document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACZhmkSaIz436Dt3kHt_cVEYKN-gHzfYo&libraries=places&callback=initMap"async defer></script>
</head>
<body>
<h1>Find weather of any city in the world</h1>
<h2>Enter City Name</h2>
<form id="form" action="CurrentWeather" method="GET">
<input id="pac-input" type="text" name="cityname">
</form><br>
<div class="button1">
<button type="submit" form="form" value="Submit">Submit</button>
</div>
</body>
</html>
I've also mentioned stylesheet.css file in comment. Please check it.
The error shows that Tomcat is unable to create an instance of your WeatherServlet class.
You should make its constructor and other methods public too. You can even make use of the default constructor by removing the less accessible constructor:
public class WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WeatherServlet(){
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Please provide a fully qualified class name on your web.xml. I was facing a similar issue and this is what fixed it.
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>org.akshayrahar.WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>
I'm using Apache Tomcat v8.0 server and in Java EE application. Basically, I created an ResponseUpload servlet. I need to get JSON data from the web app through POST request. Here it is the code of the Servlet:
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RequestUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = request.getReader();
Gson gson = new Gson();
JSONObject json = gson.fromJson(reader, JSONObject.class);
uplRequest.upload(json);
PrintWriter out = response.getWriter();
out.print(json);
}
Then to test if it works I added a form to jsp file, doing POST to url:
http://localhost:8080/webApp/RequestUpload
The form:
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
But I got 404 error -
HTTP Status 404 - /webApp/RequestUpload
Can somebody show me where is my mistake?
My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>webApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
P.S. Another form doing the same with RPC servlet (which structure is similar) is working.
After a research and with help of previous answer I found the problem in build path. The build path image
I had to allow output folders for source folder and change the output folder from build to WEB-INF/classes.
Servlet Class:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<String, String>();
options.put("first_name", request.getParameter("first_name"));
options.put("last_name", request.getParameter("last_name"));
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
JSP:home.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
if your context root of the web app is webApp and server is running on port:8080. you can see the home.jsp as follows:
When data are given in first_name as Minhajur and last_name as Rahman, After clicking the submit button,
following json response will be returned:
Note: make sure that you have added the required jar dependencies in lib folder. For example: gson-1.7.1.jar exists in webapp/WEB-INF/lib folder.
Trouble Shooting:
HTTP Status 404 - /webApp/RequestUpload
-> Check whether your webApp has been compiled successfuly and your compiled RequestUpload.class has been existed on your webapp/WEB-INF/classes directory on tomcat server.
if RequestUpload.class does not exist, then
1) It has not been compiled successfully.
or
2) the Compiled class files has not been moved to webapp/WEB-INF/classes directory.
So, follows the following steps:
i) Clean your tomcat working directory and compile run again and check the class file is existed there.
ii) Delete and Add Tomcat server on eclipse again. then follow the previous steps.
You can also read for further references:
How to use Servlets and Ajax?
let me give you an idea about how the system works.
I am using JAAS login module for login and role management. I can access specific pages depending on the role i have.
I type my url in the address bar, hit enter.
The login page appears and after correct login, it redirects me to the correct page(for now lets call it page1.jsf).
I want to call a server side method on page load.
Can you help me please?
** EDIT **
Assume i have to access page1.jsf which is accessible to role1 only.
In the address bar, i type http://localhost:8080/myapp/page1.jsf
JAAS shows up the login page and after correctly inputting the credentials, i am redirected to page1.jsf
As soon as page1.jsf is requested or on page load, i want to call a server side method from my class to reload page1.jsf
If you are using JSF 2, you can use the above page snippet:
<html xmlns="http://www.w3.org/1999/xhtml"
... >
<f:view contentType="text/html">
<f:event type="preRenderView" listener="#{permissionManager.checkRoles}" />
<f:attribute name="roles" value="ROLE" />
...
</f:view>
</html>
you can add an attribute containing the role and in the PermissionManager.checkRoles() perform redirect to the corret page.
#Named
#ApplicationScoped
class PermissionManager {
...
public void checkRoles(ComponentSystemEvent event) {
String acl = "" + event.getComponent().getAttributes().get("roles");
//Check user role
...
//Redirect if required
try {
ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) context
.getApplication().getNavigationHandler();
handler.performNavigation("access-denied");
} catch (Exception e) {
...
}
}
}
Check out this example
and take a look at this related question
Yes this works. Instead of accessing a jsp or jsf page, you can also access Servlets. So create a new servlet. E.g.:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static void yourMethod() {
// do something useful
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
yourMethod();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Then create a new entry in the web.xml file, in order to map the Servlet to /.
<servlet>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>your.packages.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
After this, you should be able to call localhost:8080/TestServlet which then calls your method.