Jersey- Rest: 404 not found error - java

I am doing a simple program , the task is to Get (user id) from html form over Rest and username associated with should be displayed. I am
getting a 404 error when I load the index.html page.
But when i give the values(userid) over the url it works fine.
here's the code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index page</title>
</head>
<body>
<form action="http://localhost:8080/rest/my/first/rest/users" method="GET">
<label for="uid">ID</label>
<input name="uid" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and here is the resource class
#Path("users") //attach client request to resource: .../users
public class RestResource {
Map<String,User> listUsers;
//initialize some resources
public RestResource(){
listUsers = new HashMap();
listUsers.put("1",new User("1", "John"));
listUsers.put("2",new User("2", "Peter"));
}
//return list of users
#GET
#Produces(MediaType.TEXT_PLAIN)
public String listOfUsersInText(){
String list="";
for (Entry<String,User> u:listUsers.entrySet()){
list += u.getValue().getName() + "\n";
}
return list;
}
//return user information corresponding to the requested uid.
#GET
#Path("{uid}") //attach client request to resource: .../users/<uid>
#Produces(MediaType.TEXT_PLAIN)
public String getUID(#PathParam("uid") String uid){
if (!listUsers.containsKey(uid))
return "User not exist!";
return listUsers.get(uid).getID()+":"+listUsers.get(uid).getName();
}
}
WEB.xml
<display-name>rest</display-name>
<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>my.first.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

The approach you have followed is wrong we have several rest client api's you can use any of those and can send the request to rest resource
The response data you can display in jsp pages.

Related

Spring Security 3.1.3 Issues

