After accepting data with #requestbody, I want to return message or realize webpage-jump - ajax

Controller:
#RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
#ResponseBody
public RegInfo receiveData(#RequestBody RegInfo info){
String reg_check = regInfoService.checkRegInfo(info);
......
}
RegInfo:
public class RegInfo {
private String account;
private String passwords;
private String realname;
private String phonenumber;
private String sex;
private String mailname;
.......}
register.jsp:
$("#sub").click(function(){
var m = {
"account": $("#_account").val(),
"passwords": $("#_pass").val(),
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val(),
"sex": $("input:checked").val(),
"mailname": $("#mail_name").val()
};
$.ajax({
type:"POST",
async : false,
url:"/demo/user/receive",
dataType:"json",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(m),
success:function(data){
alert("ok");
alert(data.realname);
},
erroe:function(data){
alert("保存失败 ")
}
})
});
Now I want to check RegInfo in the controller. If the result of check is legal, I want to jump to other webpage like login.jsp and if it is illegal, I want to return some message and show the message in register.jsp. How can I realize it?
complete Controller:
#Controller
#RequestMapping("/user")
public class LoginController {
#Autowired
private UserService userService;
#Autowired
private RegInfoService regInfoService;
#RequestMapping("/login")
public String homePage(){
return "user/login";
}
#RequestMapping("/loginin")
public String toLogin(#ModelAttribute("user")User user){
String u = userService.loginCheck(user);
System.out.println(u);
if(u == "success"){
return "user/success";
}
else{
return "user/login";
}
}
#RequestMapping("/register")
public String toRegister(){
return "user/register";
}
#RequestMapping("/success")
public String toSuccess(){
return "user/success";
}
#RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
#ResponseBody
public RegInfo receiveData(#RequestBody RegInfo info){
String reg_check = regInfoService.checkRegInfo(info);
System.out.println(reg_check);
System.out.println(info);
System.out.println(info.getRealname());
return info;
}
}

I want to jump to other webpage like login.jsp and if it is illegal, I
want to return some message and show the message in register.jsp. How
can I realize it?
Simple, in your AJAX success handler redirect with URL parameters like:
$.ajax({
type:"POST",
async : false,
url:"/demo/user/receive",
dataType:"json",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(m),
success:function(data){
alert("ok");
alert(data.realname);
if (data.realname != undefined || data.realname!= null) {
window.location = '/login?realname=' + data.realname;
}
},
erroe:function(data){
alert("保存失败 ")
}
});
EDITS:
based on your comment the controller method will look like:
#Controller
#RequestMapping("/user")
public class LoginController {
#RequestMapping("/login")
public String homePage(Mode model, #RequestParam(value="realname",required=false)String realName){
if(realName!=null && (!realName.trim().isEmpty())){
model.addAttribute("regSuccessUser",realName);
}
return "user/login";
}
}
and redirect statement will look like:
window.location = '/user/login?realname=' + data.realname;
Note: URL start with contextPath to avoid 404 problems

I test as follows:
<input type="button" value="test" onClick="newpage()">
function newpage(){
window.location="/demo/user/login";}
then it jump to login.jsp successfully.In the ajax,it had run to "window.location" but didn't jump.It looks so strange.
Final solution:
error:
<input type="submit" id="sub" value="save" >
true:
<input type="button" id="sub" value="save" >
Form is submitted twice.

Related

Hibernate how to return Json value?

