Spring MVC Web框架,我无法从我的控制器类调用一个方法

时间:2013-08-24 13:51:58

标签: spring jsp spring-mvc

我有一个基本问题。我是Spring MVC Web框架的初学者。当我单击jsp文件中的按钮时,我想从我的控制器类中调用一个方法。我已经尝试了所有可能的解决方案,但我还没有打电话给它。谢谢你的帮助。这是我的代码

/*Controller*/
        enter code here

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package controller;

    import rest.Userdata;
    import java.util.Map;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import service.UserService;

    /**
     *
     * @author simegra
     */
    @Controller
    public class UserController {

        @Autowired
        private UserService userService;

        @RequestMapping("/newUser")
        public String setupForm(Map<String, Object> map) {
            Userdata user = new Userdata();

            map.put("user", user);
            return "user";
        }

        @RequestMapping(value = "/success.htm", method = RequestMethod.POST)
        public String doActions(@ModelAttribute Userdata user, BindingResult result, @RequestParam String action, Map<String, Object> map) {
            //Userdata userResult=new Userdata();
            System.out.println("I AM CALLING");

             switch(action.toLowerCase()){
             case "signup":
             userService.add(user);
             userResult = user;
             break;
             case "edit":
             userService.edit(user);
             userResult = user;
             break;
             case "delete":
             userService.delete(user.getId());
             userResult = new Userdata();
             break;
             case "search":
             Userdata searchedUser = userService.getUser(user.getId());
             userResult = searchedUser!=null? searchedUser : new Userdata();
             break;
             }
             map.put("user", userResult);

            return "success";

        }
    }

/*My JSP*/

<%-- 
    Document   : newUser
    Created on : 15.Ağu.2013, 10:07:28
    Author     : toshiba
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Sing Up</title>
     <style type="text/css">
    .container {
        width: 500px;
        clear: both;
    }
    .container input {
        width: 50%;
        clear: both;
    }


    div.row {
  clear: both;
  padding-top: 10px;
  }div.row span.label {
  float: left;
  width: 100px;
  text-align: right;
  }div.row span.formw {
  float: right;
  width: 335px;
  text-align: left;
  } 

    </style>

</head>




<script language="javascript" type="text/javascript">


