Java ee annotations wont work - java

I'm trying to write annotations for the first time in my servlet. The #WebServlet is working fine. It is when I add #webInitParam that I get the red line. Also,
when I try to use the #POST annotation it gives me "POST cannot be resolved to a type".
Here's my code:
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Servlet implementation class Calc
*/
#WebServlet (loadOnStartup = 1 , urlPatterns = { "/CoolPage" } ,
initParams = {
#WebInitParam(name="text" , value="hello" , description="simple text"),
#WebInitParam(name="times", value="10" , description="times to print")
}
)
public class Calc extends HttpServlet {
private static final long serialVersionUID = 1L;
public Calc() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#POST
protected void doThePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside the POST method");
String username = request.getParameter("userName");
String password = request.getParameter("password");
request.setAttribute("userName", username);
request.setAttribute("password", password);
RequestDispatcher rd = request.getRequestDispatcher("jspGetting.jsp");
rd.forward(request, response);
}
}

Imports do not include sub-packages. Import the class from the javax.servlet.annotation package
import javax.servlet.annotation.WebInitParam;
It's hard to see how the servlet could compile without WebServlet being imported either(?).
import javax.servlet.annotation.WebServlet;
The POST annotation is located within the JAX-RS library
import javax.ws.rs.POST;

Related

Return ModelAndView from Spring when handling exceptions

Dealing with exceptionhandling in spring project.
I had followed this approach to handle the exceptions.
Everything is going good, but I want to return a ModelAndView instead of writing a text/html using PrintWriter object.
Following is the approach I followed.
ExceptionHandler.java
package com.test.controller;
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;
import org.springframework.web.servlet.ModelAndView;
/**
* Servlet implementation class ExceptionHandler
*/
#WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(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());
//processError(request,response);
handleException(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//processError(request,response);
handleException(request,response);
}
//I want this ModelAndView to be returned and should display the page that was set in ModelANdView object.
private ModelAndView handleException(HttpServletRequest request,HttpServletResponse response) throws IOException {
ModelAndView model = new ModelAndView("ErrorPage");
model.addObject("errMsg", "this is Exception.class");
return model;
}
//I don't want this approach.
/*private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>Exception/Error Details</title></head> <body>");
if(statusCode != 500){
out.write("<h3>Error Details</h3>");
out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
out.write("<strong>Requested URI</strong>:"+requestUri);
}else{
out.write("<h3>Exception Details</h3>");
out.write("<ul><li>Servlet Name:"+servletName+"</li>");
out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
out.write("<li>Requested URI:"+requestUri+"</li>");
out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
out.write("</ul>");
}
out.write("<br><br>");
out.write("Home Page");
out.write("</body></html>");
}*/
}
And in web.xml I had added following tag to set location for error.
<error-page>
<error-code>404</error-code>
<location>/ExceptionHandler</location>
</error-page>
EDIT: I know that void cannot return ModelAndView Object , but looking for an approach to load the ErrorPage in case of invalid URL

unable to redirect from servlet to jsp page

