I want to create an application with Spring MVC Rest Web services and angularJs. So my probleme is when i put in my controller @Controller everythings works (I have my page home1.jsp) but when i use @RestController my browser display a String ("home1"). Can you please help to understand my probleme, Thanks. Here is my code: *AppController

@RestController
@RequestMapping("/service")
public class AppController {

    @Autowired
    MyService myService;

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/home1", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );

        return "home1";
    }

    // GET ALL
    @RequestMapping(value="/allProfiles",method = RequestMethod.GET,headers="Accept=application/json")
    public List<Profil> getProfils()
    {
        System.out.println("RestControllern methode initialized");
        return myService.getAllProfiles();
    }

    @RequestMapping(value="/allPatterns",method = RequestMethod.GET,headers="Accept=application/json")
    public @ResponseBody List<Pattern> getPatterns()
    {
        logger.info("Welcome home! allPatterns {}.");
        System.out.println("RestControllern methode initialized");
        Pattern p = new Pattern();
        p.setId(5);
        p.setValue("moiuuyyt");
        return myService.getAllPattern();

    }

    @RequestMapping(value="/allComponents",method = RequestMethod.GET,headers="Accept=application/json")
    public List<Component> getComponents()
    {
        return myService.getAllComponent();
    }

    //GET ONE
    @RequestMapping(value="/components/{id}",method = RequestMethod.GET,headers="Accept=application/json")
    public Component getComponent(@PathVariable int id)
    {
        return myService.getComponentById(id);
    }

    @RequestMapping(value="/profiles/{id}",method = RequestMethod.GET,headers="Accept=application/json")
    public Profil getProfil(@PathVariable int id)
    {
        return myService.getProfilById(id);
    }

    @RequestMapping(value="/patterns/{id}",method = RequestMethod.GET,headers="Accept=application/json")
    public Pattern getPattern(@PathVariable int id)
    {
        return myService.getPatternById(id);
    }

    //SAVE
    @RequestMapping(value="/addpattern/{value}",method= RequestMethod.POST,  headers="Accept=application/json")
    public String addPattern(@PathVariable String value)
    {
        Pattern pat = new Pattern();
        pat.setValue(value);
        myService.addPattern(pat);
        return "redirect:/service/allPatterns";
    }

    @RequestMapping(value="/addprofil",method = RequestMethod.POST,headers="Accept=application/json")
    public void addProfil()
    {
        Profil pr = new Profil();
        pr.setProfilName("Profil1");
        myService.addProfil(pr);
    }

    @RequestMapping(value="/addcomponent",method = RequestMethod.POST,headers="Accept=application/json")
    public void  addComponent(Component cp)
    {

        myService.addComponent(cp);
    }

    public MyService getMyService() {
        return myService;
    }

    public void setMyService(MyService myService) {
        this.myService = myService;
    }


    /**
     * @return The page of all Patterns after we have updated one of them to test the method
     */
    @RequestMapping(value="/updatepattern/{i}/{value}",method= RequestMethod.PUT,  headers="Accept=application/json")
    public String updatePattern(@PathVariable int i,@PathVariable String value)
    {
        /*List<Pattern> liste = myService.getAllPattern();
        Pattern p = liste.get(0);       
        p.setValue("^/[0-9]Pattern has been updated");
        myService.updatePattern(p);*/
        Pattern p  = myService.getPatternById(i);
        p.setValue(value);
        myService.updatePattern(p);
        return "redirect:/service/home1";
    }   


    /**
     * @return The page of all Patterns after we have deleted one of them to test the method
     */
    @RequestMapping(value="/deletepattern/{id}",method= RequestMethod.DELETE,  headers="Accept=application/json")
    public String DeletePattern(@PathVariable int id)
    {
        /*List<Pattern> liste = myService.getAllPattern();
        Pattern p = liste.get(3);*/
        Pattern p  = myService.getPatternById(id);
        myService.deletePattern(p);
        return "redirect:/service/home1";
    }   

}