Hi I have this controller method that returns a list of customers and displays it using a model.
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers")
public String getCustomers(Model view)
{
//get customers from dao
List<Customer> results = customerDAO.getCustomers();
//add the customers to the model
view.addAttribute("customers", results);
return "list-customers";
}
}
However I would like to return the list as a json to get an output like
{
"Customer_Code": T77A,
"Customer_Name": CustomerName1
},
{
"Customer_Code": T77B,
"Customer_Name": CustomerName2
}
I tried just returning the list as follows
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers")
public List<Customer> getCustomers()
{
//get customers from dao
List<Customer> results = customerDAO.getCustomers();
return results;
}
}
but then I get this error as it seems to be expecting a view. How can I return the desired json output?
well you are trying to call getCustomers.jsp. What you want, instead, is not a JSP page but a JSON response. So you should make an AJAX call (by using JQuery or other framework or native JS)
So what I would do is change your Controller class in this way:
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<List<Customer>> getCustomers()
{
List<Customer> payload = customerDAO.getCustomers();
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(payload);
}
}
Then I would make the JSON call (I'm using JQuery in this example):
var baseUrl = YOUR_WEB_APP_CONTEXT/getCustomers;
$.ajax({
type: "GET",
url: baseUrl,
success: function(data) {
//All OK.. you should have the JSON response
},
error: function() {
//Something was wrong; you chould check
}
});

Why Struts1 ajax ActionForm values all null

In Struts1 project I'm trying to send ajax,
the chrome request payload is fine{"account":"abcd","pwd":"1234"}
but in debugMode the actionForm's values all null.
the ajax area:
function loging() {
alert(getFormData());
$.ajax({
url : '${pageContext.request.contextPath}/hello.do?method=jsonHi',
type : 'POST',
data : getFormData(),
contentType : 'application/json',
dataType : 'json',
async:false,
success : function(data) {
alert("success");
},
error : function() {
alert("error!");
}
});
}
function getFormData() {
return JSON.stringify({
'account' : $("#account").val(),
'pwd' : $("#pwd").val()
});
};
the struts-config area:
<struts-config>
<form-beans>
<form-bean name="formClass" type="com.pete.form.AccountForm" />
</form-beans>
<action-mappings>
<action name="formClass" path="/hello" parameter="method" type="com.pete.action.HelloAction" scope="request" validate="false">
<forward name="helloUser" path="/WEB-INF/pages/hello.jsp" />
<forward name="jsonHi" path="/WEB-INF/pages/afterAjax.jsp"/>
</action>
</action-mappings>
the form area:
public class AccountForm extends ActionForm{
private static final long serialVersionUID = -7462505002509046403L;
private String account = null;
private String pwd= null;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
teh Action area:
public class HelloAction extends DispatchAction {
public ActionForward jsonHi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
AccountForm reqForm = (AccountForm) form;
System.out.println(reqForm.getAccount());//console is null
System.out.println(reqForm.getPwd());// console is null
return null;
}
}
I don't know what happen the form's values is null
I found the question is My ajax is not a form submit,If I want get value
I have to use HttpServletRequest getReader()

Spring - Stop redirection on error

I have a page to manage users and I would like to stay on the page if any error occurs when clicking save.
The only cases I found online where to do with validation.
Also my page requires the userId to be posted so I don't think returning the name of the original page in the controller would work. Also I would loose the changes made in the page.
What I am trying to achieve is stay in the same page, showing a message to the user.
Here is my controller:
#RequestMapping(method = RequestMethod.POST)
public String editUser(#RequestParam("userId") String userId, final Map<String, Object> model) {
User user = spiService.getUser(userId);
model.put("user", user);
configureRoles(model, user);
return "edituser";
}
#RequestMapping(path = "/updateUser", method = RequestMethod.POST)
public String updateUser(#RequestParam("userJson") String userRoles, #RequestParam("userId") String userId, final Map<String, Object> model) throws IOException {
User user = spiService.getUser(userId);
try {
addRoles(JsonUtil.getField(userRoles, "addedRoles"), user.getRoles(), userId);
removeRoles(JsonUtil.getField(userRoles, "removedRoles"), user.getRoles(), userId);
} catch (Exception ex) {
// What now?
}
return "users";
}
Instead of redirecting you can use Ajax calls in your controller. For that you have to create one AjaxPojoClass for exampleAjaxResponseBody as your convenience.
For example
$.ajax({
type : "POST",
contentType : "application/json",
url : "/yourUrl",
data : JSON.stringify(data),
dataType : 'json',
success : function(data) {
window.location.replace("/successUrl")
},
error : function(e) {
display(e);
},
});
AjaxController
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/yourUrl")
public AjaxResponseBody getSearchResultViaAjax(#RequestBody SearchCriteria search) {
AjaxResponseBody result = new AjaxResponseBody();
//logic
return result;
}
}
you can use ajax to submit your request.

When using #response and #request for json, I meet with some problems

