Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hi all I am new in servlet and jsp I am not clear with servletconfig interface and servletcontext interface I started jsp again I encounter the term PageContext.
So any body explain me these term with the nice example.
servletconfig interface and servletcontext interface and PageContext in jsp
ServletConfig
ServletConfig object is created by web container for each servlet to pass information to a servlet during initialization.This object can be used to get configuration information from web.xml file.
when to use :
if any specific content is modified from time to time.
you can manage the Web application easily without modifing servlet through editing the value in web.xml
Your web.xml look like :
<web-app>
<servlet>
......
<init-param>
<!--here we specify the parameter name and value -->
<param-name>paramName</param-name>
<param-value>paramValue</param-value>
</init-param>
......
</servlet>
</web-app>
This way you can get value in servlet :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//getting paramValue
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("paramName");
}
ServletContext
web container create one ServletContext object per web Application. This object is used to get information from web.xml
when to use :
If you want to share information to all sevlet, it a better way to make it available for all servlet.
web.xml look like :
<web-app>
......
<context-param>
<param-name>paramName</param-name>
<param-value>paramValue</param-value>
</context-param>
......
</web-app>
This way you can get value in servlet :
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String paramName=context.getInitParameter("paramName");
}
PageContext
Is class in jsp, its implicit object pageContext is used to set , get or remove attribute from following scope:
1.page
2.request
3.session
4.application
ServletConfig is implemented by GenericServlet (which is a superclass of HttpServlet). It allows the application deployer to pass parameters to the servlet (in the web.xml global config file), and servlet to retrieve those parameters during its initialization.
For example, your web.xml could look like :
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.company.(...).MyServlet</servlet-class>
<init-param>
<param-name>someParam</param-name>
<param-value>paramValue</param-value>
</init-param>
</servlet>
In you servlet, the "someParam" param can then be retrieved like this :
public class MyServlet extends GenericServlet {
protected String myParam = null;
public void init(ServletConfig config) throws ServletException {
String someParamValue = config.getInitParameter("someParam");
}
}
ServletContext is a bit different. It is quite badly named, and you'd better think of it as "Application scope".
It is an application-wide scope (think "map") that you can use to store data that is not specific to any user, but rather belongs to the application itself. It is commonly used to store reference data, like the application's configuration.
You can define servlet-context parameters in web.xml :
<context-param>
<param-name>admin-email</param-name>
<param-value>admin-email#company.com</param-value>
</context-param>
And retrieve them in your code like this in your servlet :
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String adminEmail = getServletContext().getInitParameter("admin-email"));
}
Related
Here I have some of my code examples
Servlet Class
private String welcomeNote;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
context.getBean("SomeServlet");
PrintWriter writer = response.getWriter();
writer.println(welcomeNote);
}
public void setWelcomeNote(String welcomeNote) {
this.welcomeNote = welcomeNote;
}
Spring-config.xml
<bean id="SomeServlet" class="SomeServlet">
<property name="welcomeNote" value="aasomdp" />
</bean>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Hello, I can't figure out how to inject welcomeNote property inside servlet class. When I deploy it and open it up in web browser it's always null, no matter what I do.
I am using plain Spring, not Spring MVC.
I'm learning Spring and web aspects of Java, so I must be missing something important. Thank you all for advice.
Use the following
SomeServlet sv = (SomeServlet)context.getBean("SomeServlet");
sv. setWelcomeNote(welcomeNote);
Using Spring you actually don't need any custom servlet. The only servlet you need is DispatcherServlet. Add #Controller annotated classes instead your servlet to process requests
I am new to java programming in the web environment and am having trouble understanding the flow.
For an assignment coming up I need to build a web application accessible with an API via get/post requests. For the tutorials that I have followed here is the flow I understand.
User visits top domain->
Per configuration user is directed to a jsp page->
Jsp contains javascrip and html. To access server code (for database, computations and other processes) the jsp page can use RCP to make async requests to a java servlet->
Java servlet does server handling and returns response to jsp page
Is this the required flow or can a user directly acess a servlet, and can that servlet handle get/post, or do I have to handle at the jsp and foward to the servlet?
Servlets can be accessed directly. You just need to extend HttpServlet and implement doGet and/or doPost. For example:
public class MyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
Integer param = null;
try {
param = Integer.parseInt(req.getParameter("param"));
}
catch(NumberFormatException e) {
}
}
}
You also need to map your servlet to url in web.xml:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.adam.test.server.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/my_servlet</url-pattern>
</servlet-mapping>
Now you can access your servlet using url like this:
http://domain.com/my_servlet?param=123
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to java, I just tried to read initialization parameters from Deployment Descriptor file (web.xml), But got above error?
My web.xml and java file coding coding in snap attached.
My directrory structure is
c:\....tomcat\webapps\dd\web-inf\classes
No error in java class file.
Java file code which is compiled successfully
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
String fileName;
public void init(ServletConfig config) throws ServletException {
super.init(config);
fileName = config.getInitParameter("logfilename");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(fileName);
out.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
<init-param>
<param-name>logfilename</param-name>
<param-value>value1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/mc11</url-pattern>
</servlet-mapping>
</web-app>
Other detail of my directory and error page i think that my web.xml not working
There are two problems I can see at the moment...
Servlet init parameters
You currently have:
//defining param1
param1
value1
That's not how you define the parameter. You should specify a param-name element containing the name of the parameter, rather than using the name of the parameter as an XML element name.
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
Also note that // isn't how you write comments in XML - if you wanted a comment, you should have:
<!-- Define the first parameter -->
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
(The param-value element should have been a hint - if you could really just specify your own element, I'd have expected <logfilename>value in here</logfilename> - having the name specified as an element name, but the value specified with a fixed element name of param-value would have been an odd scheme.)
Servlet mapping
Currently your mapping is:
<servlet-name> FormServlet</servlet-name>
<url-pattern>/ss/</url-pattern>
</servlet-mapping>
I suspect that mapping won't match http://localhost:8080/dd/ss/s.html because you don't have any wildcards in there - it you may well find that it matches exactly http://localhost:8080/dd/ss/. It's not clear where the dd part comes in, but I assume that's a separate part of your configuration. You should try:
<!-- I would recommend removing the space from the servlet
- name *everywhere*. -->
<servlet-name>FormServlet</servlet-name>
<url-pattern>/ss/*</url-pattern>
</servlet-mapping>
If that doesn't work for http://localhost:8080/dd/ss/s.html, see whether it maps http://localhost:8080/ss/s.html - it may be that your engine isn't configured the way you expect elsewhere.
There is no problem with code,I try net beans tool and done assignment perfectly with the help of above code.Before that may be problem in tomcat.
this is my first time that I work on a Java project that use HttpServlet.
So I know that an HttpServlet is a program that run on a Web Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. So the servlet extend the competence of my application server.
I have some doubt to understand how exactly work this servlet founded into my project, into web.xml file I found this configuration:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>My Project</display-name>
<listener>
<listener-class>it.sistinf.ediweb.quartz.QuartzListener</listener-class>
</listener>
<servlet>
<servlet-name>edimon</servlet-name>
<servlet-class>it.sistinf.ediweb.monitor.servlets.Monitoraggio</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>edimon</servlet-name>
<url-pattern>/edimon.do/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/logon.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>displaytag</taglib-uri>
<taglib-location>/WEB-INF/displaytag-11.tld</taglib-location>
</taglib>
</web-app>
So reading some documentation it seem to understand that I have to tell the servlet container (or application server) what servlets to deploy, and what URL's to map the servlets to.
In the previous case I am configuring a servlet named edimon implemented by the Monitoraggio class.
Then it is mapped the servlet to a URL or URL pattern. In this case the edimon servlet is mapping with the /edimon.do/* URL pattern. So when it is called something that match with the previous pattern the edimon servlet is performed.
Then into my Monitoraggio class that implement the HttpServlet I found the service() method:
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
LoggerMDC.setup(req, res);
Logger logger = (Logger) Logger.getStdLogger(Monitoraggio.class); // do not declare 'logger' as static field in order to work with MDC
String service = req.getParameter("serv");
char serviceId = Utility.getServizio(req.getParameter("serv"));
if (checkSession(req, serviceId) == false) {
gotoPage(ConfigurationFactory.getPropertiesPages().getProperty("pagina_errore_session"), req, res);
return;
}
LoggerWatch loggerWatch = new LoggerWatch(Monitoraggio.class, Long.valueOf(System.getProperty(Constants.Keys.CONFIG_STATS_WARNING_THRESHOLD, String.valueOf(LoggerWatch.DEFAULT_WARNING_THRESHOLD))).longValue());
if (logger.isTraceEnabled())
logger.trace("lanciaServizio() | logger threshold: " + loggerWatch.getWarningThreshold());
loggerWatch.start();
loggerWatch.info(new StringBuffer("service() | servizio: [").append(service).append("] | service start").toString());
String paginaDaLanciare = lanciaServizio(serviceId, req, res);
String executionTime = loggerWatch.getInfoTime();
//Modifica per export
if (req.getSession().getAttribute("export") == null) {
gotoPage(paginaDaLanciare, req, res);
}
loggerWatch.info(new StringBuffer("service() | servizio: [").append(service).append("] | [").append(executionTime).append("] after forward to ").append(paginaDaLanciare).toString(), true);
loggerWatch.stop();
req.getSession().removeAttribute("export");
req.getSession().removeAttribute("stringaXML");
req.getSession().removeAttribute("downbyte");
return;
}
Reading on the documentation it receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class
So what exatly do this method? I can't understand how the servlet load the JSP
The documentation you read describes what the service() method of HttpServlet does by default. Since your servlet overrides the service() method and provides a different implementation, it doesn't do that anymore. Instead, it does... what the code in the method does.
A servlet doesn't "load a JSP". I don't see how JSPs have any relation to the servlet code you posted. Maybe gotoPage() does tell the container to forward the request to a JSP. You should look at the documentation and/or code of that method to know what it does.
I would like to have URL mappings that I'm having with spring framework like below in standard servlet web.xml configuration.
#RequestMapping(value="/students/{username}", method=RequestMethod.GET)
public String deleteSpitter(#PathVariable String username) {
...
...
}
I would like URL mappings like these two:
/students/Mike
/students/John
to be mapped to same servlet where I can also read "Mike" and "John" as parameters somehow. If it can be extended to more than one level like the example below it could be very much useful for me:
/students/{schoolname}/{studentname}
like:
/students/mcgill/mike
/students/ubc/john
You can map a standard servlet to a wildcard path and access the pathInfo part of the request using the HttpServletRequest.getPathInfo() method.
The servlet should get the path info like this
package com.acme;
public class TestServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String info = request.getPathInfo();
}
}
and you should map the servlet in your web.xml like this
<servlet>
<servlet-name>test-servlet</servlet-name>
<servlet-class>com.acme.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test-servlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
If you request the URL '/test/mcgill/mike' the path info will be '/mcgill/mike'. Parsing the path info is up to you.
If you work with a Java EE 6 compliant container you should also take a look at the JAX-RS specification to build RESTful web services.
Check out UrlRewriteFilter: http://www.tuckey.org/urlrewrite/
In the examples at http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/guide.html look at the "Clean a URL" example.
JAX-RS (aka Jersey) can do something like this with a servlet app (although not just servlets)