我们正在构建一个与远程 API 通信的 Web 应用程序。我想为这个远程 API 设计客户端,如下所示:
def RemoteApi
constructor (username, password)
getCurrentUser() //implementation will use username and password
getEmployees() //implementation will use username and password
...
重点是,我想在构造过程中将凭据传递给该客户端,并让所有其他方法使用这些凭据。我的第二个要求是我希望这个 RemoteApi
实例位于 session 中。
我已经找到了如何传递动态构造函数参数 here .
我已经找到了如何创建 session 属性 here .
但我无法找到结合这两种技术的方法。据我所知,您必须使用 session 属性自己的类似于 getter 的方法来实例化 session 属性。这种类似于 getter 的方法无法访问表单的字段,因此我此时无法传递凭据。
这就是我陷入困境的地方:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.util.Map;
@Controller
@SessionAttributes("remoteClient")
public class LoginController {
@Value("${company.name}")
private String companyName;
@Autowired
private RemoteClient remoteClient;
@ModelAttribute("remoteClient")
public RemoteClient addRemoteClientToSession() {
return remoteClient; //how do initialize this with credentials in here?
}
@RequestMapping("/")
public String showLogin(Model model) {
model.addAttribute("credentials", new Credentials());
return "login";
}
@RequestMapping("/login")
public String login(@ModelAttribute("credentials") Credentials credentials, Map<String, Object> model) {
if (remoteClient.auth(companyName, credentials.getUsername(), credentials.getPassword())) {
model.put("fullname", remoteClient.findCurrentUser().getName());
return "projectView";
} else {
return "login";
}
}
}
更新:也许解决方案与 this technique 有关。 。在此之前我不知道 ModelAndView
。
最佳答案
我在问题中链接的文章确实包含必要的技术。我要做的是创建一个具有 newInstance(Credentials)
方法的 @Autowired
RemoteApiFactory
并将其传递到 addObject
中。 newInstance
的实现最终可能会使用 new
关键字。如果有人知道如何避免这个细节,我很想听听。
这是根据我的需要调整的示例:
@Controller
@SessionAttributes("remoteApi")
public class SingleFieldController {
@Autowired
private RemoteApiFactory remoteApiFactory;
@RequestMapping(value="/single-field")
public ModelAndView singleFieldPage() {
return new ModelAndView("single-field-page");
}
@RequestMapping(value="/remember")
public ModelAndView rememberThought(@MethodAttribute("credentials") Credentials credentials) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("remoteApi", remoteApiFactory.newInstance(credentials));
modelAndView.setViewName("single-field-page");
return modelAndView;
}
}
关于java - 在 Spring-MVC 中,如何动态设置 session 属性的构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405958/