I am following up this tutorial
https://www.javacodegeeks.com/2014/03/building-java-web-application-using-hibernate-with-spring.html
I am having this error >>>> the requested resource could not be found
web.xml file content
<?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">
<servlet>
<servlet-name>studentHibernateServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servletConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>studentHibernateServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/jpaContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Archetype Created Web Application</display-name>
</web-app>
The controller content
package com.github.elizabetht.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.github.elizabetht.model.Student;
import com.github.elizabetht.model.StudentLogin;
import com.github.elizabetht.service.StudentService;
#Controller
#SessionAttributes("student")
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Student student = new Student();
model.addAttribute("student", student);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("student") Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(studentService.findByUserName(student.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
studentService.save(student);
model.addAttribute("message", "Saved student details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
StudentLogin studentLogin = new StudentLogin();
model.addAttribute("studentLogin", studentLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = studentService.findByLogin(studentLogin.getUserName(), studentLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
Please assist me I a beginner
Your dispatcher servlet only listens to *.html. You can either call a url having this as its suffix, i.e.:
http://localhost::8080/[YourAppName]/[filename].html
Or you can change the servlet mapping to something more generic:
<servlet-mapping>
<servlet-name>studentHibernateServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
and call i.e.:
http://localhost::8080/[YourAppName]/signup
Update
Your servlet version is set to 2.5 which is very old. Its 3.1 at the moment. You might want to update it, to at least 3.0 for Tomcat 7, for example. Therefore the tutorial is a little outdated too, search for Spring 4 MVC to find modern ones.
Related
I am new to Spring and trying to make integration between spring and primefaces. I am getting 404 page no found when I run the project on tomcat after adding the ContextLoaderListener and RequestContextListener.
My web.xml file:
<?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_2_5.xsd"
id = "WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
and this is my faces-config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
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-facesconfig_2_3.xsd"
version="2.3">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
</navigation-rule>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>viewRecords</from-outcome>
<to-view-id>view.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</faces-config>
and following is my controller class:
package com.testtask.nagarro.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.hibernate.annotations.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.testtask.nagarro.forms.LoginForm;
import com.testtask.nagarro.forms.StatementForm;
import com.testtask.nagarro.interfaces.StatementRepository;
import com.testtask.nagarro.interfaces.UserService;
import com.testtask.nagarro.models.Statement;
#Controller
public class NagarroController {
#Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value= "/", method=RequestMethod.GET)
public String loginPage() {
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("login");
return model;
}
#RequestMapping(value="/viewRecords", method = RequestMethod.POST)
public String showHomePage(StatementForm form) {
System.out.println("In view records controller");
List<Statement> records = getUserService().getRecordsByAccountId(form.getAccountId());
return "view";
}
#RequestMapping(method=RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map<String, LoginForm> model) {
String username = "UserName";
String password = "password";
if(result.hasErrors()) {
return "loginform";
}
loginForm = (LoginForm) model.get("loginForm");
if(!loginForm.getUsername().equals(username) || !loginForm.getPassword().equals(password)) {
return "loginForm";
}
model.put("loginForm", loginForm);
return "home";
}
}
I tried to find a solution online but I am confused because most of the examples are using jsps.
please point me to the problem, I am attaching the github link.
Your views are NOT in webapp/WEB-INF folder as you defined in your InternalViewResolver bean.
They are located in webapp folder.
I have an AngularJS client trying to consume a REST Web Service on Wildfly.
It works when the server returns an object, but when an exception is thrown, I'm getting the following message:
XMLHttpRequest cannot load
http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:51647' is therefore not allowed
access. The response had HTTP status code 500.
I tried lots of combinations of headers and filters, but nothing can make this works.
Client code:
var user = {
email : $scope.signUpData.email,
password : $scope.signUpData.password,
name : $scope.signUpData.name
};
$http.post(
'http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create',
user).
then(function(data) {
console.log("It works!");
},
function(response) {
console.log(response);
});
Web Service
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import br.com.produtos.business.UserBO;
import br.com.produtos.business.exceptions.BusinessException;
import br.com.produtos.entity.User;
import br.com.produtos.transaction.Transaction;
#Path("/user")
public class UserREST {
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON })
public User createAcount(#Context HttpServletRequest httpServletRequest, User user) throws BusinessException {
if (user.getEmail().equals("fff")) {
throw new BusinessException("Bussiness error.");
}
{...}
return user;
}
}
ExceptionMapper
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity(throwable.getMessage()).build();
}
}
Application
#ApplicationPath("/rest")
public class ThisApplication extends Application {
public static CorsFilter cors;
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ThisApplication() {
CorsFilter filter = new CorsFilter();
filter.getAllowedOrigins().add("*");
cors = filter;
singletons.add(filter);
singletons.add(new ThrowableMapper());
singletons.add(new UserREST());
}
public Set<Class<?>> getClasses() {
return empty;
}
public Set<Object> getSingletons() {
return singletons;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ProdutosBackend</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>br.com.produtos.rest.ThisApplication</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I solved the problem returning the message encapsulated into a json string.
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity("{ \"message\": \"" + throwable.getMessage() + "\" }").build();
}
}
I met a surious problem when I want to develop an API to call an "exterior" method (this method is called "createClientNode" which is a simple request for neo4j).
Anyways, this is my 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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>API</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>API</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>/API/*</url-pattern>
</servlet-mapping>
</web-app>
And this my class :
package API;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.neo4j.graphdb.Node;
import function.query.weceipt.GraphManagement;
#Path("/API")
public class MyService {
#POST
#Path("/node")
#Produces({ MediaType.APPLICATION_JSON })
public Node createNode(#DefaultValue("default_id") #QueryParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.createClientNode(id);
return node;
}
#GET
#Path("/node/{ID}")
#Produces({ MediaType.APPLICATION_JSON })
public Node getNode(#PathParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.getClientNode(id);
return node;
}
#Path("/test")
#GET
#Produces(MediaType.TEXT_PLAIN)
public void afficher() {
System.out.println("test");
}
}
the error that I get is "the Servlet jersey-serlvet is not available".
I have the impression that I have-perhaps- a problem with a specific JAR or Tomcat, but I coudn't find the cause of this problem. So, can anyone help me please because I tried a loooong time with this!
package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.test.dao.UserDAOImpl;
import com.test.model.User;
#Controller
#RequestMapping("/service/user/")
public class SpringRestController {
UserDAOImpl userDAOImpl=new UserDAOImpl();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userDAOImpl.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userDAOImpl.getAllUsers();
return users;
}
}
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>sample</display-name>
<servlet><servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
url
localhost:8080/sample/service/user/
I am getting this error please help me to resolve this error.I am using spring json rest. This error mostly comes at the time of giving request.
I have a Simple Web Service returning JSON data.
The User Class (com.bargadss.SpringService.Domain) is The POJO class containing
user_ID, firstName, lastName, eMail
The UserService class (com.bargadss.SpringService.DAO) two major operation
getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User}
getUserById(int user_ID) -> Queries the DB to Select a specific user based on ID
The SpringServiceController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bargadss.SpringService.DAO.UserService;
import com.bargadss.SpringService.Domain.User;
#RestController
#RequestMapping("/service/user/")
public class SpringServiceController {
UserService userService=new UserService();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userService.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
The ListUserController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.bargadss.SpringService.Domain.User;
#Controller
public class ListUserController {
#RequestMapping("/listUsers")
public ModelAndView listUsers() {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/";
List<LinkedHashMap> users=restTemplate.getForObject(url, List.class);
return new ModelAndView("listUsers", "users", users);
}
#RequestMapping("/dispUser/{userid}")
public ModelAndView dispUser(#PathVariable("userid") int userid) {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/{userid}";
User user=restTemplate.getForObject(url, User.class,userid);
return new ModelAndView("dispUser", "user", user);
}
}
The CorsFilter (com.bargadss.CORS) is as follows :
package com.bargadss.CORS;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter{
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
The web.xml is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringServiceWithRESTAndJSONExample</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.bargadss.CORS.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The Web Service when being invoked by AngularJS from another Web Server returns Error referring to Cross Origin Resource Sharing problem !!!
What Changes must be performed in the Controller side to eliminate the error ?
Is there any changes necessary to be done at the AngularJS side to avoid this situation ?
Check the cors-filter
Download cors-filter-2.1.2.jar and java-property-utils-1.9.1.jar.
mvn dependency
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.9.1</version>
</dependency>
and in web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>