Problem in Context Listener - servlets

I was trying to run a servlet using ServletContextListener ,I've put the codes from the book
"Head-First" writter "Kathy sierra", but this is not working.Its shows 404 error.I have put the class files in the directory C:\Tomcat 5.5\webapps\Listener_exe\web-inf\classes\com\example. and web.xml file in web-inf directory. So please show where I have
done wrong. Here are the servlet, java files, and xml file.`
package com.example;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ListenerTester extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>test context attributes set by listener<br>");
Dog dog = (Dog) getServletContext().getAttribute("dog");
out.println("Dog's breed is: "+dog.getBreed()+</body></html>);
}
}
package com.example;
public class Dog
{
private String breed;
public Dog(String breed)
{
this.breed=breed;
}
public String getBreed()
{
return breed;
}
}
package com.example;
import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext sc = event.getServletContext();
String dogBreed = sc.getInitParameter("breed");
Dog d = new Dog(dogBreed);
sc.setAttribute("dog",d);
}
public void contextDestroyed(ServletContextEvent event)
{}
}
<web-app>
<servlet>
<servlet-name>ListenerTester</servlet-name>
<servlet-class>com.example.ListenerTester</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListenerTester</servlet-name>
<url-pattern>/ListenerTester</url-pattern>
</servlet-mapping>
<Context-param>
<param-name>breed</param-name>
<param-value>Great Dane</param-value>
</Context-param>
<listener>
<listener-class>
com.example.MyServletContextListener
</listener-class>
</listener>
</web-app>

Did you use the correct URL to reach the page? Your URL should be something like,
http://localhost:8080/Listener_exe/ListenerTester
Use whatever hostname or port number you set for your connector.

Related

Spring Security Configuration for POST request

I have configured spring security in my Rest API.I have three controller methods. One uses GET and other two use POST.
Now, I have used basic authentication.
The problem is that the security is working fine for GET request but not for the POST requests.
I am always getting 403 Forbidden response for the requests when POST method is used.
Controller class:
package com.base.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.base.model.User;
import com.base.service.UserService;
#RestController
public class CountryController {
#Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
#RequestMapping(value = "/user123", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.ALREADY_REPORTED)
public User postUser(#RequestBody #Valid User user) {
System.out.println("Fetching User with id " + user.getId());
user.setName("Tou added");
return user;
}
}
Security Config:
#Configuration
#EnableWebSecurity
#ComponentScan("com.base.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
MyUSerService userService;
#Autowired
public void configureGlobalAuth(final AuthenticationManagerBuilder auth)throws Exception{
auth.userDetailsService(userService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
MyUserService (to provide the usename and password)
#Service
public class MyUSerService implements UserDetailsService{
#Override
public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
// TODO Auto-generated method stub
List<SimpleGrantedAuthority> authoriities = new ArrayList<SimpleGrantedAuthority>();
authoriities.add(new SimpleGrantedAuthority("WRITE"));
return new User("ayush","ayush123",authoriities);
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.base.config</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I am using 'Google Advanced Rest Client'.
You need to disable CRSF. CRSF is enabled by default in spring security 4.
http.csrf().disable()
or send the request with CRSF token.
In Spring Security 4.0, CSRF protection is enabled by default with XML configuration. You have to disable CSRF protection, the corresponding XML.
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
Or you to disable in Java configration file in code base by following
http.csrf().disable();

Test case for testing a jersey web resource using grizzle is giving me 404

I tried below way which is working fine
package test;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import com.mkyong.rest.HelloWorldService;
public class HelloWorldServiceTest extends JerseyTest{
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
#Test
public void testSingleNode() throws Exception {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}
When i tried to replace the resource with resource which is outside of this test class and package like below
package test;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import com.mkyong.rest.HelloWorldService;
public class HelloWorldServiceTest extends JerseyTest{
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloWorldService.class);
}
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
#Test
public void testSingleNode() throws Exception {
final String hello = target("hello").path("Test").request().get(String.class);
assertEquals("Jersey say : Test", hello);
}
}
HelloWorldService.java
package com.mkyong.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/hello")
public class HelloWorldService {
#GET
#Path("/{param}")
#Produces(MediaType.APPLICATION_JSON)
public Response getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
RestApplication.java
package rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.mkyong.rest.HelloWorldService;
public class RestApplication extends Application{
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(HelloWorldService.class);
return s;
}
}
web.xml
<web-app id="WebApp_ID" 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
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>rs-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>rest.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>rs-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I got an exception
javax.ws.rs.NotFoundException: HTTP 404 Not Found
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:917)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:423)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
at test.HelloWorldServiceTest.testSingleNode(HelloWorldServiceTest.java:48)
Can any one correct me where i went wrong...
Look at this
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
The forPackages is saying what package to scan for #Path and #Provider annotated classes, and automatically register them. The reason it works in the first example is that the resource class (the class annotated with #Path is in the getClass().getPackage().getName() package.
This method
#Override
protected Application configure() {
return new ResourceConfig(HelloWorldService.class);
}
is never called, because you override the getDeploymentContext(). Normally, if you don't override that method, it will call the configure method to register the application with the deployment context. But you neve do this.
So instead of the forPackages, you should use one of the ServletDeploymentContext.builder methods, that accept an Application class
return ServletDeploymentContext.builder(configure()).build()
return ServletDeploymentContext.builder(RestApplication.class).build();
OR
#Override
public ResourceConfig configure() {
return new ResourceConfig(HelloWorldService.class);
}
#Override
public ServletDeploymentContext configureDeployment() {
return SerlvetDeploymentContext.forServlet(new ServletContainer(configure));
}
One thing to note it that you only need to override the getTestContainerFactory and the configureDeployment if you wan to set up a servlet environment. Meaning, you need to use servlet APIs like HttpServletRequest, ServletContext, etc, in your application. If you don't need a servlet environment, just overriding configure is enough.

How do I add multiple Spring MVC controllers to my maven project

I need to add multiple controllers to my Spring MVC project which only has one right now. My current project only has one SpringDispatcher in the web.xml and it maps the
/
to the '/' of the controllers
#RequestMapping(value = "/")
start-up controller. Because everything is in the one web.xml and there are no other xml files that do any dispatcher mapping, should I not be able to just add a new
/
with a different controller pattern to the web.xml? Below are the web.xml and the one working controller.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringMvcJdbcTemplate</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</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>contextConfigLocation</param-name>
<param-value>net.codejava.spring</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
HomeController.java
package net.codejava.spring.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.codejava.spring.dao.ContactDAO;
import net.codejava.spring.dao.ContactDAODS;
import net.codejava.spring.model.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
/**
* This controller routes accesses to the application to the appropriate
* hanlder methods.
* #author www.codejava.net
*
*/
#Controller
public class HomeController {
#Autowired
private ContactDAO contactDAO;
#Autowired
private ContactDAODS contactDAODS;
#RequestMapping(value = "/")
public ModelAndView login() {
Contact contact = new Contact();
ModelAndView model = new ModelAndView("login");
model.addObject("contact", contact);
return model;
}
#RequestMapping(value = "/loginContact", method = RequestMethod.POST)
public ModelAndView loginContact(#ModelAttribute Contact loginContact) {
ModelAndView model;
Contact contact = contactDAO.login(loginContact);
if(contact != null)
{
model = new ModelAndView("menu");
return model;
}
else
{
Map<String, String> message = new HashMap<String, String>();
message.put("message", "Login password error");
//Message message = new Message();
//message.MessageText = "Login Error";
model = new ModelAndView("loginError");
model.addObject("message", message);
return model;
}
}
#RequestMapping(value = "/menuContact", method = RequestMethod.GET)
public ModelAndView menu(ModelAndView model){
model.setViewName("menu");
return model;
}
#RequestMapping(value = "/listContact", method = RequestMethod.GET)
public ModelAndView listContact(ModelAndView model) throws IOException{
List<Contact> listContact = contactDAO.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
#RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute Contact contact) {
contactDAO.saveOrUpdate(contact);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
#RequestMapping(value="/showContact")
public ModelAndView getContact(ModelAndView model) throws IOException{
Contact contact = contactDAODS.get((Integer)25);
model.addObject("contact", contact);
model.setViewName("ContactSP");
return model;
}
}
First of all, this mapping should only work for the application root. If you want any path under the application root then use
/*
Now, in your case spring dispatcher will only be called if you open your browser to point to web application root without specifying any path which as i might guess is not what you want. So, use /* to forward all requests to the spring dispatcher and the use any request mapping in your controllers

Class not found Exception in servlet Program (Windows 8.1 error)

While running my application on tomcat server class not found exception occur in my windows 8.1 PC but this program run correctly in windows XP PC.
My servlet application contains two java file and four html file. I have to run this application on windows 8.1 Operating System
Please do not use eclipse to run this Program
This is the signin.java file for the registered user.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class signin extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
PrintWriter out=res.getWriter();
String user=req.getParameter("un");
String pass=req.getParameter("ps");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:mail");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from userinfo where user_name='"+user+"' and user_pass='"+pass+"' ");
if(rs.next())
{
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/welcome.html");
rd.forward(req,res);
}
else
{
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/error.html");
rd.forward(req,res);
}
}
catch(Exception ex)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
doGet(req,res);
}
}//end of signin
This is the signup file for my new user.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class signup extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
String yr=req.getParameter("yn");
String un=req.getParameter("un");
String ps=req.getParameter("ps");
String sq=req.getParameter("sq");
String ans=req.getParameter("ans");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:mail");
Statement st=con.createStatement();
st.executeUpdate("insert into userinfo values ('"+yr+"','"+un+"','"+ps+"','"+sq+"','"+ans+"')");
st.close();
con.close();
out.println("<h1>your account has been created successfully </h1>");
}
catch(SQLException ex)
{
out.println("<h1> User name is already present try with different name </h1>");
}
catch(ClassNotFoundException ex)
{
out.println("<h1> Servlet Error </h1>");
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
doGet(req,res);
}
}
And My Web.xml file
<web-app>
<display-name>Simple Servlet Program</display-name>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>signup</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/xyz</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>signin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
</web-app>

Init method not firing JSP Servlet

I am using Eclipse IDE, a simple HelloServlet.java file and a simple index.jsp file. When I run the local server, the program starts but the following code does not execute:
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Init Firing: ");
}
I have the Console tab open, and the last statement I receive is: INFO: Server startup in 1442 ms. What might I do to get the init method to fire?
The container will only call the init() method of the servlet when it's called, not on the container startup.
If you want to start things on container startup, you can use the ContextListener as suggested here call method on server startup
This code works for me
package mine;
import java.io.IOException;
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 MySL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("xyz="+config.getInitParameter("xyz"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
and 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>jsp</display-name>
<servlet>
<servlet-name>mySL</servlet-name>
<servlet-class>mine.MySL</servlet-class>
<init-param>
<param-name>xyz</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mySL</servlet-name>
<url-pattern>/MySL</url-pattern>
</servlet-mapping>
</web-app>
When the server starts, nothing happens, because the init() method is called when the servlet is called.
On the first servlet call (e.g. opening in your browser something like http://myserver.mydomain:8080/myapp/MySL), you'll get
xyz=123
doGet
On the second servlet call, you'll get
doGet
Please notice that this is the "old way" of declaring things. Nowadays, Servlets configuration can be made using annotations. Careful to not mix annotations with XML declarations for the same servlet.
Servlets with annotations look like this
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = { "/OtherSL" }, initParams = { #WebInitParam(name = "abc", value = "456", description = "some parameter") })
public class OtherSL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("abc=" + config.getInitParameter("abc"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}

Resources