LoginController.java:
#Controller
#RequestMapping("/user")
public class LoginController {
#RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
#ResponseBody
public RegInfo receiveData(#RequestBody RegInfo info){//
System.out.println("come here");
System.out.println(info.getRealname());
return info;
}
}
register.xml:
$("#sub").click(function(){
var m = {
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val()
};
$.ajax({
type:"POST",
url:"/demo/user/receive",
data:m,
dataType:"json",
contentType:"application/json; charset=utf-8",
async:false,
success:function(data){
alert("nihao");
},
erroe:function(data){
alert("保存失败 ")
}
})
});
RegInfo.java:
public class RegInfo {
private String realname;
private String phonenumber;
//private boolean sex;
public RegInfo(){
}
public void setRealname(String realname){
this.realname= realname;
}
public String getRealname(){
return realname;
}
public void setPhonenumber(String phonenumber){
this.phonenumber = phonenumber;
}
public String getPhonenumber(){
return phonenumber;
}
demo-servlet.xml:
<context:component-scan base-package="com.lhao.core"/>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven/>
<context:annotation-config/>
I have imported jackson-annotations-2.1.4.jar, jackson-core-2.1.4.jar, jackson-databind-2.1.4.jar in the lib but I cannot see the print in the console and it shows "400 bad request" in Chrome. I have tried some ways but it does no effect.
You need to convert your javascript variable to json before sending the request to server. JSON.stringify() does the conversion. Based on the code given above, this should solve the issue. well hopefully.
$("#sub").click(function(){
var m = {
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val()
};
$.ajax({
type:"POST",
url:"/demo/user/receive",
data:JSON.stringify(m),
dataType:"json",
contentType:"application/json; charset=utf-8",
async:false,
success:function(data){
alert("nihao");
},
erroe:function(data){
alert("保存失败 ")
}
})
});

#ResourceMapping that accepts JSON from Ajax request

I'm searching how I can interprete a JSON parameter in my #ResourceMapping in Spring Portlet MVC. When I add #RequestBody, I got the message: #RequestBody is not supported... Really stuck on this one.
I have this:
View side:
<portlet:resourceURL var="getTest" id="ajaxTest" ></portlet:resourceURL>
<p>
<button onClick="executeAjaxTest();">Klik mij!</button>
<button onClick="$('#ajaxResponse').html('');">Klik mij!</button>
</p>
<p>
<h3>Hieronder het antwoord:</h3>
<h4 id="ajaxResponse"></h4>
</p>
<script>
function executeAjaxTest() {
var jsonObj = {
user: "Korneel",
password: "testpassword",
type: {
testParam: "test",
}
}
console.debug(JSON.stringify(jsonObj));
$.ajax({
dataType: "json",
contentType:"application/json",
mimeType: 'application/json',
url:"<%=getTest%>",
data:JSON.stringify(jsonObj),
success : function(data) {
$("#ajaxResponse").html(data['testString']);
}
});
}
</script>
Controller side:
#ResourceMapping(value="ajaxTest")
#ResponseBody
public void ajaxTestMethod(ResourceRequest request, ResourceResponse response) throws IOException, ParseException {
LOGGER.debug("ajax method");
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("testString", "Ik ben succesvol verstuurd geweest!");
response.getWriter().write(json.toString());
}
How can I use the spring magic to auto map this JSON data to my own model?
Note: It's Spring Portlet MVC, not regular Spring MVC..
#ResponseBody annotation is not supported out of the box in Spring MVC portlet framework, but you can implement #ResponseBody handling yourself.
We do it by implementing custom view type and model and view resolver.
Implement custom model and view resolver (ModelAndViewResolver), let's say JsonModelAndViewResolver.
In resolveModelAndView method, check whether controller method has #ResponseBody annotation (or more specific condition to identify JSON output - e.g. annotation + required supported mime type).
If yes, return your custom View implementation - let's say SingleObjectJson view (extending AbstractView).
Pass your to-be-serialized object to the view instance.
The view will serialize the object to JSON format and write it to the response (by using Jackson, Gson or other framework in renderMergedOutputModel method).
Register the new resolver as AnnotationMethodHandlerAdapter.customModelAndViewResolvers.
You need to build your json object like this:
var jsonObj = {
user: "Korneel",
password: "testpassword",
"type.testParam" : "test"
};
$.ajax({
dataType: "json",
contentType:"application/json",
mimeType: 'application/json',
url:"<%=getTest%>",
data:jsonObj,
success : function(data) {
$("#ajaxResponse").html(data['testString']);
}
});
In your Controller you should use the #ModelAttribute annotation:
#ModelAttribute(value = "jsonObj")
public JsonObjCommand obtenerJsonObjCommand() {
JsonObjCommand jsonObjCommand = new JsonObjCommand();
return jsonObjCommand;
}
#ResourceMapping(value = "ajaxTest")
public void ajaxTestMethod(
ResourceRequest request,
ResourceResponse response,
#ModelAttribute(value = "jsonObj") JsonObjCommand jsonObjCommand)
throws IOException, ParseException {
LOGGER.debug("USER: " + jsonObjCommand.getUser());
LOGGER.debug("Password: " + jsonObjCommand.getPassword());
LOGGER.debug("TestParam: " + jsonObjCommand.getType().getTestParam());
LOGGER.debug("ajax method");
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("testString", "Ik ben succesvol verstuurd geweest!");
response.getWriter().write(json.toString());
}
Don't forget your beans:
public class JsonObjCommand {
private String user;
private String password;
private TypeJson type;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public TypeJson getType() {
return type;
}
public void setType(TypeJson type) {
this.type = type;
}
}
public class TypeJson {
private String testParam;
public String getTestParam() {
return testParam;
}
public void setTestParam(String testParam) {
this.testParam = testParam;
}
}
According to the documentation, #RequestBody is only supported in Servlet environments, not Portlet environments (same for #ResponseBody). So it seems you can't use that functionality.

Resources