I am trying to create a small registeration form using jsp and servlet.
The concept goes like this:
The data being enterd in the jsp form will be checked for duplication by a servlet program.
If duplication exists , then the control must return back to the registeration (jsp) page from where the servlet was called.
I am doing this in eclipse helios.
Servlet program is under the default package under java resources ,
and jsp file is under the web content folder.
My problem is that
I am able to redirect from jsp to servlet;
but when I try to return back to the jsp page from the servlet ,
tomcat server is showing error like:
HTTP Status 404 - /RservletEs/registeration.jsp
type Status report
message /RservletEs/reg.jsp
description The requested resource is not available.
I tried both request.dispatcher() and response.sendRedirect() both are showing same error.
The file path is:
RservletEs/src/ServletCheck
Rservlets/Web Content/registeration.jsp
I have attached the source code below
somebody pls help me out of this
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import java.util.Map;
import com.google.gson.Gson;
/**
* Servlet implementation class ServletCheck
*/
#WebServlet("/ServletCheck")
public class ServletCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
* /
public ServletCheck() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String clusterName="asdf";
String hostName="localcost";
String index="testdb";
String type="emp_type";
String field="emailId";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int portNumber=26101;
final TransportClient client = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)
.put("client.transport.sniff", true).build());
Settings settings = client.settings();
out.println("**settings:"+ settings);
ImmutableMap<String, String> map = settings.getAsMap();
out.println("**map::"+ map);
((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(hostName, portNumber));
out.println("ES client:" + client);
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String emailId=request.getParameter("emailId");
String age=request.getParameter("age");
String dob=request.getParameter("dob");
String eId=request.getParameter("employeeId");
String value=emailId;
SearchResponse response2 = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.termQuery(field, value))
.setFrom(0).setSize(60).setExplain(true).setRouting("1")
.execute()
.actionGet();
SearchHit[] results = response2.getHits().getHits();
int length=results.length;
int i=0;
if (length>0){
response.sendRedirect(request.getContextPath()+"/registeration.jsp");
//request.getRequestDispatcher("/registeration.jsp").forward(request, response);
}
else{
out.println("setting the values");
hr_employee tweet = new hr_employee();
out.println("setting the id");
tweet.setEmployeeId(eId);
tweet.setFirstName(firstName);
out.println("setting the last name");
tweet.setLastName(lastName);
tweet.setEmailId(emailId);
tweet.setDob(dob);
String str=tweet.getEmployeeId();
/* System.out.println("the id is...."+str);
System.out.println("the firstname .... "+tweet.getFirstName());
System.out.println("teh last name....."+tweet.getLastName());
*/
out.println("initiallizing req builder");
final IndexRequestBuilder builder = client.prepareIndex(index, type,str);
out.println("setting source");
builder.setSource(new Gson().toJson(tweet));
out.println("getting response");
final IndexResponse response3 = builder.setRouting("1").execute().actionGet();
out.println("geting connected...");
out.println("ElasticSearchEJBBean:indexDocument:" + index+ ":" + type+ ":" + str + ":index results:" + response3);
response.sendRedirect(request.getContextPath()+"/ServletInsert");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
sounds like there must be some problem with the way u name it.
Try like this:
right click on ur jsp file and select copy qualified name .
then use that name to redirect or dispatch like this:
request.getRequestDispatcher("/registeration .jsp").forward(request,response);
Since jsp is under the web-content folder do this
response.sendRedirect("/registeration.jsp");
or try something like this
response.sendRedirect(request.getSession().getServletContext().getRealPath("/registeration.jsp"));

How getRequestDispatcher will work for servlet in different project in same server?

In servlet we can use requestdispatcher and it will forward from one servlet to another servlet with same session in same project.but if i am using different project getRequestDispatcher is not working.its giving 404 error.because its appending servlet name before the url. how can i achieve getRequestDispatcher in different project in same server?
RequestDispatcher rd = request.getRequestDispatcher("/v1/status1/toreply1");
rd.forward(request, response);
In same project getRequestDispatcher working fine. but in different project its not working ?can anyone explain why its happening ..?
You can achieve getRequestDispatcher in different project on same server.
Check out https://stackoverflow.com/a/19273223/1428052
It works on same server for different project by using
getServletContext().getContext() method.
You can follow below steps for detail implementation.
First you need to make changes in below file
(Windows) C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\context.xml
Set value of crossContext to true.
context.xml
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
Please note that crossContext="true".
Suppose you have two web applications with name InterServletComm1 and InterServletComm2
having servlets Servlet1 and Servlet1 in each web application respectively. Then the code in each servlets goes as follows:
Servlet1.java
package interServletComm1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
request.setAttribute("name", "WebApp1");
ServletContext context = getServletContext().getContext("/InterServletComm2");
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Servlet2.java
package interServletComm2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 Servlet2
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = (String) request.getAttribute("name");
pw.println("This is web application 2.");
pw.println("<br>The value received from web application one is: " + name);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Above code sends attribute name from InterServletComm1 and it is received in InterServletComm2.
Please let me know if this answer is not clear.
You have to use the ServletContext of the other web application to get the RequestDispatcher. The other context can be looked up by ServletContext#getContext(String uri):
ServletContext otherContext = request.getServletContext().getContext("/other");
RequestDispatcher rd = otherContext.getRequestDispatcher("/v1/status1/toreply1");

Best Way to output SoyTemplates from a Servlet

What is the best waya to render or output Soy Templates from closure-templates to a browser?
Currently i have the following:
package de.envisia.erp.web.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.template.soy.SoyFileSet;
import com.google.template.soy.tofu.SoyTofu;
/**
* Servlet implementation class EntryPoint
*/
#WebServlet("/EntryPoint")
public class EntryPoint extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EntryPoint() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String pathContext = servletContext.getRealPath("/WEB-INF/");
//response.getWriter().println(pathContext);
SoyFileSet sfs = new SoyFileSet.Builder().add(new File(pathContext + "\\templates\\hello.soy")).build();
SoyTofu tofu = sfs.compileToTofu();
String out = tofu.newRenderer("hello.world").render();
response.getWriter().println(out);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
But i don't think it is a good practice to use the println or even print() method of the response object, are there any better ways?
Take a look at https://github.com/codedance/silken.
The basic idea is to make a special servlet and forward requests to it:
RequestDispatcher rd = getServletContext().getRequestDispatcher("/soy/products.boat.sailingBoatView");
rd.forward(req, resp);

Using <a href> to link to servlet

I have a anchor which i want it to be linked to a LogoutServlet so that it will destroy the sessions and redirect it back to a login page.
LogoutServlet.java
package pkg;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogoutServlet
*/
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
request.getSession().invalidate();
RequestDispatcher rd = request.getRequestDispatcher("Login.html");
rd.forward(request, response);
}
}
tag
Logout
Is this the right way to implement it?? I used this but it did not redirect me to Login.html .
That will hit the doGet method not the doPost method. An anchor link like that is a HTTP GET request.
If you wish to make a POST request, you will need to submit a form to the servlet using method POST.
Move your code to doGetinstead of doPost and try that.
Use doGet method. a href will use GET method.

Categories

Resources