GVKun编程网logo

Spring MVC Controller正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL

35

在这篇文章中,我们将为您详细介绍SpringMVCController正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL的内容。此外,我们还会涉及一些关于ajax请求springmvcc

在这篇文章中,我们将为您详细介绍Spring MVC Controller正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL的内容。此外,我们还会涉及一些关于ajax请求spring mvc controller,返回中文字符串显示乱码、asp.net-mvc – ASP.NET MVC,MVCContrib,Structuremap,让它作为controllerfactory工作?、asp.net-mvc – ASP.NET MVC:Mock controller.Url.Action、asp.net-mvc – T4MVC @ Url.Action(MVC.Controller.Action())渲染“?Area =”QueryString中的参数的知识,以帮助您更全面地了解这个主题。

本文目录一览:

Spring MVC Controller正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL

Spring MVC Controller正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL

我正在研究基于Spring MVC的Web应用程序。所以我在spring mvc中创建了一个项目,并且选择了eclipse IDE.Apache
tomcat 8服务器和jre1.8的spring软件包的版本是4.2.5。在我的项目中,我创建了登录名,登录后工作正常,我将页面重定向到另一个名为“
branchinsert.jsp”的jsp,该jsp放置在另一个文件夹中(login.jsp和branchinsert.jsp来自不同的文件夹)。在Branchinsert.jsp中,Spring
MVC Controller正在运行,但未创建指定的响应URL,它是从请求映射字符串创建url,这意味着如果我给出的模式类似于下面所述,

@RequestMapping(value="/branchsubmitinsert.travel", method=RequestMethod.POST)public ModelAndView submitBranchInsert(@ModelAttribute BranchModel branchModel){    ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");    return modelAndView;}

显示网址404错误/ProjectName/modules/branch/branchsubmitinsert.jsp

实际上,我期望的网址是/branch/branchinsert.jsp(通常会发生这种情况),但是在这里创建了/branch/branchsubmitinsert.jsp网址。为什么????

这是我的代码

web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/javaee"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"  version="3.0"><display-name>CalicutTravels</display-name>   <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><listener><listener-class>    org.springframework.web.context.ContextLoaderListener</listener-class>

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:context = "http://www.springframework.org/schema/context"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd       http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc.xsd">      <context:component-scan base-package="com.classes.controller">          <context:exclude-filter type="annotation"                  expression="org.springframework.stereotype.Controller"/>      </context:component-scan>  </beans>

spring-dispatcher-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>    <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:context = "http://www.springframework.org/schema/context"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd       http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc.xsd">  <context:annotation-config />  <context:component-scan base-package="com.classes.controller">  </context:component-scan>  <mvc:annotation-driven/>   <mvc:resources mapping="/resources/**" location="/resources/" />   <bean id="viewResolver">        <property name="prefix">            <value>/modules/</value>        </property>        <property name="suffix">            <value>.jsp</value>        </property>    </bean>    <!-- declare beans -->      <bean id="userDaoImplementation"/>      <bean id="userServiceImplementation"/>   <!-- declare datasource bean "jdbc:postgresql://hostname:port   /dbname","username", "password");-->  <bean id="dataSource">   <property name="driverClassName" value="org.postgresql.Driver" />   <property name="url" value="jdbc:postgresql://localhost:5432   /db_enterpricer_travel" />   <property name="username" value="vishnu" />   <property name="password" value="root" />  </bean>  </beans>

branchinsert.jsp的表单字段

 <form action=''branchsubmitinsert.travel'' id=''brach_submit'' method=''post'' >            <fieldset>                <legend>  INSERT </legend>                    <table>                        <tr>                            <th> Branch Name :</th>                            <td> <input type="text" name=''branchName'' id=''branchName'' /></td>                        </tr>                        <tr>                          <td colspan="2" align="right"><input type="button"value=''INSERT'' onclick=''return validateBranchInsert()''/></td>                        </tr>                    </table>             </fieldset>        </form>

控制器类BranchController.java

 package com.classes.controller.branch; import org.springframework.stereotype.Controller; 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.portlet.ModelAndView; import com.classes.service.branch.BranchModel; /** * @author vishnu * */ @Controller @RequestMapping("/branch") public class BranchController { @RequestMapping(value="/branchinsert.travel", method=RequestMethod.GET) public ModelAndView getBranchInsert(){    ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");    return modelAndView; } @RequestMapping(value="/branchupdate.travel", method=RequestMethod.GET) public ModelAndView getBranchUpdate(){    ModelAndView modelAndView = new ModelAndView("/branch/branchupdate");    return modelAndView; } @RequestMapping(value="/branchshow.travel", method=RequestMethod.GET) public ModelAndView getBranchShow(){    ModelAndView modelAndView = new ModelAndView("/branch/branchshow");    return modelAndView; } @RequestMapping(value="/branchdelete.travel", method=RequestMethod.GET) public ModelAndView getBranchDelete(){    ModelAndView modelAndView = new ModelAndView("/branch/branchdelete");    return modelAndView; }@RequestMapping(value="/branchsubmitinsert.travel",method=RequestMethod.POST)public ModelAndView submitBranchInsert(@ModelAttribute BranchModel branchModel){    ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");    modelAndView.addObject("branch",branchModel);    return modelAndView;}}

