2016-11-26 8 views
1

jQueryのPOST機能によってコントローラに送信されるログインフォーム(index.jsp)があります。送信ボタンがクリックされると、フォーム入力に入力されたユーザー名ではなく、ビュー全体がエラーメッセージ要素に読み込まれます。コントローラがAJAX要求に全面的に応答します

私は間違っていますか?どんな助けでも大歓迎です。

ログインフォーム

<form class="form-inline" id="loginForm" role="form" style="margin-top: 20px"> 
    <div class="form-group"> 
     <input type="text" name="username" class="form-control" id="username" placeholder="Enter your username" 
      autocomplete="off" autocapitalize="off"> 
    </div> 
    <div class="form-group"> 
     <input type="password" name="password" class="form-control" id="password" placeholder="Enter your password" 
      autocomplete="off" autocapitalize="off"> 
    </div> 
    <div class="form-group"> 
     <button type="submit" name="loginBtn" class="btn btn-default" id="loginBtn">Log in</button> 
    </div> 
     <label class="formErrorMsg" id="loginErrorMsg" for="loginBtn"></label> 
</form> 

login.js

$(document).ready(function(){ 
    // Check that the login credentials entered are valid 
    $("#loginBtn").click(function(){ 
     event.preventDefault(); 
     $.post("/login", {username : $("#username").val()}, function(result){ 
      $("#loginErrorMsg").html(result) 
     }); 
    }); 
}); 

indexController

@Controller 
public class IndexController { 
    // Map requests for "/" to index.jsp 
    @RequestMapping(value = "/") 
    public ModelAndView returnIndexPage() { 
     ModelAndView model = new ModelAndView("index"); 
     return model; 
    } 
    // Map AJAX request, via login form, to login 
    @RequestMapping(value = "/login", method = RequestMethod.POST) 
    @ResponseBody 
    public String checkLoginCredentials(@RequestParam("username") String username){ 
     return username; 
    } 
} 

春-ディスパッチャ-servlet.xml

<mvc:annotation-driven/> 

<mvc:resources mapping="/webjars/**" location="/webjars/"/> 
<mvc:resources mapping="/resources/**" location="/resources/" /> 

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix"> 
     <value>/WEB-INF/views/</value> 
    </property> 

    <property name="suffix"> 
     <value>.jsp</value> 
    </property> 
</bean> 

web.xmlの

<servlet> 
    <servlet-name>spring-dispatcher</servlet-name> 
     <servlet-class> 
     org.springframework.web.servlet.DispatcherServlet 
     </servlet-class> 
</servlet> 

<servlet-mapping> 
    <servlet-name>spring-dispatcher</servlet-name> 
     <url-pattern>/</url-pattern> 
</servlet-mapping> 

答えて

1

あなたはインラインフォームフィールドの検証を処理したい場合は、それぞれの<form:errorsを追加する必要がありますフィールドには、formが検証され、エラーメッセージとともに表示されます。

はまた、フォームからのすべてのエラーを返すために、コントローラのメソッド内@Validまたはカスタムバリデータを使用してデータを検証する必要がある、あなたは簡単なサンプルのhereまたはhereを見ることができます。

関連する問題