I'm trying to load some init-param values into a serevlet through the web.xml file but they keep showing up null. I do have two context-param's that work fine. Does anyone know what I'm doing wrong?
This is the web.xml file that I'am using for my application.
<?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_3_1.xsd"
version="3.1"
>
<display-name>Hello World Application</display-name>
<servlet>
<servlet-name>contextxParameterServlet</servlet-name>
<servlet-class>com.wrox.HelloServlet</servlet-class>
<init-param>
<param-name>database</param-name>
<param-value>CustomerSupport</param-value>
</init-param>
<init-param>
<param-name>server</param-name>
<param-value>10.0.12.5</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>contextxParameterServlet</servlet-name>
<url-pattern>/contextParameters</url-pattern>
</servlet-mapping>
<context-param>
<param-name>settingOne</param-name>
<param-value>foo</param-value>
</context-param>
<context-param>
<param-name>settingTwo</param-name>
<param-value>bar</param-value>
</context-param>
<servlet>
<servlet-name>servletParameterServlet</servlet-name>
<servlet-class>com.wrox.initParams</servlet-class>
<init-param>
<param-name>database</param-name>
<param-value>CustomerSupport</param-value>
</init-param>
<init-param>
<param-name>server</param-name>
<param-value>10.0.12.5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>servletParameterServlet</servlet-name>
<url-pattern>/servletParameter</url-pattern>
</servlet-mapping>
</web-app>
This is page mapped to servletParameterServlet.
package com.wrox;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
public class initParams extends HttpServlet{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ServletContext c = this.getServletContext();
PrintWriter writer = response.getWriter();
Enumeration<String> temp = c.getInitParameterNames();
while(temp.hasMoreElements()) {
writer.append(temp.nextElement());
}
writer.append("database: ").append(c.getInitParameter("database"))
.append(", server: ").append(c.getInitParameter("server"));
}
#Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
System.out.println("Servlet " + this.getServletName() + " has started.");
}
#Override
public void destroy() {
System.out.println("Servlet " + this.getServletName() + " has stopped.");
}
}
The way you have initialized things, I think what you are looking for should be available in
this.getServletConfig().getInitParameter("foo");
Broadly speaking the servlet context is shared by servlets inside a JVM but this object is present inside servlet config for a particular servlet, while <init-param> go in ServletConfig.
For more details I would strongly suggest to read the docs.
Related
I have just picked up web development and I cannot for the life of me figure out what I'm doing wrong when mapping the SimpleServlet in web.xml
these are my files:
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>JavaHelloWorldApp</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>
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>wasdev.sample.servlet.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>
</web-app>
Simple Servlet
package wasdev.sample.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SimpleServlet
*/
#WebServlet("/SimpleServlet")
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().print("Hello World!");
}
}
I am simply trying to get a local host running and access the JavaHelloWorldApp/SimpleServlet
I work with Spring MVC 3.2.6.RELEASE and weblogic 10.3.6 and Eclipse Juno
When I execute the application I want to go a controller and get a jsp.
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>eusurveyadmin</display-name>
<servlet>
<servlet-name>eusurveyadmin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/eusurveyadmin-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>eusurveyadmin</servlet-name>
<url-pattern>/eusurveyadmin/*</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API</taglib-uri>
<taglib-location>/WEB-INF/Content/esapi.tld</taglib-location>
</taglib>
</jsp-config>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>file:ecalcpAdminlog4j.xml</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>propertiesConfigLocation</param-name>
<param-value>file://C://OEPEJUNO//user_projects//domains//test38//configuracion.properties</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.CustomContextLoaderListener
</listener-class>
</listener>
<error-page>
<error-code>500</error-code>
<location>/500</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
</web-app>
Controller is WelcomeController.java
package eusurvey.controller;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import eusurvey.modelA.daos.Preferencia;
import eusurvey.services.PreferencesService;
#Controller
#RequestMapping("/welcome")
public class WelcomeController extends ExceptionsController {
private static final Logger logger = Logger
.getLogger(WelcomeController.class);
#Resource(name = "preferencesService")
private PreferencesService preferencesService;
private int a = 0;
private Preferencia results = null;
#ModelAttribute("Preferencia")
public Preferencia fechaUltimaEncuesta() {
results = preferencesService.consultaPreferencia();
return results;
}
#RequestMapping(value = "/*")
public String welcome(HttpServletRequest request, ModelMap model) {
logger.info("WelcomeController welcome");
results = fechaUltimaEncuesta();
model.addAttribute("fechaUltimaEncuesta", results.getValor());
request.getSession().setAttribute("fechaUltimaEncuesta",
results.getValor());
String fechaUltimaEncuesta = (String) request.getSession()
.getAttribute("fechaUltimaEncuesta");
//return "welcome1";
return "/menu/pantallaInicio";
}
#ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e, Locale locale, HttpServletRequest request) {
logger.error("WelcomeController handleException "+e.getLocalizedMessage()+" exception "+ e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String mensajeException = sw.toString();
logger.error("WelcomeController handleException exception "+e.getClass().getSimpleName()+" mensaje "+mensajeException );
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName("errores/errorGeneral");
return mav;
}
}
When I run the applicacion I get the error
This is my weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app
xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.3/weblogic-web-app.xsd">
<wls:weblogic-version>10.3.6</wls:weblogic-version>
<wls:context-root>EcalpAdmin</wls:context-root>
<wls:container-descriptor>
<wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
</wls:container-descriptor>
</wls:weblogic-web-app>
How do I have to write my web.xml to go the controller?
It appears that your RequestMapping at the class level is /welcome. Any method level RequestMapping will be relative to that. So your URL should be http://localhost/EcalpAdmin/welcome.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Actually this is my first servlet application.just getting started..
below is my code:
package newpackage.org;
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;
//#WebServlet(description = "a general servlet", urlPatterns = {
"/simpleservlet" })
public class simpleservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServletdoGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doget(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter obj= response.getWriter();;
// String username= request.getParameter("username");
obj.println("again getting back with ");
}
}`
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>myproject</display-name>
<servlet-mapping>
<servlet-name>xmlservlet</servlet-name>
<url-pattern>/002path</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>xmlservlet</servlet-name>
<servlet-class>newpackage.org.xmlservlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>simpleservlet</servlet-name>
<url-pattern>/001path</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>simpleservlet</servlet-name>
<servlet-class>newpackage.org.xmlservlet </servlet-class>
</servlet>
</web-app>
ERROR:
HTTP Status 404 - /myproject/servlet/newpackage.org.simpleservlet
type Status report
message /myproject/servlet/newpackage.org.simpleservlet
description The requested resource is not available.
Apache Tomcat/7.0.72
You need to remove the below in web.xml
<servlet-mapping>
<servlet-name>simpleservlet</servlet-name>
<url-pattern>/001path</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>simpleservlet</servlet-name>
<servlet-class>newpackage.org.xmlservlet </servlet-class>
</servlet>
And use the below code in servlet:
#WebServlet(description = "a general servlet", urlPatterns = {"/simpleservlet", "/001path" })
<servlet-name>simpleservlet</servlet-name>
<servlet-class>newpackage.org.xmlservlet </servlet-class>
</servlet>
Give simpleservlet class name instead of xmlservlet
<servlet-name>simpleservlet</servlet-name>
<servlet-class>newpackage.org.simpleservlet </servlet-class>
</servlet>
I am trying to convert my servlet-context.xml file to Servlet Config.java and there is no compile time error. But at run time, my server shows that no request mapping for /product/.
My web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocatation</param-name>
<param-value>com.mds.test.ServetConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
and my ServletConfig is:
package com.mds.test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages={"com.mds.test"})
#EnableWebMvc
public class ServletConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver internalResourceViewer(){
InternalResourceViewResolver irvr= new InternalResourceViewResolver();
irvr.setPrefix("/WEB-INF/views/");
irvr.setSuffix(".jsp");
return irvr;
}
#Bean(name="multipartResolver")
public ExtendedMultipartResolver resolver(){
return new ExtendedMultipartResolver();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Can you tell what I am missing. Thanks in advance
Sorry guys, I was doing a very little but confusing mistake. I was writing wrong class name. Class name should be com.mds.test.ServletConfig not the com.mds.test.ServetConfig in web.xml
So guys you can take it as a simple converter from xml to java file.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletConfig1 extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException ,IOException{
PrintWriter pw = res.getWriter();
ServletConfig cfg = getServletConfig();
String myname = cfg.getInitParameter("myname");
pw.print("my name is"+myname);
System.out.println("hello");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletConfig</display-name>
<servlet>
<servlet-name> ServletConfig1</servlet-name>
<servlet-class>ServletConfig1</servlet-class>
<init-param>
<param-name>myname</param-name>
<param-value>saurabh</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletConfig1</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
while running this servletconfig example i am getting http get method is not supported even though i have used post method in my application.what could be the reason?
change the public void doPost(HttpServletRequest req,HttpServletResponse res) to public void doGet(HttpServletRequest req,HttpServletResponse res).