@restcontroller和@responsebody不在Spring MVC + Thymeleaf工作

时间:2016-01-28 20:43:31

标签: json spring spring-mvc thymeleaf spring-restcontroller

在我的Spring MVC 4.1.5应用程序配置为使用Thymeleaf 2.1.4(在使用JSP之前它工作正常),我无法返回JSON响应。

它总是返回一个完整的HTML页面天气,我的请求映射在@RestController中,或者如果用@responsebody注释

这是控制器 在@controller类中,我有以下映射

@RequestMapping(value = { "/", "/land", "/login" }, method = RequestMethod.GET)
public String getLogin(Model model, HttpSession session) {
    session.setAttribute("login", "none");
    System.out.println(programId);
    model.addAttribute("signUpForm", new SignUpForm());
    return "login";
}

并且在@RestController类中,下面是相同URL的post方法

    @RequestMapping(value = {"/login" }, method = RequestMethod.POST )
public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm,  HttpServletRequest request,
        HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ) {

    User user = userDao.findUserByName(signUpForm.getUserName());

    if (user != null && encoder.matches(signUpForm.getPassword(), user.getPassword())&& user.getProgram_id()==3) {/* && user.getProgram_id()==3*/
        session.setMaxInactiveInterval(1200);
        System.out.println(session.getMaxInactiveInterval()+":"+session.getLastAccessedTime()+":"+session.getCreationTime()+":"+session.getServletContext().getContextPath());
        session.setAttribute("login", "success");
        mo.put("redirect", "/home");
        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        session.setAttribute("urip", ipAddress);

        return mo;
    } else {
        mo.put("error", "Login failed. Please check your credentials");

        return mo;
    }
}

以下是我的xml配置

<context:component-scan base-package="com.company.cardholder" />
<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion">
                        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
    <bean class="com.company.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
  <property name="prefix" value="/WEB-INF/thymeleaf/" />
  <property name="suffix" value=".html" />
  <property name="templateMode" value="HTML5" />
  <!-- Template cache is set to false (default is true). -->
  <property name="cacheable" value="false" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
  <property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
 <property name="templateEngine" ref="templateEngine" />
 </bean>

这是我的JSON电话

$.ajax({
                type: 'POST',
                url: $form.attr('action'),
                data: JSON.stringify({
                    userName: $form.find('#userName').val(),
                    password: $form.find('#password').val(),
                }),
                contentType: "application/json",
                /*dataType: 'json',*/
                complete: function(data) {
                console.log(data);
                if (data.redirect) {
                    // data.redirect contains the string URL to redirect to
                    window.location.href = data.redirect;
                }else if(data.error){
                    $messageError.text(data.error);
                    $messageError.removeClass('hidden');
                    $messageSuccess.addClass('hidden');
                }
    }
    });

1 个答案:

答案 0 :(得分:0)

确定。这是我想要使它工作,但我仍然不确定原因。

    var upSwipes = 0

  override func viewDidLoad() {
    super.viewDidLoad()

    self.openingText.alpha = 0.0
    self.swipeUp.alpha = 0.0

    let swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    let swipeUp = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeUp.direction = UISwipeGestureRecognizerDirection.Up
    self.view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeDown.direction = UISwipeGestureRecognizerDirection.Down
    self.view.addGestureRecognizer(swipeDown)

  }


 func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {


      switch swipeGesture.direction {
      case UISwipeGestureRecognizerDirection.Down:
        print("minus 1")
        if upSwipes != 0 { upSwipes = upSwipes - 1}
      case UISwipeGestureRecognizerDirection.Up:
        print("plus 1")
              upSwipes = upSwipes + 1
      default: print("other direction")
      }

        switch upSwipes {
        case 0:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0
          self.openingText.text = "Swipe up, not down you silly "
          self.openingText.alpha = 1.0
          self.swipeUp.alpha = 1.0
        case 1:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0
          self.openingText.text = "Case specific text. Please swipe up again."
          self.openingText.alpha = 1.0
          self.swipeUp.alpha = 1.0
          // Sequence to tell specifically why you need GPS permission and that in the next frame you will ask for it          
        case 2:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0
        //          initialAuthorization() // Your func to ask for GPS permission
          // Sequence to ask eg. GPS use permission
        case 3:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0
          self.openingText.text = "Case specific text. Please swipe up again."
          self.openingText.alpha = 1.0
          self.swipeUp.alpha = 1.0
          // Sequence to eg. ask name
        case 4:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0
          self.openingText.text = "Case specific text. Please swipe up again."
          self.openingText.alpha = 1.0
          self.swipeUp.alpha = 1.0
          // Sequence to eg. send verification email
        default:
          self.openingText.alpha = 0.0
          self.swipeUp.alpha = 0.0

            let vc = storyboard?.instantiateViewControllerWithIdentifier("initilizing-done") as! InitializingDoneViewController
            presentViewController(vc, animated: true, completion: nil)
          // Then finally you might choose to go to other view controller. You need file (Cocoa class) with the same name InitializingDoneViewController.swift and VC whose specification will then be used for this VC that is modally shown herein.
        }
    }

在上面的方法签名中,我正在“注入”一个hashmap。并且spring框架默认或一些​​未知的配置决定注入“绑定结果感知Hashmap”。我不确定它会有什么不同。但要修复它,我必须做一个

public @ResponseBody HashMap<String, Object> login2(@RequestBody SignUpForm signUpForm,  HttpServletRequest request,
    HttpServletResponse httpServletResponse, HashMap<String, Object> mo, HttpSession session ){
////
}

在方法体内部并删除注入的hashmap。 如果有人能够理解这种行为,请解释一下。在我对弹簧框架的认识中,我觉得我错过了一些基本的东西。