答案1

小编典典

我将方法SubmitBranchInsert的返回类型更改为String,如下所示

 @RequestMapping(value="/branchsubmitinsert.travel", method=RequestMethod.POST)public String submitBranchInsert(ModelMap model,@ModelAttribute BranchModel branchModel){    //ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");    //modelAndView.addObject("branch",branchModel);    //return modelAndView;    model.addAttribute("branch", branchModel);    return "/branch/branchinsert";}

现在可以了,但是为什么我不能在这里使用ModelAndView代替String中的Model,这可能是我对Spring
MVC专家们的愚蠢的声音。我只想知道什么时候应该在字符串中使用ModelAndView而不是Model?我不想单独问这个问题,这就是为什么我要用我的答案本身来问这个问题。有人可以帮助我吗?

ajax请求spring mvc controller,返回中文字符串显示乱码

ajax请求spring mvc controller,返回中文字符串显示乱码

controller:

@RequestMapping("/checkName")

@ResponseBody

public String checkName(String puName){

.............

return "该用户名不存在";

}


ajax:

$.ajax({

type:'post',

url:'checkName',

data:{"puName":$("#puName").val()},

dataType:'text',---------------------------->必须改为json才不显示乱码

success:function(result){

alert(result);

}

}

)'

asp.net-mvc – ASP.NET MVC,MVCContrib,Structuremap,让它作为controllerfactory工作?

asp.net-mvc – ASP.NET MVC,MVCContrib,Structuremap,让它作为controllerfactory工作?

我正在尝试使用structuremap来正确创建我的控制器,我正在使用DI将一个INewsService注入一个NewsController,这是我唯一的构造函数.

public class NewsController : Controller
{
    private readonly INewsService newsService;

    public NewsController(INewsService newsService)
    {
        this.newsService = newsService;
    }

    public ActionResult List()
    {
        var newsArticles = newsService.GetNews();
        return View(newsArticles);
    }
}

我正在使用此代码启动应用程序

public class Application : HttpApplication
{
    protected void Application_Start()
    {
        RegisterIoC();
        RegisterViewEngine(ViewEngines.Engines);
        RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterIoC()
    {
        ObjectFactory.Initialize(config => {
            config.UseDefaultStructureMapConfigFile = false;
            config.AddRegistry<PersistenceRegistry>();
            config.AddRegistry<DomainRegistry>();
            config.AddRegistry<ControllerRegistry>();
        });
        DependencyResolver.InitializeWith(new StructureMapDependencyResolver());
        ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));            
    }
}

但Structuremap似乎不想注入INewsService,我得到了错误
没有为此对象定义的无参数构造函数.

我错过了什么?

解决方法

我使用StructureMap提供的“默认约定”机制来避免需要单独配置每个接口.下面是我用来完成这项工作的代码:

我的Global.asax在Application_Start中有这一行(它使用MvcContrib的StructureMap工厂):

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ObjectFactory.Initialize(x =>
    {
        x.AddRegistry(new RepositoryRegistry());
    });
    ControllerBuilder.Current.SetControllerFactory(typeof(StructureMapControllerFactory));
}

RepositoryRegistry类看起来像这样:

public class RepositoryRegistry : Registry
{

    public RepositoryRegistry()
    {
        Scan(x =>
        {
            x.Assembly("MyAssemblyName");
            x.With<DefaultConventionScanner>();
        });

    }

}

DefaultConventionScanner查找遵循ISomethingOrOther和SomethingOrOther的命名约定的接口/类对,并自动将后者作为前一个接口的具体类型.