I am using Spring Security 3.1.3.RELEASE in my maven pom because the book am reading is 2013 and that is what they used and have the following code snippets:
// AdminController
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
// LoginController
#Controller
#RequestMapping("")
public class LoginController {
#RequestMapping(method= {RequestMethod.GET, RequestMethod.POST}, value="/custom_login")
public String showLogin() {
return "login";
}
}
// web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>terrormovies</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>terrormovies</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
// Spring security Config :: applicationContext-security.xml
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**/*" access="ROLE_ADMIN" />
<security:form-login login-page="/custom_login" username-parameter="user_param" password-parameter="pass_param"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_ADMIN" name="admin" password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
//login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Terror movies</title>
</head>
<body>
<form action="/j_spring_security_check" method="POST">
Username<input type="text" name="user_param"/><br/>
Password<input type="password" name="pass_param"/><br/>
<input type="submit" value="Login"/>
</form>
</body>
<% if(request.getParameter("error") != null){
out.println("ERROR LOGIN");
}
%>
</html>
When I start my application I get the login page with the form alright. I enter admin/admin as username/password respectively. When i click on the login button I get this error page saying:
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
instead of going to the method createMovie(#RequestBody String movie) in the
AdminController.
The address of this error page is :: http://localhost:8080/admin/movies
The LoginController and AdminController are in the same package.
What am I missing here?
Updated
In the form action:: <form action="/j_spring_security_check" method="POST">,
where does "/j_spring_security_check"` leads to? I think that is where the problem is. Am beginner in Spring Security so I can't figure it out now. I did a search but not any good answer.
The error response message you are receiving tells you exactly what the problem is:
When i click on the login button i get this error page saying::
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
And in your controller you have set this method:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
And just as the message says, the /admin/movies method is mapped just for POST requests, so a GET request which is what is generated on redirection from the login success cannot be handled.
So here the trouble is not really the spring-security config, the problem is just that after login you are making a request to a request-mapping annotated method which does not support GET requests.
To solve it you could just configure this method into the existing AdminController:
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
And create a jsp with a form which points to the POST mapped controller method:
<form action="/admin/movies" method="POST">
Movie<input type="text" name="movie"/><br/>
<input type="submit" value="Login"/>
</form>
I would be easier too if you delete the #RequestBody annotation in the POST method, so finally the AdminController should end like this:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
}

Requested Resource is not available error [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm trying to build a twitter search using jsp, servlet, Tomcat-6.0.43 and eclipse and getting HTTP Status 404 error. Can anyone please check where am I going wrong.
My Code:
first.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ServletValues.java" method="get">
Enter Twitter Search Details : <input type="text" name="first"><br>
<input type="submit">
</form>
</body>
</html>
TwitterServlet.java:
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TwitterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TwitterServlet() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CONSUMER_KEY = "[data]";
String CONSUMER_KEY_SECRET = "[data]";
String AccessToken = "[data]";
String AccessTokenSecret = "[data]";
response.setContentType("text/html");
String input1 = request.getParameter("first");
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken oathAccessToken = new AccessToken(AccessToken, AccessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
List<Status> status = twitter.getUserTimeline(input1);
for (Status status2 : status)
{
System.out.println("---Tweet---"+status2.getText());
}}catch (TwitterException te){
System.out.println("Error occured "+te);
}
super.doPost(request, response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>
Twitter12</display-name>
<servlet>
<description>
</description>
<display-name>
TwitterServlet</display-name>
<servlet-name>TwitterServlet</servlet-name>
<servlet-class>
TwitterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</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>
Error: HTTP Status 404 - /Twitter12/ServletValues.java
type Status report
message /Twitter12/ServletValues.java
description The requested resource is not available.
In your jsp file form action, Replace
<form action="ServletValues.java" method="get">
With
<form action="TwitterServlet" method="get">
Since in your web.xml your servlet mapping pattern is TwitterServlet for the Servlet class that you intend to call.
Also in your servlet you are just printing to System.out while you should write into the reponse stream using
response.getOutputStream().write("---Tweet---"+status2.getText());
so that it shows up in the response
Change your form action to:​
<form action="/TwitterServlet" method="get">
your servlet url is /TwitterServlet as you have defined
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>

Import servlet in JSP Index => Null parameter

I'm currently working on a school project. We have to do a small market website in Java.
I've a small problem. I have an Index.jsp where i want to include a servlet (RandomArticle.jsp). This servlet have a .jsp and a .java and just shuffle a collection and return names.
When I display index.jsp, the html of RandomArticle.jsp is well displayed (so the include is correct) but the returned name are "null".
Here is some code:
Index.jsp (in WebContent of eclipse)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Market</title>
</head>
<body>
<header>
<h1>market 2013</h1>
<h2>Bievenue </h2>
</header>
<nav>
<% String include = "/WEB-INF/RandomArticle.jsp"; %>
<jsp:include page='<%=include%>' />
</nav>
</body>
</html>
RandomArticle.jsp (in WEB-INF):
<h1>Liste des produits EpiMarket</h1>
<%
String productName1 = (String) request.getAttribute("productName1");
String productName2 = (String) request.getAttribute("productName2");
String productName3 = (String) request.getAttribute("productName3");
%>
<p>Acheter <% out.println(productName1); %></p>
<p>Acheter <% out.println(productName2); %></p>
<p>Acheter <% out.println(productName3); %></p>
Web.xml
<?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">
<display-name>Market</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>fr.market.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RandomArticle</servlet-name>
<servlet-class>fr.market.servlets.RandomArticle</servlet-class>
</servlet>
</web-app>
and RandomARticle.java
public class RandomArticle extends HttpServlet {
private ArrayList<Object> allProducts;
public String getProductName(int index){
return (((AbstractProduct) allProducts.get(index)).getName());
}
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
ADAO<AbstractProduct> dao = new DAOProduit();
allProducts = ((DAOProduit) dao).getAll();
Collections.shuffle(allProducts);
request.setAttribute("productName1", getProductName(0));
request.setAttribute("productName2", getProductName(1));
request.setAttribute("productName3", getProductName(2));
this.getServletContext().getRequestDispatcher( "/WEB-INF/RandomArticle.jsp" ).forward( request, response );
}
}
I think that the .java is never called, but I don't understand why.
Thanks for your time.
Gilles

Resource not found due to misconfiguration

I am developing a Web application based on Tomcat 7, and bumped in a situation where I have no clue what and why is happening. After typing my login credentials in JSP page below:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<div id="form">
<form method=POST name=login_form action=Login>
Usuário: <input type=text name=username> <br/>
Senha: <input type=password name=password> <br/>
<input type="submit" value="Entrar">
<span class="error">${error}</span>
</form>
</div>
</body>
</html>
I receive the following message, regardless if I entered the right or wrong credentials:
HTTP Status 404 - /WebApp/Login
type Status report
message /WebApp/Login
description The requested resource is not available.
Apache Tomcat/7.0.42
The implementation for the method doPost of the servlet class is the following:
String username = request.getParameter("username");
String password = request.getParameter("password");
Date data_login = new Date(System.currentTimeMillis());
java.sql.Timestamp nova_data = new java.sql.Timestamp(0, 0, 0, 0, 0, 0, 0);
nova_data.setDate(data_login.getDay());
nova_data.setMonth(data_login.getMonth());
nova_data.setYear(data_login.getYear());
nova_data.setHours(data_login.getHours());
nova_data.setMinutes(data_login.getMinutes());
nova_data.setSeconds(nova_data.getSeconds());
DataHelper dhelper = new DataHelper();
try {
System.out.println("Registrando login...");
user temp = dhelper.doProcessaLogin(username, password);
if (temp != null) {
String fname = temp.getFirstName();
String lname = temp.getLastName();
int id = temp.getId();
System.out.println("Dados corretos");
request.getSession().setAttribute("user", fname+" "+lname);
dhelper.doRegistraSessao(fname, lname, nova_data, id);
Cookie ck = new Cookie("User",fname+" "+lname);
ck.setMaxAge(7);
response.addCookie(ck);
request.getRequestDispatcher("/WEB-INF/menu.jsp")
.forward(request,response);
}
else {
System.out.println("Dados incorretos");
request.getSession().setAttribute("erro",
"Não foi possivel efetuar o login");
System.out.println("Direcionando de volta para a pagina de login");
request.getRequestDispatcher("/login").forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have an implementation for a method doGet too:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
my web.xml is the following:
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.webapp.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
I really don't know the reason the system is looking for /WebApp/Login instead of /WebApp/login, which is what was declared in the web.xml. Someone can see any problem with the code above?
Try replacing action=Login by action=login (lowercase L) in your JSP page. Tomcat is case sensitive and you declared the URL pattern for the servlet mapping as "/login". If it still doesn't work, try with action=/login.
The problem is in your form page. See where it says action=Login (you should use quotes, by the way, both for readability and for safety)? That's telling the Web browser that the URL it should submit to is Login relative to the page it's already on, which is probably /WebApp/index.jsp. Fix that form tag.

JSP getParameters

I have a simple JSP project, which has 3 classes, controllers and DAO's
I can Login but when I click on my buttons, I just can't get the Parameters from the form.
Lemme show the code, and maybe You'll figure it out:
package school.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import school.dao.StudentDAO;
import school.model.Student;
public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String UPDATE = "/student.jsp";
private static String VIEW_COURSES = "CourseController";
private static String VIEW_GRADES = "GradeController";
private StudentDAO dao;
public StudentController() {
dao = new StudentDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("name");
if (action.equalsIgnoreCase("update")) {
forward = UPDATE;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewgrades")) {
forward = VIEW_GRADES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewcourses")) {
forward = VIEW_COURSES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here's the WEB.xml
<?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>School_JSP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CourseController</display-name>
<servlet-name>CourseController</servlet-name>
<servlet-class>school.controller.CourseController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>StudentController</display-name>
<servlet-name>StudentController</servlet-name>
<servlet-class>school.controller.StudentController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>school.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentController</servlet-name>
<url-pattern>/StudentController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CourseController</servlet-name>
<url-pattern>/CourseController</url-pattern>
</servlet-mapping>
</web-app>
And the mainPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h3>
Welcome,
<c:out value="${student.firstName}" />
</br>
<h1>My Personal Information</h1>
<center>
<form method="POST" action='StudentController' name="viewgrades">
<input type="submit" value="View My Grades" />
</form>
<form method="POST" action='StudentController' name="viewcourses">
<input type="submit" id="hidden" value="View My Courses" />
</form>
<form method="POST" action='StudentController' name="update">
<input type="submit" id="hidden" value="Update Personal Information" />
</form>
</center>
</h3>
</body>
</html>
You're confusing attributes and parameters.
Parameters are String values sent by the browser. They're accessed using the getParameterXxx() family of methods.
Attributes are data that you can add to a request (or session, or servlet context), or any type, in order to get them backlater. You typically add an attribute to the request in a servlet (for example, the information about the logged in user) in order to get back this attribute in the JSP and display the information.
In your code, the only place where you get a parameter is commented out. And you're trying to get a parameter named "hidden", although none of the form has an input field with than name. It's the name attribute of an input field that is submitted by the browser, and not its id attribute.
Also, you should use GET rather than POST for actions which consist in getting or reading things.
The reason you don't get any values is that the attribute "name" in the form, indeed is just the name of the form and isn't sent at all.
To actually send data, you need to provide some in the innerHTML of the form. Like this (not the best solution, but should you get running):
<form method="GET" action="StudentController" name="formName">
<input type="hidden" name="viewgrades" value="show" />
<input type="submit" value="View My Grades" />
</form>
After this you can read the sent data "viewgrades=show" (parameter=value) in your Java-class.
Also, btw, you shouldn't use "h3" as a paragraph ("p") or section. It is intended to be a headline.

Categories

Resources