SSM Framework Development Web Project Series (vi) SPRINGMVC Getting Started

Source: Internet
Author: User

Objective

Our initial javase part of the study, is basically a primer, but also familiar with the Java syntax and some common APIs, and then deep into the database operations, Web application development, will gradually come into contact with the JDBC, servlet/jsp knowledge, the period may be exposed to one or two relational database, such as mysql/oracle and so on. Like the previous MyBatis section, the further encapsulation of JDBC is more suitable for the actual project development process, but JDBC, mybatis, or hibernate are for persistent layer database operations, such as querying, updating records, etc. The final object of our development program is the user, and what are the user-operating procedures often used? A variety of browsers, not through our backstage test code, the user can not understand the code, do not need to understand. The user only needs to click, need input, such as click a link, jump to a new page, the page part of the data are retrieved from the database query, or enter a text, click the Submit button, update the database records. What we need to clarify is how the instructions for these pages are passed to the backend server, and then access to the database, and how the database data is returned from the background and back to the front, how to display on the page?

If you have learned servlet/jsp related content, you should have some understanding of the above questions. First of all, look at what is Servlet,servlet is a Java program running on our server, for the middle tier, that is, between the client request and the server, we send the request, control the database, business logic, response, back to the front page data, etc. can be implemented by it. The life cycle of the servlet: 1. Initialize the call to the Init () method, 2. Process client request Call Service () method, 3. End Program Call Destroy method, 4. Last garbage collection. JSP is essentially a servlet, the project starts, and the Web container compiles the JSP code into a Java class that the JVM can recognize as a servlet. JSP focus on the page display, the application of HTML, CSS, JavaScript and other front-end technology is not a problem here, and the servlet is more inclined to the background of business logic, control and forwarding and so on.

SPRINGMVC is a set of web-layer frameworks that are further encapsulated on a servlet basis, so it's easy to get started with Springmvc if you can dig into the content of the servlet, so let's take a brief look at the implementation of the servlet before.

Servlet Chapter

