user1245524 user1245524 - 28 days ago 7
AngularJS Question

AngularJS $http GET request returning 404 though corresponding Java method is executed

Firing AngularJS Rest URL as a GET request from AngularJS, its
returning 404 though its hitting the required method on server
side (spring implementation) and producing the desired Result

Below is the method firing the angularjs request

getCredentials : function(){
return $http.get('/helloRest/getUsername');
}


The above method results in the below URL

URL : http://localhost:8083/helloRest/getUsername

below is the stack traces

<body>
<h1>HTTP Status 404 - /helloRest/getUsername</h1>
<div class="line"></div><p><b>type</b> Status report</p><p>
<b>message</b>
<u>/helloRest/getUsername</u></p><p>
<b>description</b>
<u>The requested resource is not available.</u></p>
<hr class="line"><h3>Apache Tomcat/8.0.37</h3></body></html>


web.xml

<web-app>

<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>

<servlet>
<servlet-name>test</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/test-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>


Below is test-server.xml(dispatcher servlet)

<beans>
<context:annotation-config/>
<mvc:annotation-driven />

<context:component-scan base-package="com.org.simpro"/>

<jpa:repositories base-package="com.org.simpro"></jpa:repositories>

<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>

<bean id="HelloWorldRestController" class="com.org.simpro.controller.HelloWorldRestController">
<property name="userService" ref="userServiceImpl"></property>
</bean>

<bean id= "userServiceImpl" class="com.org.simpro.service.UserServiceImpl">
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="HR"/>
<property name="password" value="hr"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"></property>
<property name="packagesToScan" value="com.org.simpro.model" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<!--
<prop key="javax.persistence.schema-generation.database.action">none</prop>
<prop key="hibernate.ejb.use_class_enhancer">true</prop>

//jpa hibernate properties
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.format_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=false
-->
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
<import resource="security-context.xml"/>

</beans>


Below is the security-context.xml


<security:http auto-config="true" use-expressions="false">


<security:form-login login-page="/login"
login-processing-url="/authenticate"
authentication-failure-url="/login?error=true"
username-parameter="username" password-parameter="password"/>


<security:intercept-url pattern="/" access="ROLE_USER"/>
<security:intercept-url pattern="/authenticate" access="ROLE_USER"/>

<security:csrf disabled="true"/>
</security:http>


<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="password"
authorities="ROLE_USER"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>


Below is the method which the URL is hitting

@RequestMapping(value="/getUsername",method=RequestMethod.GET)
public void authenticateUser(HttpServletRequest hreq){
System.out.println("credentials are");
Principal principalObject = (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

System.out.println("security"+principalObject.toString());

}


The AngularJS $http request is returning me 404,though the above java
method is executing successfully. I should get 200 instead of 404
as the server response, Could you kindly check this

@RequestMapping(value="/helloRest")
public class HelloWorldRestController {


public UserService getUserService() {
return userService;
}


public void setUserService(UserService userService) {
this.userService = userService;
}

@RequestMapping(value="/getUsername",method=RequestMethod.GET)
public void authenticateUser(){
System.out.println("credentials are");
Principal principalObject =(Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

System.out.println("security"+principalObject.toString());


}

@Autowired
UserService userService; //Service which will do all data retrieval/manipulation work



@RequestMapping(value = "/pullusers/", method = RequestMethod.GET )
public ResponseEntity<Iterable<User_ex>> listAllUser_exs() {
Iterable<User_ex> users = userService.findAllUsers();
System.out.println(users.toString());
//return null;
/*if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}*/
return new ResponseEntity<Iterable<User_ex>>(users, HttpStatus.OK);
}


//-------------------Retrieve Single User--------------------------------------------------------

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User_ex> getUser(@PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User_ex user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User_ex>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User_ex>(user, HttpStatus.OK);
}



//-------------------Create a User--------------------------------------------------------

@RequestMapping(value = "/persistuser/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User_ex user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getName());

if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getName() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}

userService.saveUser(user);

HttpHeaders headers = new HttpHeaders();
//headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}


//-------------------check if particular user exists or not----------------------------------------------------------
@RequestMapping(value="/authenticate", method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User_ex> isCurrentUserExists(String username, String password){
System.out.println("A User with name " + username +password+ "exist");
User_ex user = userService.isUserLoginExist(username,password);
if(user != null){
return new ResponseEntity<User_ex>(user,HttpStatus.OK);
}

return null;
}




//------------------- Update a User --------------------------------------------------------

@RequestMapping(value = "/updateuser/{id}", method = RequestMethod.PUT)
public ResponseEntity<User_ex> updateUser(@PathVariable("id") long id, @RequestBody User_ex user) {
System.out.println("Updating User " + id);

User_ex currentUser = userService.findById(id);

if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User_ex>(HttpStatus.NOT_FOUND);
}

currentUser.setName(user.getName());
currentUser.setAge(user.getAge());
currentUser.setSalary(user.getSalary());

userService.updateUser(currentUser);
return new ResponseEntity<User_ex>(currentUser, HttpStatus.OK);
}

//------------------- Delete a User --------------------------------------------------------

@RequestMapping(value = "/removeuser/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User_ex> deleteUser(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);

User_ex user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User_ex>(HttpStatus.NOT_FOUND);
}

userService.deleteUserById(id);
return new ResponseEntity<User_ex>(HttpStatus.NO_CONTENT);
}


//------------------- Delete All Users --------------------------------------------------------

@RequestMapping(value = "/removeusers/", method = RequestMethod.DELETE)
public ResponseEntity<User_ex> deleteAllUsers() {
System.out.println("Deleting All Users");

userService.deleteAllUsers();
return new ResponseEntity<User_ex>(HttpStatus.NO_CONTENT);
}


}

Answer

try,

@RequestMapping(value="/getUsername",method=RequestMethod.GET)
public ResponseEntity authenticateUser(){
    System.out.println("credentials are");
    Principal principalObject =(Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    System.out.println("security"+principalObject.toString());

    return new ResponseEntity(HttpStatus.OK);


}