I have a servlet api where I used to throw my own exceptions from servlets level
When I throw exception from doGet method everything works fine and exception handler catches and processed my exception. the problem ocures when I throw exception from doPost method. in this case unfortunatelly I never see error page
web.xml
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
exception handler
#WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
private final Logger logger;
public ErrorHandler() {
logger = Logger.getLogger(ErrorHandler.class);
}
#Override
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
}
Servlet
#Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
throw new UserException("error message");
}
Add to your ErrorHandler
#Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
To avoid code duplication consider creating third method
private void processError(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
and invoke it from both doGet() and doPost()
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
processError(req, resp);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
processError(req, resp);
}
Related
**iam trying to generate a pdf of my page contents from doPost method. but my tomcat server fails to start each time
below is my code
#SuppressWarnings({ "deprecation", "resource" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String filename="mypdf";
PDDocument mydoc=new PDDocument();
PDPage page=new PDPage();
mydoc.addPage(page);
PDPageContentStream content=new PDPageContentStream(mydoc, page);
content.beginText();
content.setFont(PDType1Font.COURIER_BOLD, 30);
content.moveTextPositionByAmount(250, 750);
content.drawString("syllabus");
content.endText();
content.close();
mydoc.save(filename);
mydoc.close();
System.out.println("the pdf saved at"+System.getProperty("user.dir"));
}catch(IOException ie)
{
System.out.println("IOexception"+ie);
}
}
**
This worked for me. just try formatting like this.
#SuppressWarnings("javadoc")
public class Billing extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
performTask(request, response);
}
private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
//Create pdf
PDDocument document = new PDDocument();
//Create Page
PDPage page = new PDPage();
//Adding the page
document.addPage(page);
//Loading the page
File file = new File("D:/akash/my_doc.pdf");
//writing text
contentStream.beginText();
contentStream.newLineAtOffset(295, 757);
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
contentStream.showText("CHIMERA TRANSPLANT RESEARCH FOUNDATION");
contentStream.endText();
//Saving the document
document.save("D:/akash/my_doc.pdf");
//Closing the document
document.close();
}
}
In my JSF application I have a #WebFilter and I'd like to, when a page forward occurs, get the URI of the destination page. Is that possible?
#WebFilter(servletNames={"Faces Servlet"})
public class MyFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
// here, can I know the URI?
chain.doFilter(request, response);
}
#Override
public void destroy() {}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
Thanks
I am using Spring-Boot and Spring-OAuth2 to protect my Rest APIs. I have implemented OAuth2. It gets executed properly. I developed AngularJS and try to access it, but I am getting CORS error.
Error -> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.2.45:8080/Jaihind/oauth/token. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
URL -> curl -X POST -vu clientapp:123456 http://localhost:8080/Jaihind/oauth/token -H "Accept: application/json" -d "password=password&username=gaurav&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
Below are the codes.
OAuth2ServerConfiguration.java
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "restservice";
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
// #formatter:off
resources.resourceId(RESOURCE_ID);
// #formatter:on
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().antMatchers("/api/greeting").authenticated();
http.authorizeRequests().antMatchers("/oauth/token").permitAll();
//http.antMatcher("/oauth/token").p
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private UserDetailServiceBean userDetailsService;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// #formatter:off
endpoints.addInterceptor(new HandlerInterceptorAdapter() {
#Override
public boolean preHandle(HttpServletRequest hsr, HttpServletResponse rs, Object o) throws Exception {
rs.setHeader("Access-Control-Allow-Origin", "*");
rs.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
rs.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
return true;
}
});
endpoints.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// #formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("123456");
// #formatter:on
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
}
I even added Filter.
Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class YourCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,x-auth-token,x-requested-with,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
if (request.getMethod() != "OPTIONS") {
chain.doFilter(req, resp);
} else {
}
chain.doFilter(req, resp);
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}
Your filter always calls chain.doFilter(req, resp) so if the downstream app doesn't handle the CORS requests then you are going to see errors like that.
sample code shown below :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post");
Client client =Client.create();
WebResource webResource=client.resource("https://mondelezinternational-test.coupahost.com/api/invoices/");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
ClientResponse resp=webResource.queryParams(queryParams).header("X-COUPA-API-KEY","53fb46e5bb0dbe7fc338f22e2d5035e52cc302fa").header("Accept","application/xml").post(ClientResponse.class);
System.out.println("Responce Body"+resp.getStatusInfo());
System.out.println("Responce Body"+resp.getStatus());
System.out.println("Responce Body"+resp.getLanguage());
System.out.println("Responce Body"+resp.getHeaders());
if (resp.getStatus()==200)
This is something im trying to implement. I have written the doGet method , how do i map the doPost method now ?
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") &&
act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
} else if (act!= null && !act.equalsIgnoreCase("null") &&
act.equalsIgnoreCase("register")) {
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else {
forward = "/Login.jsp";
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
If you want to handle POST just like GET you could do
protected void doPost((HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
if you want to treat POST and GET in similar way then you can add a third method
doSomething(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
and call it from both
doGet and do Post
eg
doSomething(request,response);
This is the default code generated by Netbeans IDE.
Keep your code in common method and map it to your invoking method.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}