如果您不想使用该默认约定机制,那么您将在Registry类中添加代码,以使用以下语法将每个接口明确映射到具体类型:

ForRequestedType<ISomethingOrOther>().TheDefaultIsConcreteType<SomethingOrOther>();

asp.net-mvc – ASP.NET MVC:Mock controller.Url.Action

asp.net-mvc – ASP.NET MVC:Mock controller.Url.Action

我的ASP.NET MVC应用程序中的菜单的URL为控制器/操作生成。所以他们打电话
controller.Url.Action(action,controller)

现在,我如何使这项工作在单元测试?
我使用MVCContrib成功

var controller = new TestControllerBuilder().CreateController<OrdersController>();

但是无论我尝试使用它,我得到controller.Url.Action(操作,控制器)失败与NullReferenceException因为Url == null。

更新:它不是关于如何拦截HttpContext。我以几种方式做到这一点,使用MVCContrib,Scott Hanselman的伪造例子,还有一个来自http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx的例子。这并不能帮助我,因为我需要知道什么是值得冒犯的… ApplicationPath?如何设置?是否需要匹配被叫控制器/动作?也就是说,Url.Action如何工作,如何满足?

此外,我知道我可以做IUrlActionAbstraction并与它一起去…但我不知道我想做这个。毕竟,我有MVCContrib / Mock全功能,为什么我需要另一个抽象。

解决方法

以下是如何使用MvcContrib的TestControllerBuilder来模拟UrlHelper:
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
HomeController controller = CreateController<HomeController>();

controller.HttpContext.Response
    .Stub(x => x.ApplyAppPathModifier("/Home/About"))
    .Return("/Home/About");

controller.Url = new UrlHelper(
    new RequestContext(
        controller.HttpContext,new RouteData()
    ),routes
);
var url = controller.Url.Action("About","Home");
Assert.IsFalse(string.IsNullOrEmpty(url));

asp.net-mvc – T4MVC @ Url.Action(MVC.Controller.Action())渲染“?Area =”QueryString中的参数

asp.net-mvc – T4MVC @ Url.Action(MVC.Controller.Action())渲染“?Area =”QueryString中的参数

我将一个菜单从部分动作直接转换到布局,使用:
@Html.Action(MVC.Menu.Index())

此操作决定要渲染哪个菜单。例如,一个公共菜单部分。在这些部分中,我也使用T4MVC渲染链接:

<ul id="navHolder">
<li>
    <ul>
        <li><b>@Html.ActionLink("Welcome",MVC.Home.Index())</b>
           ...

由于某些原因,T4MVC提供的Urls最后包括“?Area =”:

<ul id="navHolder">
    <li>
        <ul>
            <li><b><a href="/home/index?Area=">Welcome</a></b>
               ...

我的项目中没有任何区域,我已将“IncludeAreasToken”设置设置为false。奇怪的是,只有当我使用“@ Html.Action”渲染部分时,才会发生这种情况 – 如果我将其作为“@ Html.Partial”拉入,则该参数不会被渲染,并且链接是干净和正确的。 (我不想把它作为一个部分,所以请不要提出这个建议;)

之前有任何人会遇到这个吗?

解决方法

这里有一些奇怪的事情,我想知道是否有一些MVC错误在根。即使没有使用T4MVC,如果你写:
@Html.ActionLink("Welcome","Index","Home",new { Area = "" },null)

在常规视图中,这不会产生虚假的区域=,而在一个Html.Action调用它。我需要问团队的人。

现在,您可以通过在t4mvc.tt中删除此行(围绕第310行)解决方法:

<# if (MvcVersion >= 2) { #>result.RouteValueDictionary.Add("Area",area ?? "");<# } #>

我们今天的关于Spring MVC Controller正在工作但未创建指定的响应URL,它是从请求映射字符串创建URL的分享已经告一段落,感谢您的关注,如果您想了解更多关于ajax请求spring mvc controller,返回中文字符串显示乱码、asp.net-mvc – ASP.NET MVC,MVCContrib,Structuremap,让它作为controllerfactory工作?、asp.net-mvc – ASP.NET MVC:Mock controller.Url.Action、asp.net-mvc – T4MVC @ Url.Action(MVC.Controller.Action())渲染“?Area =”QueryString中的参数的相关信息,请在本站查询。

本文标签: