I have created one authorization filter before calling rest API but i am getting 404 error message. Below is classes which I have created.
--RestAuthenticationFilter
package com.sms.Security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RestAuthenticationFilter implements javax.servlet.Filter {
public static final String AUTHENTICATION_HEADER = "Authorization";
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authCredentials = httpServletRequest
.getHeader(AUTHENTICATION_HEADER);
// better injected
AuthenticationService authenticationService = new AuthenticationService();
boolean authenticationStatus = authenticationService
.authenticate(authCredentials);
if (authenticationStatus) {
filter.doFilter(request, response);
} else {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse
.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
--AuthenticationService
package com.sms.Security;
import java.io.IOException;
import java.util.Base64;
import java.util.StringTokenizer;
public class AuthenticationService {
public boolean authenticate(String authCredentials) {
if (null == authCredentials)
return false;
// header value format will be "Basic encodedstring" for Basic
// authentication. Example "Basic YWRtaW46YWRtaW4="
final String encodedUserPassword = authCredentials.replaceFirst("Basic"
+ " ", "");
String usernameAndPassword = null;
try {
byte[] decodedBytes = Base64.getDecoder().decode(
encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(
usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
// we have fixed the userid and password as admin
// call some UserService/LDAP here
boolean authenticationStatus = "admin".equals(username)
&& "admin".equals(password);
return authenticationStatus;
}
}
--Web.xml file
<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>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.sms.presentationT</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/pages/rest/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.sms.Security.RestAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/pages/rest/*</url-pattern>
</filter-mapping>
</web-app>
--Login API
package com.sms.presentationT;
import java.io.Serializable;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import com.sms.userServices.*;
import com.sms.Registrations.Regitration;
import com.sms.persistenceT.*;
import com.sms.persistenceT.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sms.Security.*;
#Path("/user-servicesLogincheck1")
public class Check implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#POST
#Path("/LoginPagecheck1")
//#Consumes("application/json")
//#Produces("application/json")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Regitration loginUserInfo(#FormParam("logusertype") String logUserType,
#FormParam("userNAME") String UserNAME,
#FormParam("PassWORD") String PAssWORD) throws ParseException
{
System.out.println(logUserType+UserNAME+PAssWORD);
CustomApplication CA = new CustomApplication();
CA.getApplication();
LoginUserServiceCheck LUS = new LoginUserServiceCheck();
JSONObject jobj2 = new JSONObject();
jobj2 = LUS.LoginInputDatacheck(logUserType,UserNAME, PAssWORD);
System.out.println("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
System.out.println("Presentation jobj"+jobj2);
String jsonText = jobj2.toJSONString();
System.out.println(jsonText);
JSONParser parser = new JSONParser();
JSONObject newJObject = null;
try {
newJObject = (JSONObject) parser.parse(jsonText);
} catch (ParseException e) {
e.printStackTrace();
}
//System.out.println(LUS.loginresponse);
//System.out.println(LUS.resultStatus);
/*
if(LUS.resultStatus)
{
System.out.println(LUS.loginresponse);
return LUS.loginresponse;
//return "UserName is valid";
}
else
{
return LUS.loginresponse;
}
*/
System.out.println(newJObject.get("Name"));
System.out.println(newJObject.get("Email"));
Regitration rg = new Regitration();
rg.setUserType(logUserType);
rg.setName((String)newJObject.get("Name"));
rg.setEmail((String)newJObject.get("Email"));
rg.setUserName((String)newJObject.get("userName"));
rg.setPassword((String)newJObject.get("password"));
rg.setConfirmPasssword((String)newJObject.get("password"));
rg.setBirthDay((String)newJObject.get("birthday"));
rg.setGender((String)newJObject.get("Gender"));
rg.setMobileNo((String)newJObject.get("mobileNo"));
rg.setCurrentAddress((String)newJObject.get("currentAddress"));
rg.setPermenantAddress((String)newJObject.get("PermenantAddress"));
rg.setCountry((String)newJObject.get("Country"));
rg.setState((String)newJObject.get("state"));
rg.setCity((String)newJObject.get("City"));
rg.setLandmark((String)newJObject.get("Landmark"));
rg.setZipCode((String)newJObject.get("ZipCode"));
return rg;
}
}
-- Error message
Mar 27, 2017 1:44:58 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2836 ms
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
Mar 27, 2017 1:44:59 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter AuthenticationFilter
java.lang.ClassNotFoundException: com.sms.Security.RestAuthenticationFilter
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:269)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:424)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
It looks like the RestAuthenticationFilter is not available in the classpath, hence the ClassNotFoundException. Please double check if you are compiling it and putting it in the classpath.
Related
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 have a SpringBoot application running on WebLogic Server Version: 12.2.1.3.0
When I define a custom servlet Filter its working fine on Embedded Tomcat. However, when i deploy my application as a war file to wlserver it throws following error after each request. What am i missing here?
<Could not load user defined filter in web.xml: com.thy.bwsadmin.CORSFilter.
java.lang.AbstractMethodError
at weblogic.servlet.internal.FilterManager$FilterInitAction.run(FilterManager.java:400)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:328)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:197)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
at weblogic.servlet.internal.FilterManager.initFilter(FilterManager.java:130)
at weblogic.servlet.internal.FilterManager.loadFilter(FilterManager.java:92)
at weblogic.servlet.internal.FilterManager.preloadFilters(FilterManager.java:72)
at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1928)
at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3106)
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1843)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:884)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:233)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:228)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:78)
at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:52)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:752)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:262)
This is the content of my web.xml file
<web-app 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_3_0.xsd"
version="3.0">
<display-name>MWSAdminService</display-name>
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.sample.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I am setting servlet dependency as provided to prevent jar conflicts.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
This is my Filter class.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.thy.bwsadmin.service.SecurityUserService;
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
#Autowired
SecurityUserService securityUserService;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
boolean isAuthenticated = authenticateUser(request.getHeader("identity_no"), request.getRequestURI());
if (isAuthenticated) {
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
} else {
response.sendError(HttpServletResponse.SC_OK, "401");
}
}
private boolean authenticateUser(String userId, String requestURI) {
if (Util.isNotEmpty(userId)
&& securityUserService.isAuthorizedForEndpoint(userId.trim(), requestURI)) {
return true;
}else{
return false;
}
}
}
As a solution i tried to remove the filter definitions in web.xml file and registered my filter as a bean configuration since this is a SpringBoot application. I also removed #Component and #Order annotations from my filter.
But the result was the same as above. It is still working on Tomcat but not in Weblogic. Here is the code for filter config bean.
#Configuration
public class Filters {
#Bean
public FilterRegistrationBean<CORSFilter> loggingFilter() {
FilterRegistrationBean<CORSFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CORSFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
Your servlet api provided by weblogic is probably old version and your filter class needs to override init method.
Add below code at your filter class;
#Override
public void init(FilterConfig filterConfig) throws ServletException {};
At new versions of servlet api, filter class has default empty init method.
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!");
}
}
I use Javax Restfull web service. I can return String from mobile app. but I cant return Model class.
I want to return Employee model. I give a error;
Full Error:
SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/CafeSiparis] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError
at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findSerializer(AnnotationIntrospector.java:1148)
at org.codehaus.jackson.map.ser.BasicSerializerFactory.findSerializerFromAnnotation(BasicSerializerFactory.java:362)
at org.codehaus.jackson.map.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:252)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createUntypedSerializer(StdSerializerProvider.java:782)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createAndCacheUntypedSerializer(StdSerializerProvider.java:735)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findValueSerializer(StdSerializerProvider.java:344)
at org.codehaus.jackson.map.ser.StdSerializerProvider.findTypedValueSerializer(StdSerializerProvider.java:420)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:601)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:527)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at controls.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:31)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2440)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2429)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My class:
Employee Model:
package model;
/**
*
* #author cengizhan
*/
public class Employee {
private String name;
private String surname;
private int id;
public Employee(int id, String name, String surname){
this.id = id;
this.name=name;
this.surname =surname;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the surname
*/
public String getSurname() {
return surname;
}
/**
* #param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
Web Service Class:
package ws;
import helper.UrunHelper;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import model.Employee;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Path("/WSLogin")
public class WSLogin implements Serializable {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/returnModel")
public Employee returnModel() {
Employee emp = new Employee(1, "Jack", "Jason");
return emp;
}
}
SimpleCORSFilter:
package controls;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author cengizhan
*/
public class SimpleCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
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");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
Web.xml:
<!-- Web Service -->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ws</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- /Web Service -->
Thank you :)
Looks like you are mixing dependency versions.. try using jersey-server-1.8 and jersey-json-1.8 (and adjust their dependencies versions)
Maven could help you out on this..
EDIT: Try using the following jars
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!