When I change the url-pattern of servlet from / to /client doesn't take the path on consedration [duplicate] - servlets

This question already has answers here:
Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
(7 answers)
Closed last month.
This is web.xml
<servlet>
<servlet-name>ClientServlet</servlet-name>
<servlet-class>ma.fstt.web.ClientServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientServlet</servlet-name>
<url-pattern>/client</url-pattern>
</servlet-mapping>
And this is the ClientServlet.java
package ma.fstt.web;
public class ClientServlet extends HttpServlet {
...
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
...
default:
listClients(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
...
}
I'm trying to access the showNewForm by http://localhost:8081/Atelier1/client/new and this error show up
enter image description here

Try #WebServlet("/client") instead of url-pattern in web

I resolved this problem by adding a variable in the path
package ma.fstt.web;
public class ClientServlet extends HttpServlet {
...
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
...
default:
listClients(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
...
}

Related

how to add custom response HTTP header in Servlet Filter that depends on status code returned from app

for logging (MDC) I need to set a custom header when the response is failed as the following:
public class MDCFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
MDC.put("trackingId", UUID.randomUUID().toString());
try {
chain.doFilter(request, response);
} catch (Throwable throwable) {
//suppress
}
if (((HttpServletResponse) response).getStatus() >= 300) {
((HttpServletResponse) response).setHeader("x-tracking-id", MDC.get("trackingId"));
// ((HttpServletResponse) response).getHeader("x-tracking-id"); //this returns null
}
MDC.remove("trackingId");
}
}
but this does not work, no header is set. if I set the header before chain.doFilter it works, but I need to set this filter as late as possible, I need to know if the response status is OK or failed.
You need to set the header as soon as the status is set, not after when the response is already sent to the client. That's a point of no return. You can use a HttpServletResponseWrapper to decorate the behavior of setStatus() method.
For example,
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
MDC.put("trackingId", UUID.randomUUID().toString());
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
#Override
public void setStatus(int status) {
super.setStatus(status);
if (status >= 300) {
setHeader("x-tracking-id", MDC.get("trackingId"));
}
}
});
}
finally {
MDC.remove("trackingId");
}
}
Note that I also fixed the sloppy exception handling.

HTTP method POST is not supported by this URL

Can someone please tell me why am I getting this error, I have done endless search on web and tried all sorts of suggestions nothing seems to be working.
Error:- HTTP method POST is not supported by this URL
#WebServlet("/LoginProccess")
public class LoginProccess extends HttpServlet {
private static final long serialVersionUID = 1L;
#SuppressWarnings("static-access")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DbConnection dbConn = null;
Connection conn = null;
CallableStatement proc = null;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// get the variables entered in the form
String clientID = request.getParameter("cid");
String loginID = request.getParameter("lid");
String password = request.getParameter("pwd");
String instName = request.getParameter("iName");
try{
dbConn = new DbConnection();
conn = dbConn.connection();
proc = conn.prepareCall("{call pa_internal_admin.fu_login(?,?,?,?)}");
proc.setString(1, clientID);
proc.setString(2, loginID);
proc.setString(3, password);
proc.setString(4, instName);
proc.execute();
response.sendRedirect("adminHome.jsp");
proc.close();
} catch (SQLException e) {
out.println("SQLException caught: " + e.getMessage());
} catch (Exception e) {
out.println(e);
} finally {
// Always close the database connection.
try {
if (conn != null)
conn.close();
} catch (SQLException ignored) {
out.println(ignored);
}
}
}
}
Dont change the visibility modifier
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
Consider to change to
protected void doPost( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
You are doing some mistake in post method, like you are type public. But, you should must change protected. First of all you must preview the code before to posting your question.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
DbConnection dbConn = null;
Difference between public and protected:
Modifier | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public | ✔ | ✔ | ✔ | ✔
————————————+———————+—————————+——————————+———————
protected | ✔ | ✔ | ✔ | ✘

Redirect to login page without using spring security

I am new to spring and creating an web application ,
I want to redirect to login page always when user is not authenticated and without using spring security.xml??
Is it possible with session management??
A simple way would be to use a 'HandlerInterceptorAdapator':
public class CheckUserInterceptor extends HandlerInterceptorAdapter {
#Resource
private UserSession userSession;
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws IOException {
if (request.getServletPath().equals("/login.htm")) {
return true;
}
String username = userSession.getUsername();
// If the username has not been set by the login controller
if (username != null) {
return true;
} else {
response.sendRedirect("login.htm");
return false;
}
}
}
In this case you need to declare the interceptor in the Spring XML file:
<mvc:interceptors>
<bean class="fr.unilim.msi.dad.web.mvc.CheckUserInterceptor" />
</mvc:interceptors>
Another approach, if for instance your Spring MVC controller are not configured to handle all requests, is to use a filter at the servlet level:
public class AccessControlFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession(true);
User user = (User) session.getAttribute("user");
if (user == null) {
String urlRoot = ((HttpServletRequest) request).getContextPath();
((HttpServletResponse)response).sendRedirect(urlRoot + "/login.jsp");
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
}
}
I guess you can do something like below in your login controller:
if(isUserAuthenticated())
{
return "home";
}
else
{
session.invalidate();
return "redirect:login";
}

How do I specify the URL to a WebSocketServlet in Jetty?

I have read Creating a WebSocket-Chat-Application with Jetty and I would like to create a simple echo websocket using a WebSocketServlet on Jetty.
I have created my WebSocketServlet like this:
public class ChatSocketServlet extends WebSocketServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html><body><h1>Chat</h1></body></html>");
}
#Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new ChatWebSocket();
}
class ChatWebSocket implements OnTextMessage {
private Connection connection;
#Override
public void onClose(int closeCode, String message) {
System.out.println("onClose");
}
#Override
public void onOpen(Connection connection) {
this.connection = connection;
}
#Override
public void onMessage(String data) {
try {
connection.sendMessage(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But what URL should I use to connect to this websocket? It seems that I can't use the #WebServlet (e.g. #WebServlet("/HelloServlet")) as I can with HttpServlet. I have tried to connect to:
ws://localhost:8080/MyJavaWeb/ChatWebSocket
but it returns Not Found. Is there any other annotation to specify the URLs for WebSocketServlet? And I don't know the URL for getting the output from doGet on this servlet either.

How to access HttpServletResponse staticly in spring MVC

I want to write some message to response if exceptions occur in controller ,To do this I need response object .Can I access current response/request object staticly or I have to pass this object to exception too.like in jsf (FacesContext.getCurrentInstance().getExternalContext().getResponse());
List<View_Probes> getAllProbes(HttpServletResponse response) throws ResourceNotFoundException{
try {
List<Probe> probes= inseptraPersistenceService.listAllProbes();
List<View_Probes> result= mapper.mapAll(probes, View_Probes.class);
return result;
} catch (Exception e) {
throw new ResourceNotFoundException(e);
}
}
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
}
public ResourceNotFoundException(Throwable e) {
super(e);
}
}

Resources