function isValidate(){
  if (document.forms["signup"]["fname"].value=="" || document.forms["signup"]["fname"].value==null ) {       
       document.getElementById("divfname").innerHTML = " <font color= red >* Please Enter Your First Name </font>";

            return false;
  }else{document.getElementById("divfname").innerHTML =""}

  if ( document.forms["signup"]["lname"].value=="" ||document.forms["signup"]["lname"].value==null ) {       
        document.getElementById("divlname").innerHTML = "<font color= red >* Please Enter Your Last Name</font>";
    return false;
  }else{document.getElementById("divlname").innerHTML =""}

  if ( document.forms["signup"]["mail"].value=="" ||document.forms["signup"]["mail"].value==null) {       
        document.getElementById("divemail").innerHTML = "<font color= red >* Please Enter Your Email Address</font>";
    return false;
  }else{document.getElementById("divemail").innerHTML =""}


        if(document.forms["signup"]["m"].checked==false && document.forms["signup"]["f"].checked==false){
        document.getElementById("radioB").innerHTML = "<font color= red >* Choose Your Gender</font>";
    return false;
      } else{document.getElementById("radioB").innerHTML =""}


  var x = document.forms["signup"]["bdate"].value;
    var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;

        if (!x.match(reg)) {
         document.getElementById("divbdate").innerHTML = "<font color= red >* Please Enter a valid Birth Date</font>";
      return false;
    }else { document.getElementById("divbdate").innerHTML = "";
    }    

    var ph =/[0-9]|\./;
    if ( !document.forms["signup"]["phone"].value.match(ph) ||document.forms["signup"]["phone"].value=="" || document.forms["signup"]["phone"].value==null ) {       
        document.getElementById("divphone").innerHTML = "<font color= red >* Please Enter Phone Number(use only 0-9)</font>";
    return false;}else{document.getElementById("divphone").innerHTML = "";}

  var passw=  /^[A-Za-z]\w{7,14}$/;   
     if(!document.forms["signup"]["pass1"].value.match(passw) ||document.forms["signup"]["pass1"].value=="" || document.forms["signup"]["pass1"].value==null)   
{    document.getElementById("divpass1").innerHTML = "<font color= red >* Please Enter Password[7 to 15 characters which contain at least one numeric digit and a special character] </font>"; 
         return false;
    }else{document.getElementById("divpass1").innerHTML = "";}

   // var pw1=document.forms["signup"]["pass1"].value;
    // var pw2=document.forms["signup"]["pass2"].value;

     if(!document.forms["signup"]["pass1"].value!=document.forms["signup"]["pass2"].value) {   
         document.getElementById("divpass2").innerHTML = "<font color= red >* Match is not correct";
         return false;
    }else{document.getElementById("divpass2").innerHTML = "";}

    return true;
}
</script>
<body>

    <center>  <p><b><font size="6">SIGN UP</font></b></p> </center>

    <br>
    <div style="width: 350px; background-color: activeborder ;
        border: 1px dotted #333; padding: 5px;
        margin: 0px auto";>

        <form name="input" action="success.htm"   method="POST" id="signup"   >
              <table>
            <fieldset style ="background-color: aliceblue;">
      <legend>Personal Information:</legend>
        <div class="row">
           <span class="label"> First name:</span><input path="firstname" type="text" name="firstname" id ="fname" >
            <div id="divfname" ></div> 

        </div>
      <div class="row">
           <span class="label">  Last name:</span><input path="lastname"type="text" name="lastname" id="lname">
            <div id="divlname" ></div> 

             </div>
            <div class="row">
            <span class="label"> Email:</span><input path="email" type="text" name="email" id="mail">
            <div id="divemail" ></div>

             </div>

      <div class="row">  
                   <div >
                       <dd> <input type="radio" path="gender" name="sex" value="male" id="m">Male   </dd>            
            </div>
             <div class="row">
                       <dd><input type="radio" path="gender" name="sex" value="female" id="f" >Female </dd>
            <div id="radioB" ></div>                                                 
             </div></div>  

            <div class="row">
                <span class="label">  Date of Birth: </span> <input path="firstname" type="text" name="birthday" id="bdate">
            <div id="divbdate" ></div>                                                 
            </div> 
            <div class="row">
          <span class="label">   Phone     : </span><input path="phone" type="text" name="email"id="phone">
            <div id="divphone" ></div>                                                 
           </div>
            <div class="row">
           <span class="label">  Password:</span> <input type="password" name="pwd" id="pass1">
            <div id="divpass1" ></div>                                                 
             </div>
          <div class="row">
           <span class="label">  Re-enter:</span> <input type="password" name="pwd2" id="pass2">
            <div id="divpass2" ></div>                                                 
             </div>
      <center>
             <input type="submit"  name="action" value="signup" >
      </center>

  </fieldset>
        </table>
        </form>

    </div>
    </div>
</body>
</html>

/*Dispatcher-Servlet.xml*/
<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="homePage.htm">homeController</prop>
                <prop key="newUser.htm">userController</prop>

                 <prop key="success.htm">sucController</prop>

            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="homeController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="homePage" />
    <bean name="userController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="newUser" />
    <bean name="sucController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="success" />





    <bean id="mydataSource"
    class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://tmnt.zapto.org:5432/spr"/>
    <property name="username" value="smg"/>
    <property name="password" value="S1m3gra"/>
    </bean> 

    <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="mydataSource"/>
        <property name="packagesToScan" value="data"/> 
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>

        <property name="hibernateProperties">
     <props>

    <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
    <prop key="hibernate.connection.driver_class">org.postgresql.Driver</prop>
    <prop key="hibernate.connection.url">jdbc:postgresql://tmnt.zapto.org:5432/spr</prop>
    <prop key="hibernate.connection.username">smg</prop>
    <prop key="hibernate.connection.password">S1m3gra</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.current_session_context_class">thread</prop>
    <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
        </props>
        </property>
    </bean>


    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

2 个答案:

答案 0 :(得分:1)

我认为使用"/user/success.htm"作为"input"表单的操作网址,可以配置ControllerClassNameHandlerMapping作为控制器映射处理程序。

因为当您放置"/success.htm"时,它实际上是使用您的ParameterizableViewController之一进行映射,而不是使用UserController的方法进行映射(使用/success.htm作为网址映射) 。假设您的DispatcherServlet已映射为"/"

答案 1 :(得分:0)

我没有在JSP中看到使用spring:url。这是使用Spring MVC编写url的经典方法,因为它会自动将基本URL添加到您的应用程序中。 你没有提到任何映射到你的控制器所以它将被触及root root url'/',如果你想要达到你的方法'doActions()'你必须使用:

<spring:url value="/success.htm" var="success"/>

然后:

<a href="${success}>toSuccess</a>

另外,你应该使用JSPX,而不是JSP页面,这是Spring MVC的推荐方式。