SSM framework development web project series (7) SpringMVC request receiving, ssmspringmvc
Preface
In the previous Spring MVC introductory article, we have a preliminary understanding of the basic setup process of Spring MVC development. This article will list common knowledge points in the Controller section of the actual development process, the configuration is used as an example. Before that, it is necessary to review the positioning or function of Spring MVC in our WEB development? Spring MVC is mainly used in the project to receive client requests, parse paths, and distribute requests to the corresponding Controller, that is, to execute corresponding methods. In the methods, our common operations include, you can call the business logic layer (which will be introduced later) method to access the database, obtain data, or update data. If you want to obtain data, it is generally returned to the front-end. There are two common methods: 1. in traditional Jsp development, we can encapsulate the data into the Model attribute, and then obtain the data through el expressions on the page. 2. with the rise of Ajax technology and RESTful style, data can also be transferred when the former backend is separated (the RESTful basic learning stage is not important, but Ajax must be mastered ). In the Development Mode Based on Spring MVC, It is very convenient to obtain, match, and redirect parameters. Let's take a look at it.
0. page file path and page Jump Problems
If the learning phase is used to placing Jsp files directly under the web file root directory webapp, it is recommended that you start to change it now and put it under the WEB-INF, so that we want to access a page, instead of directly accessing through the path, the request in Spring MVC matches the method in the corresponding controller, and then jumps to the corresponding page. The difference is that files under the WEB-INF for the server, and the client such as the browser is not directly accessible, this can reduce the risk of direct access, in addition, even if aside from security concealment, if you directly access the Jsp page that needs to fill in the data transmitted by Model, various strange issues may occur, such as blank space, no data, and style disorder. By default, page Jump spring MVC is request forwarding. This article mainly deals with the request section and uses default request forwarding.
1. annotations in this article
@ Controller
This annotation is used by Spring to identify and instantiate the Controller bean to the context, that is, the Spring class with this annotation can recognize that it is to be used as a controller.
@ RequestMapping
This annotation can be used both in the class and in the method. It is usually used in actual development. It is used to match the url path and receive requests. Only matching requests can enter the Controller to execute related methods.
@ RequestParam
In the Controller method, it is used to bind the injected parameters to the foreground request parameters.
@ PathVariable
Parameter used to bind a placeholder in a url path
2. automatically match parameters sent from the client
Login should be a web program operation that everyone is not familiar with. Here, the User name and password are used as examples to correspond to the username and password attributes in the Entity class User respectively. Then, our page form section is as follows:
Login. jsp
<Form action = "$ {pageContext. request. contextPath}/user/login "method =" post "> user name <input type =" text "name =" username "/> <br/> password <input type =" password" name = "password"/> <br/> <button type = "submit"> log on </button> </form>
Controller code
Package com. mmm. web; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; @ Controller @ RequestMapping ("user") public class DemoController {@ RequestMapping (value = "/toLogin") public String toLogin () {return "login ";} @ RequestMapping (value = "/login") public String login (String username, String password) {System. out. println ("username ---" + username); System. out. println ("password ---" + password); return "index ";}}
With the previous file path problem, we first define a toLogin method to access the login on the login page. jsp, and then click submit in the form on the page, the login method will be requested here, focus: the name attribute value of the input box <input> in the form, corresponding to the parameter name of the method in the Controller, that is, the two parameter names, username and password, of the login method, Spring MVC can automatically match these two values so that we can easily obtain the parameter.
Start Tomcat and enter http: // localhost/spring-mvc/user/toLogin in the address bar to access the logon page, as shown below:
Enter the username and password, and click log on. The following information is displayed on the eclipse console:
And jump to the index. jsp page, where the parameters passed by the foreground are obtained successfully. This method is very convenient, but not unique. So the following describes other methods respectively.
* ** Based on the previously learned Servlet series request object HttpServletRequest, it has a getParameter (String parameterName) method, which is the frontend parameter name, the value corresponds to the name attribute value of <input> in the input box.
* ** The Spring MVC mechanism can be applied to the Assembly attributes of the object class and the parameters can also be matched. the User name and password here are usually the corresponding object class. Here, the User is used as an example, class has two string attributes: username and password. In this way, we can also match the two parameters in the foreground through the User object.
Next we will summarize the above content and modify the login method as follows:
@ RequestMapping (value = "/login") public String login (String username, String password, HttpServletRequest req, User user) {System. out. println ("retrieve directly matching parameter names: username ---" + username); System. out. println ("directly obtain the parameter name match: password ---" + password); System. out. println ("HttpServletRequest get: username ---" + req. getParameter ("username"); System. out. println ("HttpServletRequest get: Password ---" + req. getParameter ("password"); System. out. println ("User acquisition: user Name ---" + User. getUsername (); System. out. println ("User acquisition: Password ---" + user. getPassword (); return "index ";}
Access the logon page again, enter the content, and click log on. The following information is displayed in the eclipse console:
It indicates that the above methods can be used to obtain the parameter values transmitted at the front end.
PS: the first method (also common) above. If the name value in the front-end form is indeed different from the parameter name in my method, is there any other way to solve this problem? Currently, the annotations of Spring MVC are gradually improved. Spring MVC provides us with such an annotation, @ RequestParam, which is used to specify the foreground parameter name, here, if we change the value of the name attribute in the password input box on the login page to pwd, as shown below:
Password <input type = "password" name = "pwd"/> <br/>
According to the preceding parameter name match, the login method of Controller is password, and the foreground is pwd. Therefore, the login method does not match and data cannot be obtained. However, by introducing the annotation mentioned above, you can change the String password to @ RequestParam ("pwd") String password as a parameter in the method to obtain data successfully.
The preceding example introduces several methods to obtain Request Parameters. I learned about Servlet and should be familiar with the doPost and doGet methods. Here, the form is usually submitted using the post request method.
When using post to submit data, the data will be submitted to the server in the form of data blocks, and no data will appear in the URL address bar. Therefore, the form data submitted in this way is relatively safe. Therefore, we recommend that you use the post method when submitting a form that contains data similar to a password.
When you use get to submit a file, the address bar will add a similar content after your current project path? In the format of pram1 = value1 & param2 = value2, the form data is appended to the URL and submitted to the server for processing. This method is more efficient, so when there is no private data, this type is recommended for requests.
In addition to the method mentioned above, there is also a way to get the path to pass parameters. Here we also introduce it, which is more practical. Through the @ PathVariable annotation, use the url path to dynamically PASS Parameters and obtain parameter values. The Code is as follows:
@ RequestMapping (value = "/show/{id}") public String show (@ PathVariable (value = "id") String str) {System. out. println ("url acquisition: id parameter value ---" + str); return "index ";}
Then, enter localhost/spring-mvc/user/show/abcdefg in the address bar, the abcdefg at the end of the path corresponds to the id in the above Controller code @ RequestMapping (value = "/show/{id, we use the braces {id} and parameter name to dynamically receive it. No matter what your value is, the id variable is used here, so the id in @ PathVariable (value = "id") corresponds to it and is then bound to String str. This str matches the value of this parameter, we can get the data. Enter the address and press enter to view the console. The output is as follows:
3. Improved the login module
The get and post methods mentioned above mainly refer to the foreground request method. Can we choose to accept the specified request in the background? Of course. @ RequestMapping there is a method in the attribute. It means a method. Here it is used to specify the request method to be received, as shown below:
For convenience, Spring MVC also provides RequestMethod enumeration for us, as shown below:
* @author Juergen Hoeller * @since 2.5 * @see RequestMapping * @see org.springframework.web.servlet.DispatcherServlet#setDispatchOptionsRequest * @see org.springframework.web.servlet.DispatcherServlet#setDispatchTraceRequest */public enum RequestMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE}
Various request methods are specified. We can directly specify them through RequestMetho. GET.
For example, in the login section above, we first need to go to the login page, and the request does not have parameters to pass, so we directly request through the get method, and then enter the information on the login page and click Login, when submitting a form for logon, we usually use post. The value of @ RequestMapping (value = "") above is toLogin, login, and two different values to distinguish the two requests, but it can be written as the same. Here we will slightly modify it as follows:
@ RequestMapping (value = "/login", method = RequestMethod. GET) public String toLogin () {return "login" ;}@ RequestMapping (value = "/login", method = RequestMethod. POST) public String login (String username, String password) {System. out. println ("retrieve directly matching parameter names: username ---" + username); System. out. println ("directly obtain the parameter name match: password ---" + password); return "index ";}
In this way, we can achieve the previous results.
4. What should we do after obtaining request parameters?
When no maven application is available, we often use the following method to create a web project.
The first thing we need to clarify is that our web projects are all dynamic (dynamic), which is at the top of the dynamic layer. It is a variety of dynamic operations on the client, which go deep into the bottom layer and are mostly reflected in the database, so what is the relationship between the two, or how is it associated? The request parameters mentioned above are often a man-in-the-middle. For example, if the client submits two parameters: user name and password through the form, we need to query the database to see if there are user records that both account and password match at the same time, if yes, the input is correct. If no, the input information is incorrect. The uncertain logon success or failure result obtained by the client is based on its input and data in the database, countless associations like this have constructed the business logic structure of our web project.
So we need to clarify what is the business logic later. During the login process, we verify that the user name and password are correct and call the user's persistent layer object to query the database user table records. However, we also need to record the login information, insert a logon information in the log table. However, the persistence layer provides methods for querying user tables and Inserting log information. However, the two methods are not called together, therefore, we need to add a business logic layer between the control layer and the persistent layer to integrate these persistent operations and encapsulate the business logic methods for the control layer to call.
Of course, the example log here may be a bit inappropriate, because it is very convenient to implement general components based on Spring AOP, such as transaction management and log information record, so that we can focus on implementing the business logic in the project, but in general, here we can simply understand that the business logic Service layer acts between the persistent layer (dao) and the control layer (controller, it is often used to assemble more complex operation processes than the persistent layer, and is not limited to database operations, and then called by the control layer. The control layer focuses on receiving requests, distribute to the corresponding business logic method for processing, and then respond.
Summary
The above describes the process and method of processing parameters related to Spring MVC universal requests. Of course, file upload is also a special request and is often used. In actual development, we often work hard on how to implement complex business logic. On the contrary, the control layer should not be used to process these businesses. Therefore, the following section will specifically clarify the business logic layer, inject the persistent objects encapsulated by MyBatis we learned earlier, and then inject the business logic layer objects into the control layer, integrate Spring MVC with MyBatis.