Road SSM learning --springMVC parameters and return the next day _ ajax response

First, the return parameters of type String

index.jsp in:

<a href="response/testString">testString</a>

responseController中:

@Controller
@RequestMapping("/response")
public class responseController {

    /**
     * 有返回String类型给前台接收
     */
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("testString方法执行了...");
        User uuuuu = new User();
        uuuuu.setAge(16);
        uuuuu.setUsername("姓名");
        model.addAttribute(uuuuu);
        model.addAttribute("字符串");
        model.addAttribute(9547);
        model.addAttribute("串串");
        model.addAttribute(1234);
        return "success";
    }
}

success.jsp:
print out the request domain
Here Insert Picture Description

We usually through model.addAttribute(key,obj);the form, be stored in a key-value pair to request a domain, which we are very easy to operate, as long as the corresponding key field in the request will be taken out to obj.
It also found a model.addAttribute(obj);way, so I think, if you do not specify the key, then the object put into your account, and how to get out of it.

In this code, we have to request the object model stored by a User class object domain, two strings, two integers.
It was found that after starting the server, we can find just a few in this domain request deposit into something:
Here Insert Picture Description
can be found that the default key are lowercase first letter of the object belongs to the class! , Then "string" and 9547 these two go out? This is because they are the same as the default key, so that the front after the deposit to cover the lost.
Thus, we know that, in the front page by the appropriate key = string, key = integer to get into strings and numbers. Of course, this is just an experiment, I do not recommend you use this, normal or honestly with key, value in the form of deposit, to avoid making mistakes

Second, the use of forwarding and redirection

WEB-INF following content is only accessible by the server level to the client and can not be accessed . What is the client level? What is the server level it?

Forward:
server level, the browser's address will not change, because the client sends a request to the server after acceptance, but also to find the requested content to go another request, it is forwarded to its own server process is completed. No trouble client (browser), so the client does not change the address bar above.

Redirection:
is the client level. After the server receives the request, but also found something else to ask for, but did not want to deal with their own server, then tell the client that you own to deal with it, then the client requests that go to the other content. So the client (browser) will change the address bar.

Forwarding and Redirection in two ways:
1, native servlet:
within the comment as forwarding and redirection of the two, to redirect attention here to use request.getContextPath () to get the project path, followed later in response webapp directory. jsp page

@RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testVoid方法执行了...");
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //response.sendRedirect(request.getContextPath()+"/response.jsp");
    }

2, springMVC way:
here Why omit request.getContextPath () it, because this is springmvc framework for us to automatically process, you can write directly to the page webapp directory needed to be accessed.
Note that the syntax of the preceding forward: and redirect: fixed wording.

@RequestMapping("/testDispatcherAndRedirect")
    public String testDispatcherAndRedirect(){
        System.out.println("testVoid方法执行了...");
        //使用转发
        //return "forward:/WEB-INF/pages/success.jsp";
        //使用重定向
        return "redirect:/response.jsp";
    }

We can see springmvc provide us with this method works better than using native API servlet.

Third, the return type ModelAndView

controller:

@RequestMapping("testModelAndView")
    public ModelAndView testModelAndView(){
        System.out.println("testModelAndView方法执行了...");
        ModelAndView mv = new ModelAndView();
        mv.addObject("username","哈哈哈");
        mv.setViewName("success");
        return mv;
    }

success.jsp page code, and operation results
Here Insert Picture Description
instructions ModelAndView, can be divided into two parts, one is the effect of the Model class, a role of View (specified pages), will not go into effect Model, wherein it refers to the prior View we return “success”;invoke view resolver
Here Insert Picture Description
to help us jump is the same, but just write here a success, be successful jump, use the instructions to view resolvers, we will remove the view resolver , write only one mv.setViewName("success");, no doubt It is not acceptable. Therefore, in the absence of view parser, we should specify that mv.setViewName("/WEB-INF/pages/success.jsp");the full path.

Third, corresponding data json

1, the configuration unblock static resources
we use jquery and other static resources, because we in the allocation of DispatcherServlet front controller, each request will be intercepted before, leading to the request for static resources are also intercepted, so we have to configure, tell springmvc, the resources not to intercept.

Here Insert Picture Description

2, the front end of the preparation request transmitting ajax
introduced js file in index.jsp

<script src="js/jquery-3.0.0.min.js"></script>
<script>
        $(function () {
            $("#btn").click(function () {
                $.ajax({
                    url:"response/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    dataType:"json",
                    data:'{"username":"哈哈哈","age":18}',
                    type:"post",
                    success:function (data) {
                        alert(JSON.stringify(data));
                        alert(data.username);
                        alert(data.age);
                    }
                });
            });
        });
</script>


<button id="btn" value="点击">按钮</button>

url: the request address controller
contentType: set and character encoding type
dataType: type of data sent
data: the type of data and corresponding dataType, here json string
type: mode request, here a post way
success: sent successfully after the operation made here with parameter data to receive the data back, and turn into json string, through pop and to eject the string and username and age.
Which alert(JSON.stringify(data));can help us convert Json object to a string. Otherwise with the print data directly, you can only print out the Object object.

controller in the method:

@RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了");
        user.setUsername("嘻嘻嘻");
        return user;
    }

Here by @RequestBodyreceiving returned ajax respective key string and the string to Json, these keys will help us SpringMVC encapsulated into the user object , and before the return type plus User @ResponseBodyUser type of the return Json string is converted into an object .
This operation is required to support a set of jar package, because it is maven project just import-dependent coordinates to

	<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

operation result:
** ** bold style

Published 31 original articles · won praise 0 · Views 1217

Guess you like

Origin blog.csdn.net/SixthMagnitude/article/details/104287471