Populating string property of Servlet using Spring - java

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

Related

how to load servlet from main method

I have Main class, there I doing api request and integrate with database.
I also create servlet where I want to get data from clients and put it in database.
it is the main method in Main class:
public static void main(String[] args) throws IOException {
serverSocket = new ServerSocket(8888); // Server port
System.out.println("Server started. Listening to the port 8888");
initProviderList();
initNewsAppDB();
Thread newFeedsUpdate = new Thread(new NewFeedsUpdate(providerList));
newFeedsUpdate.start();
}
it is the servlet:
#WebServlet(name = "GetClientTokenServlet")
public class GetClientTokenServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String token = request.getParameter("token");
System.out.println(token);
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>GetClientTokenServlet</servlet-name>
<servlet-class>GetClientTokenServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetClientTokenServlet</servlet-name>
<url-pattern>/GetClientTokenServlet</url-pattern>
</servlet-mapping>
</web-app>
how I can setup the GetClientTokenServlet (to be able listen to clients calls) into main method?
In most cases web applications in Java don't have main methods. The main method is implemented by a servlet container, such as Tomcat, and that's what you actually run. The servlet container discovers your application's classes and web.xml through some method, often by finding them in a WAR file that you have dropped in a directory defined by the servlet container, such as Tomcat's webapps directory. The servlet container then instantiates the servlets identified in your web.xml file.
That said, there are some web servers that you can instantiate as components within your own application. A server that is commonly used for this purpose is Jetty. Jetty is a web server that passes incoming requests to "handlers" that you define. You can have Jetty load your entire web application from your WAR file and instantiate the servlets defined in your web.xml, or you can use ServletHandler to register servlets manually; in this case you don't need web.xml.

why do we use servletconfig interface and servletcontext interface [closed]

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"));
}

What exactly do the service() method of this HttpServlet?

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.

How can I map Spring or RESTful like URLs using standard servlets and web.xml

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)

Java Servlet: pass a request back to default processing

I want a Servlet to handle requests to files depending on prefix and extension, e.g.
prefix_*.xml
Since mapping on beginning AND end of request path is not possible, I have mapped all *.xml requests to my Servlet.
The question now is: how can I drop out of my servlet for XML files not starting with "prefix_", so that the request is handled like a "normal" request to an xml file?
This is probably quite simple but I do not seem to be able to find this out... :-/
Thanks a lot in advance
another solution (maybe fits for you) is if you are using/plan to use an Apache in front of that web container instance you could use the rewrite module of apache. Rewriting the url to something more easy to handle for the Webapp container.
Hope this helps.
David.
I would strongly suggest using a proper MVC framework for this. As you've discovered, the flexibility of the standard servlet API is very limited when it comes to request dispatching.
Ideally, you would be able to use your existing servlet code in combination with an MVC framework, with the framework doing the diapcthing based on path pattern, and your servlets doing the business logic. Luckily, Spring MVC allows you to do just that, using the ServletForwardingController. It'd be a very lightweight spring config.
So you'd have something like this in your web.xml:
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>foo.MyServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<url-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*</url-pattern>
</url-mapping>
You would then have a WEB-INF/spring-servlet.xml file like this:
<beans>
<bean name="/prefix*.xml" class="org.springframework.web.servlet.mvc.ServletForwardingController">
<property name="servletName" value="myServlet"/>
</bean>
</beans>
And that would be pretty much it. All requests for /prefix*.xml would go to myServlet, and all others would fall through to the container.
Not shure, but once you catch all *.xml requests you can inspect the request again in your code via HttpServletRequest.getRequestURI()
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri =req.getRequestURI();
int i = uri.lastIndexOf('/');
int j = uri.lastIndexOf('.', i);
if (uri.substring(i+1, j).startsWith("prefix_")) {
// your code
}
}
(code not tested, only an idea ...)

Categories

Resources