GVKun编程网logo

Spring MVC应用程序-如何设置会话范围的Bean值(springmvc设置session有效期)

30

在本文中,我们将详细介绍SpringMVC应用程序-如何设置会话范围的Bean值的各个方面,并为您提供关于springmvc设置session有效期的相关解答,同时,我们也将为您带来关于android

在本文中,我们将详细介绍Spring MVC应用程序-如何设置会话范围的Bean值的各个方面,并为您提供关于springmvc设置session有效期的相关解答,同时,我们也将为您带来关于android – 为现有的Spring MVC应用程序设计移动应用程序(Spring Mobile或Phonegap)、asp.net – 如何设置MVC应用程序的默认页面?、asp.net-mvc – 具有已定义范围的.NET ASP.NET MVC应用程序Facebook OAuth、Bean的Spring会话范围如何工作?Web上下文中Bean的默认范围是什么?的有用知识。

本文目录一览:

Spring MVC应用程序-如何设置会话范围的Bean值(springmvc设置session有效期)

Spring MVC应用程序-如何设置会话范围的Bean值(springmvc设置session有效期)

在我的应用程序中,我需要在一个屏幕上收集信息,然后在下一个屏幕上显示它。

我选择将此信息存储在一个范围设置为会话的bean中(它将在初始数据收集屏幕之后的其他几个屏幕中使用)

Manager的配置如下:

 <bean name="/springapp.htm">        <property name="sessionBeanManager" ref="sessionBeanManager" />    </bean>

Bean的配置如下:

<bean id="sessionBean"scope="session">    <aop:scoped-proxy/>   <property name="beanValue" value="defaultValue" /></bean><bean id="sessionBeanManager">    <property name="sessionBean" ref="sessionBean"/></bean>

我在jsp页面上输出

<c:out value="${sessionBean.beanValue}"></c:out>

但是每当我加载页面时,该值为空吗?

在我看来,该Bean正在加载OK,但未填充该值,这使我认为是未填充会话Bean还是未将其创建为会话Bean?

答案1

小编典典

除非首先将Spring bean添加到模型中,否则它们在视图中(在您的情况下为JSP)是不可见的。

您必须将sessionBean添加到控制器中的模型中,以使其可用于视图。

model.addAttribute("sessionBean", sessionBean);

android – 为现有的Spring MVC应用程序设计移动应用程序(Spring Mobile或Phonegap)

android – 为现有的Spring MVC应用程序设计移动应用程序(Spring Mobile或Phonegap)

我使用Spring MVC和MySQL在Openshift上创建了一个Web应用程序.

现在我想为这个应用程序移动.我想将相同的应用程序发布为移动应用程序(主要是Android).首先,这个移动版本也应该使用HttpPost / Webservice安全授权.

我知道Pivotal有一个Spring Mobile项目,它可以为同一个应用程序创建一个移动站点(比如spring form标签和所有应用程序更复杂).

另一方面,Phonegap可以借助HTML5和CSS创建一个跨平台的移动应用程序.

我的问题是:

>将我的精力放在Phonegap或Spring Mobile上是否值得?
>如果我选择Spring Mobile,如何在Android Play商店中发布移动应用程序?

一些利弊或任何参考链接将有所帮助.

解决方法:

介绍

首先,让我给你一个警告.虽然这是一个建设性的问题(比这里提到的平均问题更好),但人们通常喜欢那些花费一些时间自己寻找答案的用户的问题.我稍后会解释这一部分.

差异

Phonegap(Cordova)和Spring Mobile是两个完全不同的框架,它们提供完全不同的用途.你可能已经发现谷歌搜索.

Phonegap(Cordova)是一个用于混合移动应用程序创建的包装框架.您的HTML / CSS / JavaScript代码已封装到本机shell中,您可以使用JavaScript< - >用于访问本机电话功能的本机桥接代码.虽然您可以像使用vanilla JavaScript一样使用它,但它通常与其他移动框架一起使用,如jQuery Mobile,Sencha Touch或Kendo UI.

Spring Mobile是Spring MVC的扩展,旨在简化移动Web应用程序的开发. Spring Mobile是一个框架,它提供了检测向Spring网站发出请求的设备类型的功能,并根据该设备提供备用视图.

