Spring Tool Suite.HTTP Status 404 -The requested resource is not available - java

I'm working with Spring Tool Suite and I want to be redirected to a jsp (rapports.jsp) from sevelet.But I can't do so .I get this error:
HTTP Status 404 - /rapports.jsp
type Status report
message: /rapports.jsp
description:The requested resource is not available.
This is my controller:
package com.mycompany.myapp;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springframework.http.HttpStatus;
import javax.servlet.ServletConfig;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.tools.ant.util.Base64Converter;
import javax.servlet.ServletConfig;
#Controller
public class HomeController extends HttpServlet {
private static final long serialVersionUID = 1L;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.setViewName("authentification");
return model;}
#RequestMapping(method=RequestMethod.POST)
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
String Str1 = request.getParameter("smya");
String Str2 = request.getParameter("mdps");
System.out.println(Str1);
System.out.println(Str2);
try {
URL url = new URL("http://pc-demo-bi:8090/jasperserver-pro/rest/login?j_username="+Str1+"&j_password="+Str2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
System.out.println("connected");
response.sendRedirect("/rapports.jsp");
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
as you see I have used: response.sendRedirect("/rapports.jsp") to do so.
and this is my Web.xml:
<?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>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</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>
this is my rapport.jsp
<title>hahahah</title>
</head>
<body>
Welcome!!
</body>
</html>
thanks in advance if you have any suggestion.

Personally, I dont think you need to extend HttpServlet. Try something like what i've put below. Assuming you have a valid view resolver (Spring or otherwise, I prefer Apache Tiles), returning just the name of the JSP page "rapports" will redirect the user. You can also use the annotation #RequestAttribute to get Str1 and Str2 from the HttpServletRequest, rather than injecting it into the method.
#Controller
public class HomeController {
private static final long serialVersionUID = 1L;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.setViewName("authentification");
return model;
}
#RequestMapping(method=RequestMethod.POST)
public void service(#RequestAttribute("smya") Str1, #RequestAttribute("mdps") Str2){
System.out.println(Str1);
System.out.println(Str2);
try {
URL url = new URL("<code>http://pc-demo-bi:8090/jasperserver-pro/rest/login?j_username="+Str1+"&j_password="+Str2</code>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
System.out.println("connected");
return("rapports");
conn.disconnect();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Hopefully that makes sense!

Related

cannot Inject Named bean into javax.ws.rs class while #EJB could be used

I try to inject a named bean into a class using javax.ws.rs.* and got the result of :
javax.servlet.ServletException: A MultiException has 1 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=UserBean,parent=NameCheckREST,qualifiers={},position=-1,optional=false,self=false,unqualified=null,903092946)
root cause
So I can guess the dependency injection failed. After I comment the #inject and related methods, it works. My question is why I cannot inject the named bean into javax REST class while my teacher uses #EJB to inject ejb and it succeeds.
Is this kind of design mechanism? You can refer to the code below:
#inject failed:
package restServices;
import java.text.DecimalFormat;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import beans.UserBean;
#Path("checkname")
public class NameCheckREST {
#SuppressWarnings("unused")
#Context
private UriInfo context;
#Inject
private UserBean userBean;
/**
* Default constructor.
*/
public NameCheckREST() {
// TODO Auto-generated constructor stub
}
// /**
// * Retrieves representation of an instance of NameCheckREST
// * #return an instance of String
// */
// #GET
// #Produces("application/json")
// public String getJson() {
// // TODO return proper representation object
// throw new UnsupportedOperationException();
// }
/**
* Retrieves representation of an instance of HelloWorld
* #return an instance of String
*/
#GET
#Produces("text/html")
public String getHtml() {
// TODO return proper representation object
//DecimalFormat df = new DecimalFormat("0.00");
return "<html><body><h1>" + "Web resources for CMS" + "</h1> </body></html>";
//throw new UnsupportedOperationException();
}
/**
* PUT method for updating or creating an instance of NameCheckREST
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/json")
public void putJson(String content) {
}
#POST
#Path("user")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.APPLICATION_JSON)
public JsonArray checkUsername(#FormParam("account") String account) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
objectBuilder.add("account", account);
if(userBean.searchUserByAccount(account) == null) {
objectBuilder.add("exist", false);
}else {
objectBuilder.add("exist", true);
}
arrayBuilder.add(objectBuilder);
return arrayBuilder.build();
}
}
named user bean:
package beans;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.util.logging.Level;
import java.util.logging.Logger;
import entity.NormalUser;
//import entity.User;
import repository.UserRepository;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
UserRepository userRepository;
//default constructor
public UserBean() {
}
public List<NormalUser> getAllUsers(){
try {
List<NormalUser> users = userRepository.getAllUsers();
//System.out.print("users:" + users.size());
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, "users:" + users.size());
return users;
} catch(Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public boolean addUser(NormalUser user) {
try {
userRepository.addUser(user);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean removeUser(String account) {
try {
userRepository.deleteUser(account);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean editUser(NormalUser user) {
try {
userRepository.updateUser(user);
return true;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public NormalUser searchUserByAccount(String account) {
try {
NormalUser user = userRepository.searchUser(account);
return user;
}catch (Exception ex) {
Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
#EJB succeed:
package helloworld;
import java.text.DecimalFormat;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import calculator.LoanBean;
#Path("greeting")
public class HelloWorld {
#SuppressWarnings("unused")
#Context
private UriInfo context;
#EJB
private NameStorageBean nameStorage;
#EJB
private LoanBean loanBean;
/**
* Default constructor.
*/
public HelloWorld() {
// TODO Auto-generated constructor stub
}
/**
* Retrieves representation of an instance of HelloWorld
* #return an instance of String
*/
#GET
#Produces("text/html")
public String getHtml() {
// TODO return proper representation object
DecimalFormat df = new DecimalFormat("0.00");
return "<html><body><h1>Hello " + nameStorage.getName() + ", the monthly payment is " + df.format(loanBean.calculate()) +"!</h1> </body></html>";
//throw new UnsupportedOperationException();
}
#POST
#Consumes("application/x-www-form-urlencoded")
public void setPostName( #FormParam("name") String content) {
nameStorage.setName(content);
}
#POST
#Path("loan")
#Consumes("application/json")
public void setPostLoan(Loan loan) {
loanBean.setPrinciple(loan.getPrinciple());
loanBean.setInterestRate(loan.getInterestRate());
loanBean.setNumberOfYears(loan.getNumberOfYears());
loanBean.setMonthlyPayment(loanBean.calculate());
// ELContext context
// = FacesContext.getCurrentInstance().getELContext();
// WebServiceBean currentWebBean = (WebServiceBean) FacesContext.getCurrentInstance().getApplication()
// .getELResolver().getValue(context, null, "webServiceBean");
// currentWebBean.setMonthlyPayment(loanBean.calculate());
}
/**
* PUT method for updating or creating an instance of HelloWorld
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("text/html")
public void putHtml(String content) {
}
}
about web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
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">
<display-name>CMS-war</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<!-- <context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</param-value>
</context-param> -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<security-constraint>
<display-name>AdminContstraint</display-name>
<web-resource-collection>
<web-resource-name>WebResource</web-resource-name>
<url-pattern>/faces/admin/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>DELETE</http-method>
<http-method>PUT</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint>
<description>Administrator</description>
<role-name>Admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<display-name>NormalContstraint</display-name>
<web-resource-collection>
<web-resource-name>WebResource</web-resource-name>
<url-pattern>/faces/normal/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>DELETE</http-method>
<http-method>PUT</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint>
<description>NormalUser</description>
<role-name>Normal</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>cms_security</realm-name>
<form-login-config>
<form-login-page>/faces/login.xhtml</form-login-page>
<form-error-page>/faces/error.xhtml</form-error-page>
</form-login-config>
</login-config>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<security-role>
<description>Administrator</description>
<role-name>Admin</role-name>
</security-role>
<security-role>
<description>NormalUser</description>
<role-name>Normal</role-name>
</security-role>
</web-app>
So is there anything I did not pay attention to or I just cannot inject named bean but ejb into javax-rest class.

I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?

my web.xml file :
Web.xml
I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?
I am using the below URL :
http://localhost:8080/learning1/rest/firstRest/User1
<?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">
<servlet>
<servlet-name>Learn</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.java.learning1</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Learn</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My restfulwebservice java file : java file
Server is responding with HTTP Status code 404 : not found
package org.java.learning1;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces("MediaType.TEXT_HTML")
#Path("{name}")
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello";
return greeting;
}
}
Hello user7481861 and welcome to stackoverflow!
You have two errors in your code, I've corrected them bellow and added a comment in each, saying what was wrong.
package org.java.learning1;
//import javax.websocket.server.PathParam; <-- incorrect import
import javax.ws.rs.PathParam; // <<-- correct import
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces(MediaType.TEXT_HTML) // No quotes like stdunbar said in the comments
#Path("/{name}") // missing slash before name
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello " + name; // concatenate the string with the variable name
return greeting;
}
}

HTTP Status 500 - Error instantiating servlet class com.marlabs.demo.XMLServlet

I am developing a simple webapp and I am getting the following error when I am registering my users.
HTTP Status 500 - Error instantiating servlet class com.marlabs.demo.XMLServlet
web.xml is as follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SimpleServletProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>XMLServlet</servlet-name>
<servlet-class>com.marlabs.demo.XMLServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XMLServlet</servlet-name>
<url-pattern>/XMLServlet</url-pattern>
</servlet-mapping>
</web-app>
My servlet is as follows
package com.marlabs.demo;
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#SuppressWarnings("serial")
#WebServlet(description = "A simple servlet", urlPatterns = { "/XMLServlet" })
public class XMLServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pout = response.getWriter();
String emailID = request.getParameter("emailID");
String pass = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
HttpSession sess = request.getSession();
ServletContext context = request.getServletContext();
if (emailID != "" && emailID != null) {
sess.setAttribute("savedEmail", emailID);
context.setAttribute("savedEmail", emailID);
}
pout.println("Hello " + fname + "<br/>");
UserDetails user = new UserDetails();
user.setEmailID(emailID);
user.setPass(pass);
user.setFname(fname);
user.setLname(lname);
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
pout.println("Your information is saved!");
}
}

ExceptionMapper causes "No 'Access-Control-Allow-Origin' header is present on the requested resource" when handling an exception

I have an AngularJS client trying to consume a REST Web Service on Wildfly.
It works when the server returns an object, but when an exception is thrown, I'm getting the following message:
XMLHttpRequest cannot load
http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:51647' is therefore not allowed
access. The response had HTTP status code 500.
I tried lots of combinations of headers and filters, but nothing can make this works.
Client code:
var user = {
email : $scope.signUpData.email,
password : $scope.signUpData.password,
name : $scope.signUpData.name
};
$http.post(
'http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create',
user).
then(function(data) {
console.log("It works!");
},
function(response) {
console.log(response);
});
Web Service
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import br.com.produtos.business.UserBO;
import br.com.produtos.business.exceptions.BusinessException;
import br.com.produtos.entity.User;
import br.com.produtos.transaction.Transaction;
#Path("/user")
public class UserREST {
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON })
public User createAcount(#Context HttpServletRequest httpServletRequest, User user) throws BusinessException {
if (user.getEmail().equals("fff")) {
throw new BusinessException("Bussiness error.");
}
{...}
return user;
}
}
ExceptionMapper
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity(throwable.getMessage()).build();
}
}
Application
#ApplicationPath("/rest")
public class ThisApplication extends Application {
public static CorsFilter cors;
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ThisApplication() {
CorsFilter filter = new CorsFilter();
filter.getAllowedOrigins().add("*");
cors = filter;
singletons.add(filter);
singletons.add(new ThrowableMapper());
singletons.add(new UserREST());
}
public Set<Class<?>> getClasses() {
return empty;
}
public Set<Object> getSingletons() {
return singletons;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ProdutosBackend</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>br.com.produtos.rest.ThisApplication</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I solved the problem returning the message encapsulated into a json string.
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity("{ \"message\": \"" + throwable.getMessage() + "\" }").build();
}
}

How to integrate Cross Origin Resource Sharing with Spring MVC 4.0.0 RESTful Webservice

I have a Simple Web Service returning JSON data.
The User Class (com.bargadss.SpringService.Domain) is The POJO class containing
user_ID, firstName, lastName, eMail
The UserService class (com.bargadss.SpringService.DAO) two major operation
getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User}
getUserById(int user_ID) -> Queries the DB to Select a specific user based on ID
The SpringServiceController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bargadss.SpringService.DAO.UserService;
import com.bargadss.SpringService.Domain.User;
#RestController
#RequestMapping("/service/user/")
public class SpringServiceController {
UserService userService=new UserService();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userService.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
The ListUserController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.bargadss.SpringService.Domain.User;
#Controller
public class ListUserController {
#RequestMapping("/listUsers")
public ModelAndView listUsers() {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/";
List<LinkedHashMap> users=restTemplate.getForObject(url, List.class);
return new ModelAndView("listUsers", "users", users);
}
#RequestMapping("/dispUser/{userid}")
public ModelAndView dispUser(#PathVariable("userid") int userid) {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/{userid}";
User user=restTemplate.getForObject(url, User.class,userid);
return new ModelAndView("dispUser", "user", user);
}
}
The CorsFilter (com.bargadss.CORS) is as follows :
package com.bargadss.CORS;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter{
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
The web.xml is as follows :
<?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: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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringServiceWithRESTAndJSONExample</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.bargadss.CORS.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The Web Service when being invoked by AngularJS from another Web Server returns Error referring to Cross Origin Resource Sharing problem !!!
What Changes must be performed in the Controller side to eliminate the error ?
Is there any changes necessary to be done at the AngularJS side to avoid this situation ?
Check the cors-filter
Download cors-filter-2.1.2.jar and java-property-utils-1.9.1.jar.
mvn dependency
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.9.1</version>
</dependency>
and in web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Categories

Resources