The construction of SSM framework--spring+springmvc+mybatis

Source: Internet
Author: User
Tags aop

One: Overview

The SSM framework is often used in project development, and it is applied more broadly in only a few years of development compared to the SSH framework.

Spring, as a lightweight framework, has a lot of expansion capabilities, the most important of which is the IOC and AOP used in our general projects.

SPRINGMVC is a Web layer implemented by spring, equivalent to the struts framework, but more flexible and powerful than struts!

MyBatis is a persistent layer framework that is more flexible to use than hibernate and can control the writing of SQL, using XML or annotations for related configurations!

According to the above description, learning the SSM framework is very important!

Second: The process of building a SSM

Manage projects with Maven

Using MAVEN to create a WebApp project in Eclipse, the specific creation process does not demonstrate, as there is no creation of [Create project]

You can also use the MAVEN command to create, enter the specified directory in a DOS window, and execute the following command:

Mvnarchetype:create-dgroupid=org.ssm.dufy-dartifactid=ssm-demo-darchetypeartifactid=maven-archetype-webapp- Dinteractivemode=false

Use the command to be aware that the system has MAVEN installed and the environment variable is configured! [MAVEN Installation and environment variable configuration]

Import project (named Creation), add dependency

The import project is in the IDE, or it is created directly in the IDE, with the general default of "Src/main/java" and manually creating the "Src/test/resources", "Src/test/java" folder.

The following project structure:

Then directly configure the package dependencies in the Pom.xml file!

4.0.0org.dufyssmwar0.0.1-snapshotssmdemohttp:// Maven.apache.org4.0.5.release3.2.11.6.61.2.125.1.35org.springframeworkspring-core${spring.version} Org.springframeworkspring-webmvc${spring.version}org.springframeworkspring-context${spring.version} Org.springframeworkspring-context-support${spring.version}org.springframeworkspring-aop${spring.version} Org.springframeworkspring-aspects${spring.version}org.springframeworkspring-tx${spring.version} Org.springframeworkspring-jdbc${spring.version}org.springframeworkspring-web${spring.version} Org.springframeworkspring-test${spring.version}testorg.springframeworkspring-webmvc${spring.version} Org.springframeworkspring-web${spring.version}mysqlmysql-connector-java${mysql.version} Com.alibabadruid0.2.23com.alibabafastjson1.1.41log4jlog4j${log4j.version}org.slf4jslf4j-api${slf4j.version} Ch.qos.logbacklogback-classic1.1.2ch.qos.logbacklogback-core1.1.2org.logback-extensionslogback-ext-spring0.1.1org.mybatis Mybatis${mybatis.version}org.mybatismybatis-spring1.2.0javax.servletjavax.servlet-api3.0.1javax.servlet.jspjavax.servlet.jsp-api2.3.2-b01javax.servletjstl1.2junitjunit3.8 .1testssmDemo

Creating databases and tables, generating code

Create a database I refer to the other People's blog database design, this piece did not write their own, directly add code

Droptableifexists user_t ; CreateTable user_t ( id int (one) notnullauto_increment, user_name varchar (notnull), password varchar (255) notnull, age Int (4 ) Notnull, PRIMARYKEY ( id )) engine=innodbauto_increment=2defaultcharset=utf8;/Data for the table user_t / Insertinto user_t ( id , user_name , password , age ) VALUES (1, ' Test ', ' SFASGFAF ', 24)

To generate code, see:

[MyBatis automatically generated code]

The generated code import picture explains:

Spring and MyBatis integration, connecting databases, JUnit testing

Copy the generated code into the project, then integrate the spring and MyBatis to add the configuration file!

Mainly has

ApplicationContent.xml:Spring the relevant configuration!

Spring-mhbatis.xml:spring and MyBatis integrated configuration!

Jdbc.properties: Database Information Configuration!

Logback.xml: Log Output information configuration! (Do not introduce, detailed information to view the source code)

The main introduction applicationcontext.xml, Spring-mhbatis.xml, Jdbc.properties. The main contents are as follows:

Jdbc.properties

jdbc_driverclassname=com.mysql.jdbc.driverjdbc_url=jdbc:mysql://localhost:3306/ssm?useunicode=true& Characterencoding=utf8jdbc_username=rootjdbc_password=root

Applicationcontext.xml

Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

"> can not be configured--

Spring-mybatis.xml

HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd ">

Test the code in two ways:

Test 1:

Package org.ssm.dufy.service;importorg.junit.test;importorg.junit.runner.runwith; importorg.springframework.beans.factory.annotation.Autowired; Importorg.springframework.test.context.ContextConfiguration; importorg.springframework.test.context.junit4.springjunit4cla***unner;importorg.ssm.dufy.entity.user;/**

    • Configure spring and JUnit consolidation, and the JUnit boot load SPRINGIOC container spring-test,junit

*/@RunWith (Springjunit4cla***unner.class)//Tell JUnit Spring configuration file @contextconfiguration ({"Classpath: Applicationcontext.xml "}) publicclassiuserservicetest{@AutowiredpublicIUserServiceuserService; @Testpublicvoid Getuserbyidtest () {useruser = Userservice.getuserbyid (1); System.out.println (User.getusername ()); } }

Test 2:

Package org.ssm.dufy.service;importorg.springframework.context.applicationcontext; Importorg.springframework.context.support.classpathxmlapplicationcontext;importorg.ssm.dufy.entity.user; Publicclassiuserservicetest2{publicstaticvoid Main (string[] args) {applicationcontextapplication = Newclasspathxmlapplicationcontext ("Applicationcontext.xml"); Iuserserviceuservice = (IUserService) Application.getbean ("UserService"); Useruser = Uservice.getuserbyid (1); System.out.println (User.getusername ()); }}

5: Integrate SPRINGMVC, add configuration, create JSP

The dependency required by SPRINGMVC has been added to the pom.xml, and it is now necessary to add the boot SPRINGMVC boot configuration and the spring consolidation SPRINGMVC configuration to Web. XML in the website project.

Add the following two files:

Spring-mvc.xml

Http://www.springframework.org/schema/beans

Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

Http://www.springframework.org/schema/context

Http://www.springframework.org/schema/context/spring-context-3.2.xsd

Http://www.springframework.org/schema/mvc

Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> Application/json-->json=application/json Xml=application/xml html=text/html/mappings, you can map static resources--

Xml

Ssm-democontextconfiglocationclasspath:applicationcontext.xml

Webapprootkey

Springmvc.root

- Springencodingfilterorg.springframework.web.filter.characterencodingfilterencodingutf-8forceencodingtruespringencodingfil Ter/*logbackconfiglocationclasspath: Logback.xmlch.qos.logback.ext.spring.web.LogbackConfigListenerorg.springframework.web.context.ContextLoaderListenerdispat CherServletorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath: spring-mvc.xml1dispatcherservlet/index.jsp

New index.jsp File

<% @pagecontentType = "text/html; Charset=utf-8 "%>

Hello world!

6. Start the Web service, test

Add the above items to Tomcat, launch, console without error, and access in the Address bar, HTTP://LOCALHOST:8080/SSM. Page shows Hello world! Project configuration ok!

7: Write controller, and corresponding business interface

New Usercontroller, through the parameter pass UID to get the user, if the user exists, jump to showname.jsp, if the user does not exist, then jump to error.jsp, and return the prompt message!

Package org.ssm.dufy.web;importjavax.servlet.http.httpservletrequest; Importorg.springframework.beans.factory.annotation.autowired;importorg.springframework.stereotype.controller; importorg.springframework.ui.model;importorg.springframework.web.bind.annotation.requestmapping; Importorg.springframework.web.bind.annotation.RequestMethod; Importorg.springframework.web.bind.annotation.requestparam;importorg.springframework.web.servlet.modelandview; Importorg.ssm.dufy.entity.user;importorg.ssm.dufy.service.iuserservice; @ControllerpublicclassUserController {@ Autowiredprivateiuserserviceuserservice; @RequestMapping (value= "/showname", Method=requestmethod.get) Publicstringshowusername (@RequestParam ("UID") int UID , Httpservletrequestrequest,modelmodel) {System.out.println ("showname"); Useruser = Userservice.getuserbyid (UID), if (user! = null) {Request.setattribute ("name", User.getusername ()); Model.addattribute ("Mame", User.getusername ()); return "ShowName"; } request.setattribute ("Error", "The user was not found!") "); return"Error "; }}

The JSP content is as follows:

showname.jsp

<% @pagecontentType = "text/html; Charset=utf-8 "%>show Name

Three: the problems encountered

1: Unable to find UserService, error

May be a problem with the packet scan path, check whether the service is within the scope of the scan

2:jsp cannot receive Request.setattribute ("", "");

Check the data that is because of the JSP version of the problem, you can add <%@ page iselignored= "false" on the JSP%>

or modify Web. XML to add version!

The construction of SSM framework--spring+springmvc+mybatis

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.