功夫

一切都取决于你要做什么.混合移动应用程序通常使用单独的客户端和服务器端代码完成.使用AJAX完成通信.因此我会跳过Spring Mobile并仅使用Spring作为RESTful Web服务框架.我个人更喜欢Play框架,但那只是我.

当然,您仍然需要选择客户端JavaScript框架,或者您可以从头开始创建所有内容.我建议你使用像jQuery Mobile这样的预构建框架.

如果你真的想要使用Spring Mobile

如果你真的想使用Spring Mobile,它仍然可以完成. Phonegap可用于将远程网站包装到移动应用程序中.这种方法有几个缺点.如果您的网站停机并且您将无法创建iOS应用程序,则该应用程序将无用,因为这些类型的应用程序一见钟面就被拒绝了.

最佳行动方案

>单独的客户端和服务器端代码
>选择a client side mobile JavaScript framework.
>使用Spring作为RESTful Web服务,或任何其他RESTful框架,如Play.
>将客户端代码包装到Phonegap(Cordova)
>发布为Android,iPhone应用程序

链接

>如何create jQuery Mobile application with Phonegap | Mac version
> Sencha Touch vs jQuery Mobile
> Secrets of a good jQuery Mobile page architecture
>如果您已经有过jQuery的经验,learn the differences between jQuery and jQuery Mobile

asp.net – 如何设置MVC应用程序的默认页面?

asp.net – 如何设置MVC应用程序的默认页面?

我想让我的基本URL去一个在线商店的特定类别(一个 NopCommerce在线商店,如果这有所作为).该类别的URL为:http://myUrl.com/c/6

在阅读包括Scott Gutherie的帖子about MVC routing在内的几篇帖子后,我以为我可以将以下代码添加到我的Global.ascx.cs文件中:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //register custom routes (plugins,etc)
        var routePublisher = EngineContext.Current.Resolve<IRoutePublisher>();
        routePublisher.RegisterRoutes(routes);

        routes.MapRoute(
                "Default",// Route name
                "{controller}/{action}/{id}",// URL with parameters
                new { controller = "Catalog",action = "Category",id = 6 },new[] { "nop.Web.Controllers" }
        );
    }

但这似乎没有起作用.我该如何完成我想要做的事情?

我对MVC没有什么经验,所以我道歉,如果这没有任何意义.

解决方法

看起来像最有趣的位在nopcommerce源代码中.默认路由注册为
routes.MapLocalizedRoute("HomePage","",new { controller = "Home",action = "Index"},new[] { "nop.Web.Controllers" });

您将基本上希望先注册默认路由,然后注册自定义路由注释.应该最终看起来像这样:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
            "Default",// Route name
            "{controller}/{action}/{id}",// URL with parameters
            new { controller = "Catalog",new[] { "nop.Web.Controllers" }
    );

    routes.MapRoute(
        "CustomHome",// Route name
        "",// URL with parameters
        new { controller = "Catalog",new[] { "nop.Web.Controllers" }
    );

    //register custom routes (plugins,etc)
    var routePublisher = EngineContext.Current.Resolve<IRoutePublisher>();
    routePublisher.RegisterRoutes(routes);


}

第一条路线甚至不需要.我不确定.从未与nopcommerce合作.

asp.net-mvc – 具有已定义范围的.NET ASP.NET MVC应用程序Facebook OAuth

asp.net-mvc – 具有已定义范围的.NET ASP.NET MVC应用程序Facebook OAuth

使用定义范围的Facebook OAuth创建 .NET ASP.NET MVC应用程序的最简单方法是什么?

我尝试了很多例子. OAuthWebSecurity.RegisterClient 不支持添加更多Facebook范围. Facebook application template创建一个画布,我需要非画布应用程序. FacebookScopedClient未满,无法使用此修复程序.

你有什么建议?

我也开放JavaScript / jQuery解决方案.

解决方法

可能我已经太迟了,但是几天前我遇到了这个问题,我发现网上只有一些不好的解决方案.所以我写了自己的解决方案,我现在才发布.

我利用DotNetopenAuth.AspNet.Clients.oauth2client类来完成大部分工作.我只扩展了它以包括范围和额外的用户数据.

