Hi all I want to return a userName with a rest http request in Spring + Mysql.
Controller:
#Controller
#SessionAttributes("user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUserName(#PathVariable String userName) {
return userName;
}
}
Model:
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
I just want to retrieve my services put,delete,post and get with requestmappings connecting with my model to my mysql DB. I´m trying to make the request in this way:
http://localhost:8080/portuzona/userss?userName=Arnoldo
But I get this:
HTTP Status 404 - /portuzona/userss
type Status report
message /portuzona/userss
description The requested resource is not available.
portuzona and userss is correctly handled (html views) but I cannot make a get in my controllers.
Log says correctly the Table has been found by the bean:
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: portuzona.users
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dateofbirth, password, firstname, emailaddress, id, username, lastname, status]
As a User requested here is more info that could be help .. or not:
/WEB-INF/servlet.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">
<servlet>
<servlet-name>usersHibernateServlet</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>usersHibernateServlet</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>
/WEB-INF/config/servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.portuzona" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
</beans>
Looks like you're mixing up mapping and path variables. Two options:
1:
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUname(#PathVariable String userName) {
return userName;
}
http://localhost:8080/portuzona/userss/Arnoldo
2:
#RequestMapping(method=RequestMethod.GET, value="/userss/yourmapping")
public #ResponseBody String getUserName(#RequestParam String username) {
return username;
}
http://localhost:8080/portuzona/userss/yourmapping?username=Arnoldo
Try the following with http://localhost:8080/portuzona/userss?userName=Arnoldo
#RequestMapping(method=RequestMethod.GET, value="/userss")
public #ResponseBody String getUserName(#RequestParam String userName) {
return userName;
}
Related
I am learning Spring framework. I have created a sample project with SpringMVC with REST + JSON. I can able to compile successfully but when i hit the rest url, the system says below message
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Below is the springmvc-servlet.xml
<context:component-scan base-package="com.springmvc.beans" />
<context:annotation-config />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter" />
</list>
</property>
</bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
And the Web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
And the EmployeeController.java
package com.springmvc.beans;
import java.util.HashMap;
import java.util.Map;
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 org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class EmployeeController {
public static final String GET_EMPLOYEE = "/rest/employee/{empId}";
public static final String CREATE_EMPLOYEE = "/rest/employee/create/";
public static final String DELETE_EMPLOYEE = "/rest/employee/delete/{empId}";
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
private Map<String, Employee> employeeData = new HashMap<String, Employee>();
private Integer count = 1;
#RequestMapping(method=RequestMethod.GET, value=GET_EMPLOYEE)
public #ResponseBody Employee getEmployee(#PathVariable ("empId") String empId){
return employeeData.get(empId);
}
#RequestMapping(method=RequestMethod.PUT, value=CREATE_EMPLOYEE)
public #ResponseBody void createEmployee(){
employeeData.put(String.valueOf(count++), new Employee(String.valueOf(count++), "Batman"+Math.random(), "23"+Math.random(), "Andartica"+Math.random(), "dash2#gmail.com"+Math.random()));
}
#RequestMapping(method=RequestMethod.PUT, value=DELETE_EMPLOYEE)
public #ResponseBody void deleteEmployee(#PathVariable ("empId") String empId){
employeeData.remove(empId);
}
#RequestMapping(method=RequestMethod.GET, value=GET_ALL_EMPLOYEES)
public #ResponseBody Map<String, Employee> getAllEmployees(){
return employeeData;
}
{
employeeData.put(String.valueOf(count), new Employee("1", "Mani", "31", "America", "Dash#gmail.com"));
}
}
Finally the Employee.java pojo
package com.springmvc.beans;
/**
* #author Mani
*
*/
public class Employee {
private String empId;
private String name;
private String age;
private String address;
private String email;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee(String empId, String name, String age, String address, String email) {
super();
this.empId = empId;
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
}
Note : My Spring version is 4.1 and I have added below jars in my classpath to convert output to JSON message
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
Kindly help to solve this.
Thanks in Advance
Manivannan
looking at the code the endpoint is mapped to
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
where as the url being accessed is
/SpringMVC/rest/employee
org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Try making as below:
GET_ALL_EMPLOYEES = "/rest/employee";
This is my DateDeserializer class :
public class DateDeserializer extends StdDeserializer<Date>
{
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public DateDeserializer()
{
this(null);
}
public DateDeserializer(Class<?> vc) {
super(vc);
}
#Override
public Date deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException, JsonProcessingException {
String date = arg0.getText();
try
{
return formatter.parse(date);
}
catch(ParseException e)
{
throw new RuntimeException(e);
}
}
}
And this is how I annotate the setter (appears also in getter method) of the Date attribute in my entity :
#JsonDeserialize(using = DateDeserializer.class, as = Date.class)
public void setDate(Date date) {
this.date = date;
}
When I send request in json format , the date has the format like in the deserializer method, but I get the following error :
"Can not construct instance of java.util.Date from String value"
Should I inject the deserializer to jersey somewhere ?
I don't understand what I do wrong.
Here is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<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" version="2.5">
<!-- Configure ContextLoaderListener to use JavaConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified #Configuration classes -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.sharon.trempiada.resources.ResourcesConfiguration org.sharon.trempiada.services.ServicesConfiguration</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>trempiada</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.sharon.trempiada.resources,org.glassfish.jersey.jackson</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>trempiada</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
My model class :
#Entity
#Table(name = "TBRIDES")
public class Ride
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name= "ride_id")
private int id;
#Column
private String source;
#Column
private String destination;
#Column
#JsonDeserialize(using = DateDeserializer.class)
private Date date;
#Column
private Time time;
#Column
private boolean isPermanent;
#Column
#JsonDeserialize(using = DateDeserializer.class)
private Date expirationDate;
#ManyToOne
#JoinColumn(name="driver_id", nullable= false)
private User user;
#Column
private String comments;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
public boolean isPermanent() {
return isPermanent;
}
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
So I´m trying to make an application with all http request get, put, post, delete.I'm making first a login with mysql and spring 3. So here I got this:
login.jsp:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="UsersLogin">
signup.jsp
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="Users">
persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="{http://java.sun.com/xml/ns/persistence} {http://java.sun.com/xml/ns/persistence_2_0.xsd}"
version="2.0">
<persistence-unit name="punit">
</persistence-unit>
</persistence>
Here is my jpaContext.xml:
<context:annotation-config />
<jpa:repositories base-package="com.portuzona.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/portuzona?autoReconnect=true&createDatabaseIfNotExist=true&" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
</beans>
com.portuzona.model
Users model:
#Entity
#Table(name="users")
public class Users {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
USersLogin model:
public class UsersLogin {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
com.portuzona.service
public interface UsersService {
Users save(Users users);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
}
Implementation:
#Service("UsersService")
public class UsersServiceImpl implements UsersService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Users save(Users users) {
return usersRepository.save(users);
}
public boolean findByLogin(String userName, String password) {
Users stud = usersRepository.findByUserName(userName);
if(stud != null && stud.getPassword().equals(password)) {
return true;
}
return false;
}
public boolean findByUserName(String userName) {
Users use = usersRepository.findByUserName(userName);
if(use != null) {
return true;
}
return false;
}
}
com.portuzona.repository
#Repository("UsersRepository")
public interface UsersRepository extends JpaRepository<Users, Long> {
#Query("SELECT s FROM users s WHERE s.userName = :userName")
Users findByUserName(#Param("userName") String userName);
}
com.portuzona.controller
#Controller
#SessionAttributes("users")
public class UsersController {
#Autowired
private UsersService userService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("users") Users users, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(userService.findByUserName(users.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
userService.save(users);
model.addAttribute("message", "Saved users details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
UsersLogin usersLogin = new UsersLogin();
model.addAttribute("UsersLogin", usersLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("UsersLogin") UsersLogin usersLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = userService.findByLogin(usersLogin.getUserName(), usersLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
I got this error when trying to access to /login or /signup where I have my .jsp with my forms:
sep 24, 2015 11:14:35 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet usersHibernateServlet
org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [SELECT s FROM users s WHERE s.userName = :userName]
I have been with this for two days, looking for answers here but no kind of good results from my side... just gives me the same error, any idea?
I have a entity class group.
before change
#Entity
#Table(name = "Group")
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
#Deprecated
public Group() {
// Do not Use. Required by JPA Spec
}
public Group(Long id) {
this.id = id;
}
#Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#NotNull
#Size(min = 2, max = 75)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (o instanceof User) {
return getId().equals(((Group) o).getId());
}
else {
return false;
}
}
Now I changed the max size of the name from 75 to 1000.
#Entity
#Table(name = "Group")
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
#Deprecated
public Group() {
// Do not Use. Required by JPA Spec
}
public Group(Long id) {
this.id = id;
}
#Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#NotNull
#Size(min = 2, max = 1000)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (o instanceof User) {
return getId().equals(((Group) o).getId());
}
else {
return false;
}
}
After this change the length of the name in the database is not getting changd from 75 to 1000.
The persistance.xml looks like
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="primary" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/sampleDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Hibernate's schema update feature (hibernate.hbm2ddl.auto=update) is very limited and cannot be relied on. It will add new tables, fields and foreign keys, but that's about all it does.
If your schema changes, you'll need some kind of migration mechanism, such as Liquibase. Relying on Hbm2ddl in production is a recipe for disaster.
I am having rest method in spring controller like below:
#RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
#ResponseBody
public String getUserName(HttpServletRequest request,#PathVariable String userName ){
System.out.println("User Name : "+userName);
return "available";
}
In jquery I have writeen ajax call like:
$(document).ready(function(){
$('#userName').blur(function(){
var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();
$.ajax({
type : "get",
URL : methodURL,
data : $('#userName').val(),
success : function(data){
alert(data);
$('#available').show();
}
})
});
});
In web.xml I have:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In spring-servlet.xml I have the view resolver like below:
<context:component-scan base-package="com.users.controller" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When I am running this in server, it is not going to controller.
Please let me know the problem with this code.
Please can any one help on this.
Regards,
Shruti
Since you have the #RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.
var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";
But you have also a problem in your RequestMapping value, it should start with /
#RequestMapping(value="/register/{userName}"
Also I doubt that you need the ".html" at the end
Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like #Controller and #RequestMapping
<mvc:annotation-driven />
Example of an annotated controller
Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)
You controller class would look something like the following.
#Controller
#RequestMapping(value="/users")
class UserController {
#ResponseBody
#RequestMapping(value="/register/{username}", method=RequestMethod.GET)
public String registerUser(#PathVariable String username) {
return username;
}
}
Please find my solution for calling REST web-services in Spring Framework.
/**
* REST API Implementation Using REST Controller
* */
#RestController
public class RestReqCntrl {
#Autowired
private UserService userService;
#Autowired
private PayrollService payrollService;
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<User> registerUser(#RequestBody User user, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.registerUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
}
//-------------------Authenticating the User--------------------------------------------------------
#RequestMapping(value = "/authuser", method = RequestMethod.POST)
public ResponseEntity<User> authuser(#RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.authUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Company--------------------------------------------------------
#RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
public ResponseEntity<String> registerCompany(#RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
String result ="";
boolean flag = payrollService.registerCompany(comypanyDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Employee--------------------------------------------------------
#RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
public ResponseEntity<String> registerEmployee(#RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
String result ="";
boolean flag = payrollService.registerEmpbyComp(employeeDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Get Company Deatils--------------------------------------------------------
#RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("getCompanies getCompanies ");
List<ComypanyDTO> comypanyDTOs =null;
comypanyDTOs = payrollService.getCompanies();
//Setting the Respective Employees
for(ComypanyDTO dto :comypanyDTOs){
dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
}
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="USER_TABLE")
public class User implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
private String email;
private String userId;
private String password;
private String userType;
private String address;
#Transient
private int statusCode;
#Transient
private String statusDesc;
public User(){
}
public User(String firstName, String lastName, String email, String userId, String password, String userType,
String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userId = userId;
this.password = password;
this.userType = userType;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userType
*/
public String getUserType() {
return userType;
}
/**
* #param userType the userType to set
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* #param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* #return the statusDesc
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* #param statusDesc the statusDesc to set
*/
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}