mardi 4 août 2015

Spring 4 response to form submission dosent go thru view resolver. Gives back return string in response

I inherited a spring 4 web project at work which is configured with Tiles view framework, Spring framework for dispatcher servlet and IOC.

I am trying to build a reset password functionality which has three screens with three forms.

1)reset form. Takes the user's email and controller method sends an email with a temp password.

<form:form class="form-horizontal" action="/NCHP/reset.htm" method="post" id="resetForm">
                                    <fieldset>
                                        <legend>Enter your registered email address</legend>
                                        <div class="form-group">
                                            <div class="col-sm-12">
                                                <input id="resetEmail" name="email" class="form-control" placeholder="Email" required="required" tabindex="1" type="email">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                    <button type="reset" class="btn btn-default" data-dismiss="modal">Back</button>
                                                    <button type="submit" class="btn btn-primary" >Submit</button>
                                                </span>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form:form>

2) Form to enter temp pwd:

<form:form class="form-horizontal" name="verify" method="POST" id='verifyform'>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-user form-control-feedback"></i>
                                            <input type="text" id="inputEmailVerify" name="userNameVerify" placeholder="User Name" class="form-control" autofocus="autofocus">
                                        </div>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="passwordVerify" id="inputPasswordVerify" placeholder="Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="verify-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                <input type="submit" formaction="/NCHP/resetVerify.htm" value="Verify" class="btn btn-primary btn-block">
                                                </span>
                                            </div>
                                        </div>
                                    </form:form>

3) form to enter new password:

<form:form class="form-horizontal" name="resetPass" method="POST" id='resetPassForm' >

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" id="newpass" name="newpass" placeholder="new Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="newpass2" id="newpass2" placeholder="re enter Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="new-login-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                        <input type="submit" formaction="/NCHP/changePass.htm" value="Save Password" onsubmit="modaljay();" class="btn btn-info btn-block">
                                        <div class="modaljay"><!-- Place at bottom of page --></div>
                                        </span>
                                        </div>
                                        </div>
                                    </form:form>

The first two forms i do an ajax submit and get back just the data without a view like below with jquery $.ajax()

$('#resetForm').submit(function(event) {
                                        $("#verifyModal").hide();
                                        $("passModal").hide();
                                        var resetmail = $('#resetEmail').val();
                                        console.log(resetmail);
                                        var json = {
                                            "email" : resetmail
                                        };

                                        $.ajax({
                                                    url : "http://localhost:8080/NCHP/reset.htm",
                                                    data : json,
                                                    dataType : 'text json',
                                                    type : "POST",

                                                    success : function(e) {
                                                        $('#resetModal').modal('hide');
                                                        $("#verifyModal").modal('show');
                                                        console.log(e);
                                                    },
                                                    error : function(e) {
                                                        console.log(e);
                                                        if (e.responseText == "email sent") {
                                                            $('#resetModal').modal('hide');
                                                            $("#verifyModal").modal('show');
                                                        } else if (e.responseText == "email not sent. UNAUTHORIZED") {
                                                            $("#emailResponce").html("there was an error. We could not process your request at this time. Please contact support@nexiscard.com");
                                                        }
                                                    }
                                                });

                                        event.preventDefault();
                                    });

The third form is a regular form submission and no ajax submission. because i want the user to be forwarded to their home page after they login with temp and set new password.

Below are the controller mappings for first two forms.

@Controller
public class UserLoginreset
{
@Autowired
public UserDao userDao;
@Autowired
public BCryptPasswordEncoder encoder;
@Autowired
public SecureServiceClient serviceClient;

@RequestMapping(value = "/reset", method = RequestMethod.POST)

public @ResponseBody String  reset( @RequestBody(required=true) String email, 
                                            HttpServletRequest request) 
{
    String mail="";
    try{
            mail = java.net.URLDecoder.decode(email, "UTF-8").replace("email=", "");
        }
    catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    User user =userDao.findUserByemail(mail);
    request.getSession().setAttribute("user",user);
    String resetPwd= encoder.encode("xxxx");

    if(user!=null && email!=null){
        userDao.resetPass(user.getUser_name(), resetPwd);
        return (String) serviceClient.returnRestTemplate("email", mail);//"home";
    } else {
        return "login";//"index";
    }
}

@RequestMapping(value = "/resetVerify", method = RequestMethod.POST)
public @ResponseBody String  resetVerify( @RequestParam(value="user",required=true) String user,@RequestParam(value="pass",required=true) String pass, 
                                            HttpServletRequest request) 
{
    User user1 =userDao.findUserByName(user);
    if(user1!=null && pass.matches("xxxx")){
        return "success";//"home";
    } else {
        return "unauthorised";//"index";
    }

}

}

and third form.

@RequestMapping(value = "/changePass", method = RequestMethod.POST)
public @ResponseBody String  resetPass( @RequestParam(value="newpass", required=true) String newpass, @RequestParam(value="newpass2", required=true) String newpass2,
                                            HttpServletRequest request, Model model, HttpServletResponse httpServletResponse) 
{
    User user = (User)request.getSession(false).getAttribute("user");
    if(user.getUser_name()!=null && newpass.matches(newpass2)){
        userDao.resetPass(user.getUser_name(), encoder.encode(newpass));
        String news = userDao.getDynamicNewsByUser(user.getUser_name());
        model.addAttribute("user",user);
        model.addAttribute("news", news);
        return "MainLayout_Jay";//"home";

    } else {
        return "login";//"index";
    }

}

And below is my spring config

<bean id="annotationResolver" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.nexis.cardholder" />
<mvc:annotation-driven >
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
    <bean class="com.nexis.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/Pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    <property name="order" value="1" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" >
    <property name="order" value="2" />
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
    <property name="order" value="0" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/views.xml</value>
        </list>
    </property>
</bean>

I have two issues. 1) The last form submission dosent return a view with the data in it. It just returns an empty page with controller method's return string in it.

2) I configured my home page in both tiles.xml and put it in /web-inf/pages folder. so if tiles view resolver could not find it, regular resolver should have. i doubt if its treating this request as a ajax request and skipping the model-view mapping part totally. how do i figure out the root cause.

2.5)if i want to parse ajax requests as Json, should i use @restcontroller and will it automatically send the responce as json? i tried using MappingJackson2HttpMessageConverter but didnt see any difference in debug mode?? did it even get used?

Aucun commentaire:

Enregistrer un commentaire