public class FacebookExtendedClient : DotNetopenAuth.AspNet.Clients.oauth2client
{   
    protected FacebookClient facebookClient;
    protected string fields;
    protected string scope;
    protected Func<string,object,string> fieldTransformer;
    protected bool emailAsUsername;
    protected IDictionary<string,string> userData;

    private string[] splittedFields;
    private string[] splittedScope;

    protected const string serviceLoginBaseUrl = "https://www.facebook.com/dialog/oauth";
    protected const string serviceMeBaseUrl = "https://graph.facebook.com/me";
    protected const string serviceAccesstokenBaseUrl = "https://graph.facebook.com/oauth/access_token";

    /// <summary>
    /// Create an instrance of the class.
    /// </summary>
    /// <param name="appId">The App ID of the application used to connect to Facebook service.</param>
    /// <param name="appSecret">The App Secret of the application used to connect to Facebook service.</param>
    /// <param name="fields">
    /// String containing comma separated fields to add to the request.
    /// If empty the request will retrieve the default fields based of the specified scope.
    /// </param>
    /// <param name="fieldTransformer">
    /// Function to be applied to the values retrived from facebook.
    /// If null provided the method will try to cast values from object to string explicitly,/// an InvalidCastException will be thrown if the cast will not be possible.
    /// </param>
    /// <param name="scope">
    /// String containing comma separated permissions to add to the request.
    /// If empty the request will have the basic scope.
    /// </param>
    /// <param name="emailAsUsername">Makes the email of the facebook user used as authentication username.</param>
    public FacebookExtendedClient(string appId,string appSecret,string fields = "",Func<string,string> fieldTransformer = null,string scope = "",bool emailAsUsername = false)
        : base("facebook")
    {
        if (string.IsNullOrEmpty(appId))
            throw new ArgumentException("The appId argument can not be null or empty.","appId");
        if (string.IsNullOrEmpty(appSecret))
            throw new ArgumentException("The appSecret argument can not be null or empty.","appSecret");

        fields = fields.Replace(" ","");
        scope = scope.Replace(" ","");
        this.splittedFields = fields.Split(',');
        this.splittedScope = scope.Split(',');

        if (emailAsUsername == true && !this.splittedFields.Contains("email") && !this.splittedScope.Contains("email"))
            throw new ArgumentException("The scope argument must contain the 'email' permission and the 'email' field to allow emailAsUsername to true.","scope");

        this.facebookClient = new FacebookClient();
        this.facebookClient.AppId = appId;
        this.facebookClient.AppSecret = appSecret;
        this.fields = fields;
        this.fieldTransformer = fieldTransformer;
        this.scope = scope;
        this.emailAsUsername = emailAsUsername;
    }

    public FacebookClient FacebookClient
    {
        get
        {
            return this.facebookClient;
        }
    }

    public IDictionary<string,string> UserData
    {
        get
        {
            return this.userData;
        }
    }

    protected override Uri GetServiceLoginUrl(Uri returnUrl)
    {
        Dictionary<string,object> parameters = new Dictionary<string,object>();
        parameters.Add("redirect_uri",returnUrl.AbsoluteUri);

        if (!string.IsNullOrEmpty(this.scope))
            parameters.Add("scope",this.scope);

        return this.facebookClient.GetLoginUrl(parameters);
    }

    protected override IDictionary<string,string> GetUserData(string accesstoken)
    {
        // This method makes the AuthenticationResult's UserName property be the facebook username of the logged user,// but if the facebook username is missing the facebook id will be used.
        // If emailAsUsername is true then AuthenticationResult's UserName property is the email retrieved from facebook
        // and the facebook username can be retrieved by the key "fb_username" in this.userData

        FacebookClient facebookClient = new FacebookClient(accesstoken);

        var getResult = facebookClient.Get<IDictionary<string,object>>("me",new { fields = this.fields });
        Dictionary<string,string> result = new Dictionary<string,string>();

        if (this.fieldTransformer != null)
        {
            foreach (var pair in getResult)
                result.Add(pair.Key,this.fieldTransformer(pair.Key,pair.Value));
        }
        else
        {
            foreach (var pair in getResult)
            {
                string value = pair.Value.ToString();

                if (value == null)
                    throw new InvalidCastException("Cast not possible for the object associate to the key '" + pair.Key + "'.");

                result.Add(pair.Key,value);
            }
        }

        if (this.splittedFields.Contains("username"))
            result["fb_username"] = result["username"];

        if (this.emailAsUsername)
            result["username"] = result["email"];

        this.userData = result;

        return result;
    }

