I have two servlets below and work well with Tomcat7/Indigo,
it will print ' is added' when I visit myhost/DynamicAddServlet/tobeadded.jsp.
But they do not work in WebLogic 12c, is this possible in WebLogic 12c?
AddServletServlet
package test.servlets;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="AddServletServlet", urlPatterns={"/add.jsp"},
loadOnStartup=1)
public class AddServletServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8873939883201271898L;
#Override
public void init() throws ServletException {
super.init();
final ServletRegistration.Dynamic dn =
this.getServletContext().addServlet("TobeAddedServlet", TobeAddedServlet.class);
dn.setAsyncSupported(true);
dn.addMapping("/tobeadded.jsp");
System.out.println(" ... init ...");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}
TobeAddedServlet
package test.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TobeAddedServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8873939883201271898L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(" is added");
}
}
the stacktrace in WebLogic 12c:
<Mar 2, 2012 5:56:09 PM CST> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "1330682169014" for task "2". Error is: "weblogic.application.ModuleException: [HTTP:101216]Servlet: "AddServletServlet" failed to preload on startup in Web application: "DynamicAddServlet".
java.lang.UnsupportedOperationException: [HTTP:101388]The ServletContext was passed to the ServletContextListener.contextInitialized method of a ServletContextListener that was neither declared in web.xml or web-fragment.xml, nor annotated with javax.servlet.annotation.WebListener.
at weblogic.servlet.internal.WebAppServletContext.checkNotifyDynamicContext(WebAppServletContext.java:3834)
at weblogic.servlet.internal.WebAppServletContext.addServlet(WebAppServletContext.java:3464)
at weblogic.servlet.internal.WebAppServletContext.addServlet(WebAppServletContext.java:3564)
at test.servlets.AddServletServlet.init(AddServletServlet.java:25)
at javax.servlet.GenericServlet.init(GenericServlet.java:240)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:299)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:250)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.StubSecurityHelper.initServletInstance(StubSecurityHelper.java:94)
at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:82)
at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:74)
at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:60)
at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:34)
at weblogic.servlet.internal.ServletStubImpl.initStubLifecycleHelper(ServletStubImpl.java:638)
at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:579)
at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1874)
at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1848)
at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1738)
at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1704)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:70)
at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:212)
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:111)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:70)
at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:24)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:582)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:148)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:114)
at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:149)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:335)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:844)
at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1253)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:440)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:163)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:545)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)"
Thanks in advance,
Hippo
According to Servlet specification (point 4.4) You can execute method addServlet only from contextInitialized method of a ServletContextListener implementation or from the onStartup method of a ServletContainerInitializer implementation.
Servlet Specification
Related
I have a vue app that is deployed on server running a tomcat 9. HOw can I add Feature-Policy and Expect-CT headers to all the pages?
Filter class that add headers to response
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;
public class MyCustomHeadersFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
HeaderResponseWrapper headerResponseWrapper = new HeaderResponseWrapper(httpResp);
headerResponseWrapper.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
headerResponseWrapper.setHeader("Pragma", "no-cache"); // HTTP 1.0.
headerResponseWrapper.setHeader("Expires", "0"); // Proxies.
chain.doFilter(request, headerResponseWrapper);
}
#Override
public void destroy() {
}
}
HeaderResponseWrapper class
import java.io.*;
import javax.servlet.http.*;
public class HeaderResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter writer;
public HeaderResponseWrapper(HttpServletResponse response) {
super(response);
writer = new CharArrayWriter();
}
public PrintWriter getWriter() {
return new PrintWriter(writer);
}
public String toString() {
return writer.toString();
}
}
Now add this class as filter in the web.xml of tomcat and map it to relevant URLs
<filter>
<filter-name>MyCustomHeadersFilter</filter-name>
<filter-class>com.headers.config.MyCustomHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyCustomHeadersFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
I'm trying to check if attemptAuthentication is working but in postman but I'm getting 401 unauthorized.
My security Configure:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//http.formLogin();
http.authorizeRequests().antMatchers("/login","/login/**","/register/**").permitAll();
http.authorizeRequests().antMatchers(HttpMethod.POST,"/tasks/**").hasAuthority("ADMIN");
http.authorizeRequests().anyRequest().authenticated();
http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
http.addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
My attemptAuthentication:
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
AppUser appUser = null;
try {
appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("****************************");
System.out.println(appUser.getUsername());
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
}
My postman test:
My JWTAuthenticationFilter:
package security;
import java.io.IOException;
import java.util.Date;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.example.springJWT.entities.AppUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super();
// super.setFilterProcessesUrl("/login");
this.authenticationManager = authenticationManager;
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
AppUser appUser = null;
try {
appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("****************************");
System.out.println(appUser.getUsername());
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
User springUser=(User) authResult.getPrincipal();
String jwt=Jwts.builder()
.setSubject(springUser.getUsername())
.setExpiration(new Date(System.currentTimeMillis()+SecurityConstants.EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS256, SecurityConstants.SECRET)
.claim("roles", springUser.getAuthorities())
.compact();
response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX+jwt);
super.successfulAuthentication(request, response, chain, authResult);
}
}
in your JWTAuthenticationFilter class in the attemptAuthentication method you are providing a UsernamePasswordAuthenticationToken to the auth manager
which has as principal a String instance and the in the successfulAuthentication method you are trying to cast this to an User
User springUser=(User) authResult.getPrincipal();
and this goes wrong if I try it but it depends on the AuthenticationProvider you are actually using
I am new to Camel and I am facing an issue while sending files to webservice via camel http.
I have a rest web service which consumes Multipart form data type content and accepts input as part of form data.
When I send file and form parameter via camel it gives me the following error at camel console:
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/JAX_RS_Application/resource/restwb/upload with statusCode: 415
at org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:230)
at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:156)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:435)
at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)
at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
The error i get on the server side console is as follows:
SEVERE: MessageBodyReader not found for media type=application/octet-stream, typ
e=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=clas
s org.glassfish.jersey.media.multipart.FormDataMultiPart.
The code snippet of the Rest web-service created via jersey is as follows:
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/restwb")
public class FileResource {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(#FormDataParam("username") String username,#FormDataParam("password") String password,#FormDataParam("upload") InputStream is) {
String output ="Hi "+username+" your password is "+password;
output=output+IOUtils.LINE_SEPARATOR +IOUtils.LINE_SEPARATOR;
output=output+"Output :"+IOUtils.LINE_SEPARATOR+"------------------------------------------------------------------------------"+IOUtils.LINE_SEPARATOR;
try {
output=output+IOUtils.toString(is)+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
output=output+"==================================================================================================="+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
System.out.println("Output :"+output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return output;
}
}
And my Camel config is as follows:
import org.apache.camel.*;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.spi.UnitOfWork;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.james.mime4j.message.Multipart;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
/**
* Created by Manish.Pillai on 7/16/2015.
*/
public class LoggingMain {
private static final Logger logger =Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception{
CamelContext camelContext =new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getContext().getTypeConverterRegistry().addTypeConverter(HttpEntity.class,InputStream.class,new InputStreamToHttpEntityConvertor());
exchange.getOut().setBody(exchange.getIn().getBody(),HttpEntity.class);
}
})
.to("http://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
static class InputStreamToHttpEntityConvertor implements TypeConverter {
public boolean allowNull() {
return false;
}
public <T> T convertTo(Class<T> type, Object value) throws TypeConversionException {
Exchange exchange=(Exchange)value;
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("upload", new FileBody(exchange.getIn().getBody(File.class), ContentType.MULTIPART_FORM_DATA, (String) exchange.getIn().getHeader(Exchange.FILE_NAME)));
multipartEntityBuilder.addPart("username",username);
multipartEntityBuilder.addPart("password",password);
return (T)multipartEntityBuilder.build();
}
public <T> T convertTo(Class<T> aClass, Exchange exchange, Object o) throws TypeConversionException {
return convertTo(aClass,o);
}
public <T> T mandatoryConvertTo(Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Object value) {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Exchange exchange, Object value) {
return convertTo(type,value);
}
}
}
Any leads would be helpful.
Well, there are several things that can be improved in your code.
First, since you are using a MultipartEntityBuilder, that means you're using Apache's HttpClient version 4.3+, so for best compatibility you should use Camel's HTTP4 component.
Third, in an example as small as this, you don't really need to use the converter, you can do something like this:
public class LoggingMain {
private static final Logger logger = Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception {
CamelContext camelContext = new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("username", username);
multipartEntityBuilder.addPart("password", password);
String filename = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
File file = exchange.getIn().getBody(File.class);
multipartEntityBuilder.addPart("upload", new FileBody(file, ContentType.MULTIPART_FORM_DATA, filename));
exchange.getIn().setBody(multipartEntityBuilder.build());
}
})
.to("http4://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
I hope this helps!
//code for my application:-
when i run my application and open the logout or profile page i.e. i click on logout or profile links then the error 404 resource not found occurs //index.html
<h1>Welcome to login pannel</h1>
Login
Logout
Profile
//link.html
Login |
Logout |
Profile
//login.html
<form action="loginservlet" method="post">
Name:<input type="text" name="name"/><br>
Password:<input type="password" name="pass"/><br>
<input type="submit" value="login"/>
</form>
//loginservlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/* Servlet implementation class loginservlet
*/
#WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("1234")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
Cookie ck=new Cookie("name",name);
res.addCookie(ck);
}else{
out.print("sorry, username or password error!");
req.getRequestDispatcher("login.html").include(req, res);
}
out.close();
}
}
//profileservlet.java//
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class profileservlet
*/
#WebServlet("/profileservlet")
public class profileservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public profileservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
Cookie ck[]=req.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
req.getRequestDispatcher("login.html").include(req, res);
}
out.close();
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
}
//logoutservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class logoutservlet
*/
#WebServlet("/logoutservlet")
public class logoutservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
Cookie ck=new Cookie("name","");
ck.setMaxAge(0);
res.addCookie(ck);
out.print("you are successfully logged out!");
//res.getWriter().append("Served at: ").append(req.getContextPath());
}
}
//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>log_in_out</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
When i make a request to my JAX-RS path with an empty body I am getting error 500 as a response. If I send a body with {} is ok since it interprets that is a JSON.
I would like to be able to return the error code 400 BAD_REQUEST since in my opinion this is a client error.
#PUT
#Produces(APPLICATION_JSON)
#Consumes(APPLICATION_JSON)
#Path("/up")
public Response signUp(Credentials credentials) {
I am using jersey, and for the JSON mapper this library:
org.glassfish.jersey.media:jersey-media-json-jackson:2.22.2'
Create a custom provider to deserialise your JSON payload and hook up your logic. I assume you are using JAXB annotation in your classes.
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONUnmarshaller;
#Provider
#Consumes({MediaType.APPLICATION_JSON})
public class MyJsonReaderProvider<T> implements MessageBodyReader<T> {
#Override
public boolean isReadable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return type.isAnnotationPresent(XmlRootElement.class);
}
#Override
public T readFrom(Class<T> type,
Type genericType,
Annotation[] annotations,
MediaType mediatype,
MultivaluedMap<String, String> headers,
InputStream inputStream) throws IOException,
WebApplicationException {
try {
JAXBContext jc = JSONJAXBContext.newInstance(type);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JSONUnmarshaller jsonUnmarshaller = JSONJAXBContext.getJSONUnmarshaller(unmarshaller);
T object = (T) jsonUnmarshaller.unmarshalFromJSON(inputStream, type);
return object;
} catch (JAXBException e) {
throw new BadRequestException("Bad Request");
}
}
}
Register the provider in your javax.ws.rs.core.Application