Create a new normal Web project or MAVEN Web project by inheriting HttpServlet and creating our custom servlet, as shown below

 PackageCom.mmm.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classMyservletaextendsHttpServlet {@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {//request forwarding, equivalent to a requestReq.getrequestdispatcher ("/a.jsp"). Forward (req, resp); //response redirection, which is equivalent to two requests, the property value set by the previous request will not be available on the page//resp.sendredirect ("./a.jsp"); //This is often done through persistent layer objects to access the database, to get or update the data//get to the data by setting the properties, and then the front-end JSP page can be obtained by means of the El expression and then render the style display    }        }

Here's/a.jsp, representing the JSP page path, for example under the Web file root directory under WebApp, so we webapp under the simple create a.jsp as follows

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >    This is a.jsp</body> 

Then, under the Web folder, under the Web-inf folder, add the following content in the <web-app></web-app> node of the XML

  <servlet>      <servlet-name>MyServletA</servlet-name>      <servlet-class> com.mmm.servlet.myservleta</servlet-class>  </servlet>  <servlet-mapping>      <servlet-name>MyServletA</servlet-name>      <url-pattern>/a.do</url-pattern>  </servlet-mapping>

The value of <servlet-name> here is consistent in <servlet> and <servlet-mapping>,<servlet-class> That is, the full name of the servlet (including the package name) that we have previously customized,<url-pattern> is used to match the URL address we entered in the Address bar. For example, this can be matched to the servlet through Localhost:8080/servlet-web/a.do, thus running to the relevant method in the servlet, where the request is forwarded to a.jsp, as shown in.

Above for a most basic front-end HTTP request to the background server, after running the servlet, return to the front-end view of the process. But in fact, the front-end request will not be so simple to take back a static data-free page, there will not be only one, for example, if the above a.do corresponds to an operation to add a commodity data, that is, in our custom Myservlet Dopost () method to perform the add operation, So if there is a deletion check operation, according to the way here, we need to define MYSERVLETB, Myservletc, myservletd, Then the Web. XML adds 3 segments corresponding to the servlet node definition, and then continue to expand, we do not only the product of the increase and deletion, as well as employees, sales records and so on to operate, so go on, we have to define and configure how many servlets, some people think of ways, For example, the operation path of the product match is a.do, and then add a parameter to determine, and after the path plus? Action=add or? Action=del and so on, so that the operation of the same class of objects we uniformly match it to the same servlet, Inside the servlet's method, you can determine exactly what action to perform (which business logic to run) based on the specific action action type.

Spirngmvc this idea to the extreme, we have only defined in the Web,xml and only one servlet, the servlet can match all the normal request, and then can be based on the path to the exact resolution of a particular class of a method, The class here is the control layer controller, such as a product related operations, we define a commodity controller class, the class defines a variety of operation methods, the need to access the database, often through the service layer object to call the persistence layer of code to implement database operations. The following is an example of a single pass through SPRINGMVC to achieve intermediate control layer effect of small cases.

SPRINGMVC article

To facilitate the management of the jar package, here we can create a new MAVEN Web project, Pom Dependency can refer to the previous environment building, and here in contrast to the servlet, we only need a Java class is the above mentioned controller, and then a specified path under the JSP file, Finally, a little modification of Web. XML, these three steps can be simply over the SPRINGMVC of the basic operating process. These three steps are detailed in the following sections.

Democontroller.java
 package   Com.mmm.web;  import   Org.springframework.stereotype.Controller;  import   org.springframework.web.bind.annotation.RequestMapping; @Controller @requestmapping ( demo  public  class   Democontroller {@RequestMapping (value  ="/topage ")  public   String    ToPage () { return  "page" ; }}

From the top down, first @Controller annotations belong to one of the Spring Series Component bean annotations, corresponding to the components of the Web presentation layer, similar to the @service representing the business logic layer, @repositoty for the database access layer, generic component @ Component and so on, in the actual project, the class objects between layers and layers are also called to each other, and based on the spring container's IOC and dependency injection, we are exposed to @Autowired,@Autowired and so on. Here we can simply understand that by @Controller annotations, spring will recognize and instantiate the bean, and the creation and management of such objects will be controlled by the spring container.

And then@RequestMapping ("Demo"To see the English word meaning should not be difficult to understand,RequestRequestmapping map, request map, Through the HTTP request from our client such as the browser, the servlet we used earlier would match to the corresponding servlet by configuring the URL to match to the access path, which is similar here. SPRINGMVC will match the corresponding method in the corresponding Contoller according to our access path, and yes, there will be a further exact match to the method. The following @RequestMapping (value= "/topage" Demo/topage, you can match to this democontroller topage Executed in the method.

< Span style= "COLOR: #000000" > < Span style= "COLOR: #000000" > You can see that the return value of a method is a string string type, which is understood to be used to get the View page path. The following is explained in conjunction with the Spring MVC configuration file.
/span>

  Application-mvc.xml

<?XML version= "1.0" encoding= "UTF-8"?>  <Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/s Pring-beans-4.0.xsd Http://www.springframework.org/schema/context HT Tp://www.springframework.org/schema/context/spring-context-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.O Rg/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">                               <!--automatic scanning is turned on -      <Context:component-scanBase-package= "Com.mmm.web" />     <Mvc:annotation-driven/>          <!--Spring MVC View parsing configuration -      <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver">          < Propertyname= "prefix"value= "/web-inf/views/" />          < Propertyname= "suffix"value= ". jsp" />    </Bean>                                                  </Beans>

<context:component-scan base-package=" Com.mmm.web "/> is used for the spring scan to identify bean annotations, such as the @controller you just talked about, and <mvc:annotation-driven/> Used to scan SPRINGMVC related specific annotations, such as here @RequestMapping and so on.

The following view resolution configuration is combined with the View page path just above, prefix and suffix respectively for the prefix and suffix meaning, combined with the previous controller method, that is, the page request forwarding path of the unified prefix, the front controller in the return value of the method is "page", then the combination of prefix, that is,/web-inf/ views/page.jsp, and this path corresponds to where, as shown.

So we are going to create a JSP file here, the Views folder is also.

Finally, add the following to Web. xml

 <servlet>        <Servlet-name>Dispatcher</Servlet-name>        <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>        <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Classpath:/application-mvc.xml</Param-value>        </Init-param>    </servlet>    <servlet-mapping>        <Servlet-name>Dispatcher</Servlet-name>        <Url-pattern>/</Url-pattern>    </servlet-mapping>

We will find that this is also the configured servlet, Org.springframework.web.servlet.DispatcherServlet, which only configures this single, mapping path to match the generic request, and Init-param Setting the initial parameters is our SPRINGMVC configuration file path. In this way, we request that the SPRINGMVC series components accept, parse the path, and assign the appropriate method to the appropriate controller.

At the end of the above step, we publish the project and launch the Tomcat server, enter Http://localhost/spring-mvc/demo/toPage in the browser address bar, see the following page, that is, the success

Summary

Through the above-mentioned example, we can understand the use of SPRINGMVC from servlet to Web framework, and also follow these basic rules in actual development, except for more business logic, view files and so on, such as the request forwarding in the page jump. Then whether the servlet is similar to the response redirect, also, the controller in the method we do not necessarily jump to the page, we can directly pass the JSON data back to the front end, as well as we learned before the MyBatis package persistence layer, So how do we connect with the persistence layer to access the database query or update the data, and what is the business logic, and so on, these are the issues we need to consider, and then prepare to separate the specific examples to unfold the description, welcome to explore together.

SSM Framework Development Web Project Series (vi) SPRINGMVC Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.