SPRINGMVC part of Springmvc,spring,hibernate,mybatis architecture development and construction

Source: Internet
Author: User

Resignation unemployed youths is to have a lot of time to write a blog, before the traditional industry technology strength is relatively small, do not deal with big data, do not get high concurrency, so learn what high-end programming technology and architecture method, then I have to figure out a SSH architecture of things out, hoping to help some friends, Also hope that the big give the corresponding guidance opinion.

Start with something to talk about Sshm=springmvc+spring+hibernate+mybatis, as for why so, I first briefly said.

Springmvc My initial idea was that it was smaller than struts2 and belonged to the lightweight MVC framework, and it was perfectly combined with spring.

I don't need a crap about Spring.

Hibernate is mainly used to request the application of database things, the main implementation of DML statements, but with a relatively bad, not very will, I hope more guidance.

Mybatis is mainly used to query, because query this thing I still like to use SQL to query.

The spring version 3.1.2,hibernate3,mybatis3.1.1 version is still relatively new. Other technologies include, for example, Poi,jdom,jackson, and so on.

Here to insert a section, in spring Select version early, I was using 3.0.5 this version, Jackson used a relatively low version, these two things are incompatible, headache! After experimenting with multiple versions, I found that Jackson was not compatible with this thing, I went, interesting, and finally determined that the spring3.1.2 up and jackson2.1 around the version is compatible, well, when learning.

First look at the basic Web. XML configuration.

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <welcome-file-list> <welcome-file>index.jsp</w Elcome-file> </welcome-file-list> <!--Spring Filter Unified Setup--<filter> <filter-name& Gt Spring character encoding filter</filter-name> <filter-class> Org.springframework.web.filter . Characterencodingfilter </filter-class> <init-param> <param-name>encoding</p             aram-name> <param-value>UTF-8</param-value> </init-param> <init-param>        <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>spring character encoding filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Specify the directory where the spring bean's configuration files are located. The default configuration is in the Web-inf directory-<context-param> <param-name>contextConfigLocation</param-name> & Lt;param-value>classpath:config/applicationcontext*.xml</param-value> </context-param> <!--Web Project Spring loaded log4j Monitor-<listener> <listener-class> org.springframework.web.util.Lo G4jconfiglistener </listener-class> </listener> <!--Spring Application Context Listener primary initialization injection--<lis tener> <listener-class> Org.springframework.web.context.ContextLoaderListener </liste Ner-class> </listener> <!--servlet module will also load {Servletname}-servlet.xml file Springmvc Pre-value control mode base Selvlet--&G    T <servlet> <servlet-naMe>newframe</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherServ Let </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet -mapping> <servlet-name>newframe</servlet-name> &LT;URL-PATTERN&GT;*.DO&LT;/URL-PATTERN&GT;&L t;!         --is to intercept requests that end with. Do, customizable--</servlet-mapping> <!--If the Webapprootkey parameter is not defined, then Webapprootkey is the default "Webapp.root". But it's best to set up to avoid name collisions between projects.        Once defined, the absolute path to root is written to the system variable when the Web container is started.         Then the log4j configuration file can be used ${Myapp.root} to represent the absolute path of the Web directory, the log file is stored in the WebApp.        This parameter is used for the following "Log4jconfiglistener"-<context-param> <param-name>webAppRootKey</param-name> <param-value>myapp.root</param-value> </context-param> <context-param> <param -name>log4jconfiglocation</param-name> &LT;PARAM-VALUE&GT;CLASSPATH:LOG4J.PROPERTIES&LT;/PARAM-VALUE&GT </context-param> <session-config> <session-timeout>15</session-timeout> </session- Config></web-app>

Does every label have a clear idea?

Then we start from the SPRINGMVC first, I here only how to build this MVC process as for the principle of SPRINGMVC, I do not want to do too much introduction, because this is not the focus of this article, and is not a sentence two words can explain the white, I see some articles hundreds of words + A few pictures said this thing Springmvc basic principle, I have skimmed some springmvc source, the complexity of the inside is not simple words can describe the clear, so do not introduce, and so I really thoroughly understand, in writing, The information can refer to the Spring official website of SPRINGMVC Introduction, not very detailed, but also can understand a probably.