***Home1.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!Doctype html>
<html data-ng-app="myTest" lang="en">
    <head>
        <title>Home</title>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">



    </head>
    <body >
        <h1>
            Hello world!  
        </h1>

        <P>  The time on the server is ${serverTime}. </P>
        <hr/>
        <div data-ng-controller="myController" style="margin-left: 100px">
            <div>
                <p>ALL PATTERNS</p>
                <button class="btn btn-default" data-ng-click = "listPattern()">All Patterns</button>               
                <br/><br/>
                <table class="table" data-ng-hide="state" style="width: 600px">             
                    <tr>
                        <th>Id_Pattern</th>
                        <th>Pattern</th>
                    </tr>
                    <tr data-ng-repeat="p in patterns">
                        <td>{{p.id}}</td>
                        <td>{{p.value}}</td>
                    </tr>               
                </table>                
            </div>
            <br/><br/><hr/>
            <div>
                <h3>ADD PATTERN</h3>
                <form class="form-inline">
                    <div class="form-group">
                        <input  type ="text" class="form-control" placeholder="Pattern value" data-ng-model="value"/> 
                        <button class="btn btn-default" data-ng-click = "addPattern()">New Pattern</button> 
                    </div>
                </form>
            </div>
            <br/><br/><hr/>
            <div>
                <h3>UPDATE PATTERN</h3>
                <form class="form-inline">
                    <div class="form-group">
                        <input  type ="text" class="form-control" placeholder="PATTERN_ID" data-ng-model="selectedPattern"/> 
                        <input  type ="text" class="form-control" placeholder="new Pattern value" data-ng-model="newvalue"/> 
                        <button class="btn btn-default" data-ng-click = "updatePattern()">Update</button> 
                    </div>
                </form>
            </div>
            <br/><br/><hr/>
            <div>
                <h3>DELETE PATTERN</h3>
                <form class="form-inline">
                    <div class="form-group">
                        <input  type ="text" class="form-control" placeholder="PATTERN ID" data-ng-model="id_pattern"/> 
                        <button class="btn btn-default" data-ng-click = "deletePattern()">Delete</button> 
                    </div>
                </form>
            </div>

        </div>


        <script>
            var module = angular.module('myTest',[]);
            module.controller('myController',function($scope,$http){

                //function to get Patterns Lists
                $scope.state = true;
                $scope.listPattern = function() {           
                    $http({method: 'GET', url: 'allPatterns'}).
                    success(function(data) {
                        $scope.patterns = data;
                        $scope.state = !$scope.state;
                    });
                };


                /*Function to add pattern
                @param the pattern value
                @return pattern lists
                */
                $scope.addPattern = function(){
                    if($scope.value == "" )
                    {
                        alert("You must Enter all specified fields");
                    }
                    else
                    {
                        $http({method:'POST', url:'addpattern/'+$scope.value}).
                        success(function (data){
                            $scope.patterns = data;
                            $scope.state = false;
                        });
                    }
                };

                /*Function to update pattern
                @param the pattern value
                @return pattern lists
                */
                $scope.updatePattern = function(){
                    if($scope.newvalue == "" || $scope.selectedPattern == "")
                    {
                        alert("You must Enter all specified fields");
                    }
                    else
                    {
                        $http({method:'PUT', url:'updatepattern/'+$scope.selectedPattern+'/'+$scope.newvalue}).
                        success(function (data){
                            $scope.patterns = data;
                            $scope.state = false;
                        });                     
                    }
                    $scope.newvalue="";
                    $scope.selectedPattern="";
                };

                /*Function to update pattern
                @param the pattern value
                @return pattern lists
                */
                $scope.deletePattern = function(){
                    if($scope.id_pattern == "" )
                        {
                            alert("You must Enter all specified fields");
                        }
                    else 
                    {                       
                        $http({method:'DELETE', url:'deletepattern/'+$scope.id_pattern}).
                        success(function (data){
                            $scope.patterns = data;
                            $scope.state = false;
                        });
                    }   
                    $scope.id_pattern="";
                };
                $scope.value="";
                $scope.state = true;
            });
        </script>
    </body>
</html>

web.xml contextConfigLocation /WEB-INF/spring/root-context.xml

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

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

<welcome-file-list>
    <welcome-file>/home1.jsp</welcome-file>
</welcome-file-list>

***dispatcher****

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xmlns:beans="http://www.springframework.org/schema/beans"
  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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
         http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <!-- Enable annotation-based Spring MVC controllers (eg: @Controller annotation) -->
  <mvc:annotation-driven/>
  <context:annotation-config/>

  <!-- Classpath scanning of @Component, @Service, etc annotated class -->
  <context:component-scan base-package="com.demo.projet1.controllers" />
  <context:component-scan base-package="com.demo.projet1.services" />
  <context:component-scan base-package="com.demo.projet1.repositories" />
  <jpa:repositories base-package="com.demo.projet1.repositories"/>

  <!-- Resolve view name into jsp file located on /WEB-INF -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
  </bean>

share
up vote 1 down vote accepted

When using @RestController annotation, all @RequestMapping methods assume @ResponseBody semantics by default. That's why home1 is being returned as String. If you are mixing a JSP view and Responsebody, then i would suggest to go with @Controller annotation.

share
    
i don't want to use ResponseBody, i just use it because RestController didn't work with me, i want to use this annotation instead of annotating all my RequestMapping methods with ResponseBody, do you have any idea?? – K.Mouna Apr 14 '15 at 15:34
    
You cannot mix jsp view and json response with @RestController. – minion Apr 14 '15 at 15:58
    
so what should i do ??? – K.Mouna Apr 14 '15 at 15:59
    
One option would be split the jsp view @RequestMapping into a separate controller @Controller annotation, or annotate your controller with @Controller and use @ResponseBody annotation wherever required.. I don't want to suggest something with narrow view on your application. – minion Apr 14 '15 at 16:03
    
Thank you for your help, i will do like you suggest. – K.Mouna Apr 14 '15 at 16:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.