SPRINGMVC Introduction
Both spring Web MVC and STRUTS2 are the framework of the presentation layer, which is part of the spring framework.
Java EE three layer architecture
- Presentation Layer Web layer (using JSP/SERVLET/STRUTS2/SPRINGMVC Technology): Display of data.
- Application Layer service layer (using BEAN/EJB technology): Handle business logic, general if judgment, loop, etc.
- The data Layer DAO layer (accurate data interface, using Jdbc/hibernate/mybatis technology): To save data and access data.
SPRINGMVC Architecture
Request Process
- 1, the user sends the request to the front controller Dispatcherservlet
- 2. Dispatcherservlet received a request to call the Handlermapping processor mapper.
- 3. The processor mapper locates the specific processor according to the request URL, and returns the Processor object and the processor interceptor (if any) to Dispatcherservlet.
- 4. Dispatcherservlet calls the processor via the Handleradapter processor adapter
- 5, the execution processor (Controller, also known as the back-end controller).
- 6, controller execution completed return Modelandview
- 7, Handleradapter the controller execution results Modelandview returned to Dispatcherservlet
- 8. Dispatcherservlet Pass Modelandview to Viewreslover view parser
- 9, Viewreslover after parsing return to the specific view
- 10. Dispatcherservlet view is rendered (the model data is populated into the view).
- 11. Dispatcherservlet Response User
Component Description
Dispatcherservlet: Front Controller
The user request arrives at the front controller, it is equivalent to the MVC pattern C,dispatcherservlet is the entire Process Control center, by it calls other components processing user's request, the Dispatcherservlet existence reduced the coupling between the components.
Handlermapping: Processor Mapper
Handlermapping is responsible for the user request URL to find handler is the processor, SPRINGMVC provides different mapper implementation of different mapping methods, such as: Configuration file mode, implementation interface, annotation method.
Handler: Processor
The Handler is the back-end controller of the Dispatcherservlet front-end controller, which is processed under the control of Dispatcherservlet Handler to specific user requests.
because Handler involves specific user business requests, so the general situation requires programmers to develop handler based on business requirements.
Handladapter: Processor Adapter
through The Handleradapter executes on the processor, which is an application of the adapter pattern that can be performed on more types of processors through the extension adapter.
are many different adapters that can eventually be connected using a USB interface
Viewresolver: View Resolver
View Resolver is responsible for generating a view view of the processing results, and the view Resolver first resolves to the physical view name that is the specific page address based on the logical view name, and then the view object is generated. The final rendering of the view renders the processing results to the user through the page.
View: Views
The SPRINGMVC framework provides support for many view view types, including: Jstlview, Freemarkerview, Pdfview, and so on. The most common view we use is JSP.
In general, the model data needs to be presented to the user through page labels or page template technology, and the programmer needs to develop specific pages based on the business requirements.
I. SPRINGMVC construction
1. Guide Package
2, Configuration Springmvc
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "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" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/HTTP Www.springframework.org/schema/mvc/spring-mvc-4.0.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx.xsd "> <!--***************** Configuring various annotations ******************--> < !--Configuring note drivers (because the default is obsolete), for scanning annotations such as requestmapping-<mvc:annotatiOn-driven/> <!--scan @controler, @Service ...-<context:component-scan base-package= "cn.x5456"/> <!--view interpreter Modelandview.setviewname ("/web-inf/jsp/itemlist.jsp"); ==> modelandview.setviewname ("itemList"); --<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix" value= "/web-inf/jsp/"/> <property name= "suffix" value= ". jsp"/> </bean></beans>
3, configuring Web. XML
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "version=" 3.1 "> <!--configuration look for profile + listener--<context-para M> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/applicationcont ext.xml</param-value> </context-param> <listener> <listener-class>org.springframework .web.context.contextloaderlistener</listener-class> </listener> <!--front-end controllers--<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.dis patcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <se Rvlet-mapping> <servlet-Name>dispatcher</servlet-name> <!--1. /* Block all JSP js PNG. CSS true full intercept recommendation does not use 2. *.action *.do intercept the request with the do action will definitely be able to use ERP 3. /intercept all (excluding JSP) (including. js. Png.css) It is strongly recommended to use front-facing consumer www.jd.com/search/release of static resources--<url-pattern >*.action</url-pattern> </servlet-mapping></web-app>
4. Writing Controller
The class is referred to Spring management @controllerpublic class Itemscontroller { @Autowired private itemservice itemservice; Configure the requested URL @RequestMapping ("/itemlist.action") public Modelandview queryitemlist () { //create the product data that the page needs to display list<item> items = itemservice.selectitemslist (); Modelandview Modelandview = new Modelandview (); Put in the Request field modelandview.addobject ("ItemList", items); Modelandview.setviewname ("/web-inf/jsp/itemlist.jsp"); Modelandview.setviewname ("ItemList"); return modelandview; }
Note: Do not guide the wrong package
two. Integration with MyBatis1, configuration and MyBatis integration of the Applicationcontext.xml
<!--**************** integrated mybatis****************--><!--read configuration file--><context:property-placeholder location= "Classpath:db.properties"/><!--setting up the database connection pool--><bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value=" ${j Dbc.driver} "/> <property name=" url "value=" ${jdbc.url} "/> <property name=" username "value=" ${jdbc.user Name} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" maxactive "value=" 10 "/& Gt <property name= "Maxidle" value= "5"/></bean><!--build mybatis sqlsessionfactory plant--><bean id= " Sqlsessionfactorybean "class=" Org.mybatis.spring.SqlSessionFactoryBean "> <!--injection Connection pool-<property name=" DataSource "ref=" DataSource "/> <!--core profile location--<property name=" configlocation "value=" Classpath:sqlma Pconfig.xml "/></bean><!--Mapper Dynamic agent development scan--><Bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <!--Basic Package, will automatically scan the sub-package--<property name= "Bas Epackage "value=" Cn.x5456.dao "/></bean><!--****************** Configuring annotation Transactions ********************--><!- -Configure the transaction core Manager to encapsulate all transactional operations. Dependent on connection pool--><bean name= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/></bean><!--Open use annotations to manage AOP transactions--><tx:annotation-driven/>
2, Configuration Sqlmapconfig.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--Set alias--><typealiases><!--Specify the scan package, all classes within the package will be alias, alias name is the class name, case insensitive-->< Package Name= "Cn.x5456.domain"/></typealiases><mappers><package name= "Cn.x5456.dao"/> <!- -Configure the Scan mapper interface (must be equipped with)--></mappers></configuration>
3, Db.properties
jdbc.driver=com.mysql.jdbc.driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?characterencoding= Utf-8jdbc.username=rootjdbc.password=xxx
4. Service Layer
Itemservice.java
Public interface Itemservice {public list<item> selectitemslist ();}
Itemserviceimpl.java
@Servicepublic class Itemserviceimpl implements Itemservice { @Autowired private Itemdao Itemdao; Public list<item> selectitemslist () { list<item> itemList = Itemdao.finditemlist (); return itemList;} }
5. DAO Layer
Itemdao.java
Public interface Itemdao { list<item> finditemlist ();}
Itemdao.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Cn.x5456.dao.ItemDao" ><!--bind the current interface to the interface--><!--query all orders--><select id= "Finditemlist "Resulttype=" Item ">select * from ' item ' </select></mapper>
three. Receiving Parameters
Mode one: Receive httpservletrequest,httpservletresponse,httpsession, model to the development of the servlet era
Gets the request,response,session,model@requestmapping ("/itemedit.action") public Modelandview itemEdit that is bound to the current thread ( HttpServletRequest request, HttpServletResponse response, HttpSession session, model model) { //mode one: the way of development of the servlet era c1/>//1. Accept the parameter String id = request.getparameter ("id"); 2. Get current Item information Item item = Itemservice.selectitem (Integer.parseint (ID)); SYSTEM.OUT.PRINTLN (item); 3. Put in the request field Modelandview Modelandview = new Modelandview (); Modelandview.addobject ("Item", item); 4. Set the jump page modelandview.setviewname ("EditItem"); return Modelandview;}
Mode two: Direct receive parameters
Gets the request,response,session,model@requestmapping ("/itemedit.action") public Modelandview itemEdit that is bound to the current thread ( Integer id,httpservletrequest Request, HttpServletResponse response, HttpSession session, model model) { // Mode two: Directly receive the parameters, the field name must be the same as the form came //1. Accept the parameter //string id = request.getparameter ("id"); 2. Get the current Product information Item item = Itemservice.selectitem (ID); SYSTEM.OUT.PRINTLN (item); 3. Put in the request field Modelandview Modelandview = new Modelandview (); Modelandview.addobject ("Item", item); 4. Set the jump page modelandview.setviewname ("EditItem"); return Modelandview;}
Method Three: Receive parameters, encapsulated into Pojo
Gets the request,response,session,model@requestmapping ("/itemedit.action") public Modelandview itemEdit that is bound to the current thread (Item Itempojo,httpservletrequest request, HttpServletResponse response, HttpSession session, model model) { //mode three: Receive parameters, Encapsulated in Pojo //1. Accept the parameter //string id = request.getparameter ("id"); 2. Get current Item information Item item = Itemservice.selectitem (Itempojo.getid ()); SYSTEM.OUT.PRINTLN (item); 3. Put in the request field Modelandview Modelandview = new Modelandview (); Modelandview.addobject ("Item", item); 4. Set the jump page modelandview.setviewname ("EditItem"); return Modelandview;}
Four. Other1, configure the post-commit garbled problem
Xml
<!--processing Post submission garbled problem--><filter> <filter-name>encoding</filter-name> < Filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param > <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param></filter><filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*.action</url-pattern></filter-mapping>
2. Configure the converter
Applicationcontext.xml
<!--configuration Note driver (due to default is obsolete), used to scan annotations such as requestmapping--><!--configuration Converter--><mvc:annotation-driven Conversion-service= "Conversionservicefactorybean"/><!--Configure Conveter Converter conversion Factory (date, remove front and back spaces) ...-->< Bean id= "Conversionservicefactorybean" class= " Org.springframework.format.support.FormattingConversionServiceFactoryBean "> <!--Configuring multiple converters -- <property name= "Converters" > <list> <!--as long as it is in date format, go to this converter (because the date type is accepted)-- < Bean class= "Cn.x5456.conversion.DateConveter"/> </list> </property></bean>
Dateconveter.java
public class Dateconveter implements Converter<string, date> { @Override public Date convert (String s) { C2/>if (S!=null&&!s.equals ("")) { try { SimpleDateFormat SimpleDateFormat = new SimpleDateFormat (" Yyyy:mm-dd hh_mm-ss "); Date realdate = Simpledateformat.parse (s); return realdate; } catch (ParseException e) { e.printstacktrace (); } } return null;} }
springmvc--