Don't gossip, look first. SPRINGMVC configuration file, Location: Wen-inf folder, Named by: Dispatcherservlet in the Web. xml file Serlvletname-servlet.xml for the formula, you can also customize the file name, under the Dispatcherservlet node, add the following configuration:

<init-param>        <param-name>contextConfigLocation</param-name>        <param-value>/ Web-inf/config/applicationcontext-mvc.xml</param-value></init-param>

The contents of the MVC configuration file are as follows:

<?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: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/spring-beans-3.0.xsd Http://www.springframewor K.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd/HTTP Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <!-- Scan all classes in a Web package to complete bean creation and automatic dependency injection-<mvc:annotation-driven></mvc:annotation-driven>

<!--first scan controller after service--<context:component-scan base-package= "com.tansun.newframe.*" > & Lt;context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/> <context:exclude-filter type= "Annotation" expression= "Org.springframework.stereotype.Service"/> < /context:component-scan> <!--make annotations effective-<bean class= "Org.springframework.web.servlet.mvc.annota tion. Annotationmethodhandleradapter "> <property name=" messageconverters "> <list> <ref bean= "Mappingjacksonhttpmessageconverter"/> <bean class = "Org.springframework.http.conve Rter. Stringhttpmessageconverter "> <property name =" Supportedmediatypes "> <list> <bean class= "Org.springframework.http.MediaType" > <coNstructor-arg index= "0" value= "text"/> <constructor-arg index= "1" value= "plain"/&gt ; <constructor-arg index= "2" value= "UTF-8"/> </bean> &lt ; Bean class= "Org.springframework.http.MediaType" > <constructor-arg index= "0" value= "*"/> <constructor-arg index= "1" value= "*"/> &L T;constructor-arg index= "2" value= "UTF-8"/> </bean> </list& Gt </property> </bean> </list> </property> </bean> <! --Springmvc's configuration file, its naming rules: the name of the Springmvc module in Web. xml + "-servlet.xml" for the resolution of the Model view name, that is, adding a prefix to the model view name for example: Controller returns a name The logical view name of test, according to the configuration file, it eventually found the file is/panges/test.jsp, that is, the prefix is assembled into a path. -<bean Id= "Viewresolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <propert Y name= "prefix" value= "/web-inf/pages/" ></property> <property name= "suffix" value= ". JSP" ></proper Ty> </bean> <!--Jaskson for data exchange in JSON format for front and back tables, set the encoding set to UTF-8 encoding-<bean id= "Mappingjacksonhttpmessage Converter "class=" Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter "> <proper Ty name= "Supportedmediatypes" > <list> <value>application/json;charset=utf-8</v alue> </list> </property> </bean> <!--SPRINGMVC exception handling mechanism--< Bean id= "Exceptionresolver" class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > <property name= "Exceptionmappings" > <props> <prop key= "Java.lang.Exception" ; COMMON/ERROR&LT;/PROP&GT <prop key= "java.lang.Throwable" >common/error</prop> </props> </property> <property name= "Statuscodes" > <props> <prop key= "errors/500" >500</prop> <prop key= "errors/404" >404</prop> </props> </property> &lt ;! --Set the log output level, do not define the default output warning error log information--<property name= "warnlogcategory" value= "WARN" ></property> <!--default error page, use this default configuration--<property name= "Defaulterrorview" value= "when the exception that is specified in mappings above is not found in the corresponding view. /error "></property> <!--default HTTP status code--<property name=" Defaultstatuscode "value=" Lt;/property> </bean> </beans>

Based on the above configuration, the basic configuration of SPRINGMVC should be completed, simply write a controller.

@Controller annotations for this class as Controller

Before @RequestMapping the annotation class, it can be understood as a predecessor name for the request URL, which can be understood as the post-name of the request before the method, and the request of the code is/newframe/test/getalldemo.do

@Resource don't need to explain too much, people who have used spring know what to do.

@Controller @requestmapping (value= "/test") public class DemoControl {        @Resource (name= "Demoservice")    public Demoservice Cdemoservice;        @RequestMapping (value= "/getalldemo.do", method=requestmethod.get) public    Modelandview Getalldemo () {        Modelandview Treturn = new Modelandview ("Test/test_list");        List<demo> Mdemos =cdemoservice.getalldemo ();        Treturn.addobject ("demos", Mdemos);        return treturn;}    }

