使用AngularJs的Spring MVC中的@RestController VS @Controller

时间:2015-04-14 14:52:18

标签: angularjs rest spring-mvc annotations

我想用Spring MVC Rest Web服务和angularJs创建一个应用程序。 所以我的问题是当我放入我的控制器@Controller everythings工作(我有我的页面home1.jsp)但是当我使用@RestController我的浏览器显示一个字符串(" home1")。 能帮助你理解我的问题吗,谢谢。 这是我的代码: * 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>

*** ****调度

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

1 个答案:

答案 0 :(得分:2)

使用@RestController注释时,所有@RequestMapping方法默认采用@ResponseBody语义。这就是home1作为String返回的原因。如果您要混合JSP视图和Responsebody,那么我建议您使用@Controller注释。