    protected override string QueryAccesstoken(Uri returnUrl,string authorizationCode)
    {
        UriBuilder builder = new UriBuilder(serviceAccesstokenBaseUrl);
        builder.Query = string.Format("client_id={0}&client_secret={1}&redirect_uri={2}&code={3}",this.facebookClient.AppId,this.facebookClient.AppSecret,HttpUtility.UrlEncode(Encoding.ASCII.GetBytes(returnUrl.AbsoluteUri)),authorizationCode);

        using (WebClient client = new WebClient())
        {
            string str = client.DownloadString(builder.Uri);

            if (string.IsNullOrEmpty(str))
                return null;

            return HttpUtility.ParseQueryString(str)["access_token"];
        }
    }
}

你可以使用它在OAuthWebSecurity中注册它(在Application_Start中放置Registerauth方法,就像在InternetApplication模板中一样):

public static class AuthConfig
{
    public static void Registerauth()
    {
        configuration.LoadFromAppSettings();

        OAuthWebSecurity.RegisterClient(new FacebookExtendedClient(
            "##YOUR_APP_ID##","##YOUR_APP_SECRET##","id,first_name,last_name,link,username,gender,email,age_range,picture.height(200)",new Func<string,string>(fieldsTransformer),"email"));
    }

    private static string fieldsTransformer(string key,object value)
    {
        switch (key)
        {
            case "picture":
                var data = (value as IDictionary<string,object>)["data"] as IDictionary<string,object>;
                return data["url"].ToString();
            case "age_range":
                var min = (value as IDictionary<string,object>)["min"];
                return min.ToString();
            default:
                return value.ToString();
        }
    }
}

正如你在上面的例子中看到的那样,方法fieldsTransformer将获得键和值foreach字段被选中,在这种情况下,它将把facebook重新获得的对象转换为图片的url.这是一种方便的方法,如果为Func参数提供null,则将保存values对象的JSON表示.

稍后在登录后检索客户端信息,可以这样做:

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        IDictionary<string,string> userData = (OAuthWebSecurity.GetoAuthClientData("facebook").AuthenticationClient as FacebookExtendedClient).UserData;
        string email = userData["email"];

        // If leave null the fieldTransform of the client you can access to complex properties like this:
        JObject picture = JObject.Parse(userData["picture"]);
        string url = (picture["data"] as JObject)["url"].ToString();

        ViewBag.Email = userData["email"];
        ViewBag.PictureUrl = url;
        return View();
    }
}

希望你喜欢这段代码,即使它有点晚了!

总结

以上是小编为你收集整理的asp.net-mvc – 具有已定义范围的.NET ASP.NET MVC应用程序Facebook OAuth全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Bean的Spring会话范围如何工作?Web上下文中Bean的默认范围是什么?

Bean的Spring会话范围如何工作?Web上下文中Bean的默认范围是什么?

我正在研究Spring MVC,但有以下疑问:

  1. 会话范围的目的到底是什么?

阅读文档,我知道这将bean定义的范围限定为HTTP会话。仅在可感知网络的Spring
ApplicationContext上下文中有效。而且,每个用户会话一次创建一个新实例。

但是什么时候才使用呢?出于什么目的?你能举一个实际的例子吗?

  1. 在Spring MVC中,Web上下文的默认范围是什么?

我知道在Spring中,bean的默认范围是 单例, 但是在Web上下文中,bean的范围如何?

关于Spring MVC应用程序-如何设置会话范围的Bean值springmvc设置session有效期的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于android – 为现有的Spring MVC应用程序设计移动应用程序(Spring Mobile或Phonegap)、asp.net – 如何设置MVC应用程序的默认页面?、asp.net-mvc – 具有已定义范围的.NET ASP.NET MVC应用程序Facebook OAuth、Bean的Spring会话范围如何工作?Web上下文中Bean的默认范围是什么?的相关信息,请在本站寻找。

本文标签: