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
Related
On my web application, which is hosted on Google App Engine, whenever I call a Servlet by typing in the URL on a browser, this results in two calls being made to the Servlet. However, if I make a call to the Servlet by clicking on an anchor, then only one call is made.
What is the cause and how can I correct this behavior?
Web.xml
<servlet>
<servlet-name>ServletOne</servlet-name>
<servlet-class>com.test.nz.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletOne</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
Servlet:
public class MyServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
final Logger log = Logger.getLogger(MyServlet.class.getName());
log.info("Here in MyServlet");
}
}
Update:
The issue appears to be caused by Google Chrome making requests on its own. Whenever I type in a URL, a request is made before I actually press enter, followed by the actual request. Is there any way to disallow these type of requests to my application?
I had the same issue, only in Chrome, turns out the servlet was mapped to / and was accepting requests for favicon.ico as well. For me this is the source of the second request.
My first attempt at developing a simple authentication based REST services. I am trying to develop a RESTful web application using Jersey on Tomcat 8. I am using Apache Shiro for session management and authorization. Only HTTPS is supported.
All services require authentication, neither guest nor anonymous access is allowed. The request can be authenticated two ways.
If the user belongs to the list of users in web application, then the user logs in from a Web browser and Shiro simply validates if the current user is logged in and allows request to proceed. This is for the custom UI provided by the application itself.
If the request is from third party application, the username/password token are passed into the HTTP header authorization field for every service request. The users are managed by third party app and the app uses a common username/password for its users to access the web service. Such common users are prevented from logging in.
All service requests are filtered (web.xml):
<servlet>
<servlet-name>REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>com.unisys.cpf.ffm.filter.AuthenticationFilter</param-value>
</init-param>
</servlet>
<servlet-mapping>`enter code here`
<servlet-name>REST Service</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
The AuthenticationFilter class implements ContainerRequestFilter for authentication:
#Override
public ContainerRequest filter(ContainerRequest cr) {
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
//User is not logged in so get the authorization from header and authenticate
String auth = cr.getHeaderValue("authorization");
//Do Shiro authentication here.
}
return cr;
}
I have a web service which accepts form parameters and creates a resource. The Form parameters are dynamic based on what user selects. So I cannot use #FormParam to get all the parameters. Also there may be more contents to form as new features are added so I do not want to touch the Service again for each new/removed parameter.
I am using the Chrome Advanced REST Client plugin to simulate third party requests. Any browser is fine for the first scenario (logged in user).
Now I know just two ways of accessing the form parameters.
First method is to use MultivaluedMap.
#POST
#Path("/create")
public String createResource(MultivaluedMap<String, String> parameters) {
System.out.println("Name of the resource: " + parameters.getFirst("resourceName"));
}
But trying to get the parameters using MultivaluedMap works only when a logged in user submits the form. If I submit from REST Client plugin the same form values, then all parameters return null.
Second method is to use #Context HttpServletRequest
#POST
#Path("/create")
public String createResource(#Context HttpServletRequest request) {
System.out.println("Name of the resource: " + request.getParameter("resourceName"));
}
This works for REST Client but does not work if a logged in user submits form. All request.getParameter return null.
If anybody knows how to fix the problem or better way to do authentication, then please let me know.
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)
I'm a Ruby on Rails developer programming a web application in Java. I am trying to achieve something similar to what is achieved in Rails. In Rails it is possible to call a link using localhost:8000\Users\1 when Users is a Model and 1 is the id of a specific user. I would like to get the same kind of thing in Java.
I am working in an MVC type design where my JSP pages are the view and my Servlets are the controllers. I created a servlet called Users which renders the users.jsp page now i can get to that page using the URL localhost:8000\projectName\Users, i would like to route localhost:8000\projectName\Users\1 to the page user.jsp while the appropriate Servlet will handle sending into the page the correct user (with id=1).
Any idea how I can achieve this?
I'm doing this in a University project and am not allowed to use any frameworks. I also would rather something i could code rather than install.
now i can get to that page using the URL localhost:8000\projectName\Users, i would like to route localhost:8000\projectName\Users\1 to the page user.jsp while the appropriate Servlet will handle sending into the page the correct user (with id=1).
Simple. Map the servlet on an URL pattern of /Users/* instead of /Users. You can then grab the path info (the part after /Users in the URL, which is thus /1 in your example) as follows:
String pathInfo = request.getPathInfo();
// ...
You can just forward to users.jsp the usual way.
Long id = Long.valueOf(pathInfo.substring(1));
User user = userService.find(id);
request.setAttribute("user", user);
request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
I would try this via a servlet and servlet mappings like that in web.xml
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.example.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/Users</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/Users/*</url-pattern>
</servlet-mapping>
Than in your UserServlet try to get the full URL and parse it to your needs. Example:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
String url = reg.getRequestURL();
//... get last part after slash and parse it to your id
}
See http://download.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletRequest.html for further documentation on the request and how its parameters can be retrieved
UrlRewriteFilter is like mod_rewrite but for Tomcat. You can use it to make your URLs SEO-friendly. You can also use Apache+mod_rewrite+Tomcat.