Note that the return value is a Modelandview object, and the incoming "test/test_list" in the constructor method is the path to a JSP. In the MVC configuration file has been briefly introduced Internalresourceviewresolver this is his application, he said after the execution of this method is forwarded (note is forwarded) to/newframe/test/test_list.jsp, Where the AddObject method sets a pair of key values, set the pair of key values to HttpRequest (note is in request). If you return "Test/test_list" directly, internalresourceviewresolver resolves the string to a JSP path and returns to/newframe/test/test_list.jsp. So how do you get a request or a response in this way? In fact, I personally do not recommend this, because if you use request or response to become a Java EE programming, lost the use of the open source framework, but there are ways

This will allow you to operate the Response,request!

So how does spring work in conjunction with Jackson?

Jackson is an open source technology that transforms Java entity objects into JSON-formatted data formats, and he doesn't need you to write any code (you can, of course, write it, but it's troublesome, if you want to solve it programmatically, I suggest you can use Apache's Jsonarray, Or Google's Gson two technology), only need you to configure to your SPRINGMVC profile, he can be springmvc with the front desk JavaScript perfectly together, the foreground can use jquery to parse the returned JSON data format. The specific configuration method above has been given, below to describe how the controller is applied.

    @RequestMapping (value = "/getusers.do", method = Requestmethod.post)    @ResponseBody public    map<string, Object> getusers (UserInfo UserInfo,            @RequestParam string page, @RequestParam string rows)            throws Exception {        //Get total number of bars        int totalnum = Cuserinfoservice.getusercount ();        Get the query to the user        list<userinfovo> userlist = cuserinfoservice.getusers (userInfo, page,                rows);        map<string, object> mMap = new hashmap<string, object> ();        Mmap.put ("Rows", userlist);        Mmap.put ("Total", totalnum);        return mMap;    }

Here is a note @responsebody his role is that the return value of the Java object (OBEJCT) will be returned to the foreground page in response, there is actually no response what big thing to understand wrong.

The method is simple to return the query to the user's list object, and the total number of bars returned to the page, it is encapsulated in a map, ah, it is so simple, this map in the foreground in JSON format parsing. Specifically how to parse, that is the front-end programmer thing, of course, no front-end you have to parse it, very simple.

Some people ask, you this is really too much trouble if I return two messages, do I have to encapsulate into an object? For example I return to the foreground {["Result", "1"],["MSG", "Failed! "]}, do I also need to encapsulate into an object? In fact, programming is very flexible, and spring's Daniel is of course considering this issue. Please refer to the Method!

/** * User Deletion method * * @param ID * @return * @throws Exception */@RequestMapping (value = "/userdele Te.do ", method = Requestmethod.post) @ResponseBody public string Userdelete (string IDs) throws Exception {St        Ring Mreturn = null;        String mmsg = null;            try {cuserinfoservice.userinfodelete (IDS);            Mmsg = Codetransferutil.transfercode (dataconst.del_success);        Mreturn = Jsonutil.getjsonstring (true, mmsg);            } catch (Syscontlexception sexception) {//log logutil.info (sexception);            Encoding conversion mmsg = Codetransferutil.transfercode (Sexception.getmessage ());        Processing Mreturn = Jsonutil.getjsonstring (false, mmsg);            } catch (Daoexception dexception) {//log logutil.info (dexception);            Encoding conversion mmsg = Codetransferutil.transfercode (Dexception.getmessage ()); Handling Mreturn = Jsonutil.getjsoNstring (False, mmsg);            } catch (Exception e) {logutil.error (e);        Throw e;    } return Mreturn; }

The code returns a JSON-formatted string, and the @responsebody annotation returns a string, with the stringhttpmessageconverter instead of the Jackson

Mappingjacksonhttpmessageconverter, so the string is converted to JSON-formatted data back to the foreground. Simple string, complex object has a clear solution, so there is no problem, such applications are basically applied to the front-office Ajax technology combined.

So the MVC part of the introduction is complete, if there are any questions welcome message, mutual learning with each other progress is the key to blogging, I hope enthusiastically sprayed me ~

Please refer to the following information:

Http://www.springmvc.net

SPRINGMVC part of Springmvc,spring,hibernate,mybatis architecture development and construction

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.