MAVEN+SSM Framework (Spring+springmvc+mybatis)-Hello World (forwarding)

Source: Internet
Author: User
Tags log4j

[JSP] MAVEN+SSM Framework (Spring+springmvc+mybatis)-Hello World

Source: http://blog.csdn.net/zhshulin/article/details/37956105?utm_source=tuicool&utm_medium= Referral (The following blog post has changed and supplemented the original blog post)

The red bottom of the blog post, in order to notice the change of place, here first declare

Source: MAVEN&SSM Framework-Hello World

Development environment:

Eclipse Java EE IDE for WEB developers. Version:mars.2 Release (4.5.2)

apache-tomcat-8.0.33

Jdk1.8.0_77

MySQL 5.0.11-dev (official website download need account login, so do not provide, please own Baidu)

1. Basic Concepts

1.1. Spring

Spring is an open source framework, and spring is a lightweight Java development framework that emerged in 2003 by Rod Johnson in his book expert one-on-one development and Some of the concepts and prototypes elaborated in design are derived. It is created to address the complexities of enterprise application development. Spring uses basic JavaBean to accomplish things that were previously only possible by EJBS. However, the use of spring is not limited to server-side development. From the standpoint of simplicity, testability, and loose coupling, any Java application can benefit from spring. In short, spring is a lightweight control inversion (IoC) and aspect-oriented (AOP) container framework.

1.2, SPRINGMVC

Spring MVC is a follow-on product of springframework and has been integrated into spring Web flow. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, and this separation makes them easier to customize.

1.3, MyBatis

MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis. MyBatis is a Java-based persistence layer framework. The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO) MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and raw mapping, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.


2. Construction of development environment

See Blog: MYECLIPSE+TOMCAT+MAVEN+SVN Project Complete Environment Construction (Shu_lin)


3. Maven Web project Creation

See blog: Creating a Web Project with Maven (Shu_lin) (the last step of the blog can be used without setting up, Maven->update project ... will be set automatically)

Add: (Can skip)

The new Maven,java resources are only resource

You can add the server library automatically generated

Right-click the project->properties->java Build path->add library...->server Library


4. SSM Integration

The following is mainly about the integration of the three frameworks, as for the construction of the environment and the creation of projects, see the above blog post. I've divided 2 profiles for this integration, The Spring-mybatis.xml, which contains the spring and MyBatis profiles, and a configuration file for Spring-mvc, plus 2 resource files: Jdbc.propertis and log4j.properties.

The use of frames is a newer version:

Spring 4.0.2 RELEASE (PS: No manual download required, MAVEN will automatically be down)

Spring MVC 4.0.2 RELEASE (PS: No manual download, maven automatically)

MyBatis 3.2.6 (Download: https://github.com/mybatis/mybatis-3/releases)

The full directory structure is as follows:

4.1. Maven introduces the required jar package

In order to make it easier to say later without the need to introduce the jar package, I am here to give all the necessary jar package, this is the basic jar package, each package is what the comment, no longer say.


Pom.xml

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.2. Integration of Spring and MyBatis

All of the required jar packages are introduced, first with the integration of spring and MyBatis, then the JUnit test, first look at a project map:

4.2.1, creating a JDBC Property file

jdbc.properties(file code modified to Utf-8)

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.2.2, log4j configuration (skip this step also does not affect)

In order to facilitate debugging, the general will use the log to output information, log4j is an Apache open source project, through the use of log4j, we can control the log information delivery destination is the console, files, GUI components, even a socket server, NT Event recorder, UNIX Syslog Daemon, etc. we can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully.
LOG4J configuration is very simple, but also common, the following gives a basic configuration, for other projects do not need to do much adjustment, if you want to make adjustments or want to understand the various configurations of log4j, see my reprint of a blog, very detailed: log4j configuration detailed (Shu_lin)


log4j.properties(file code modified to Utf-8)

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.2.3, establishing spring-mybatis.xml configuration file

This file is used to complete the integration of spring and MyBatis. There are not many lines in the configuration, the main is automatic scanning, automatic injection, configuration database. The notes are also very detailed, and we'll see.


Spring-mybatis.xml

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.2.4, JUnit Test

After the above steps (log4j does not work), we have completed the integration of spring and mybatis so that we can write a test code to try to succeed.

4.2.4.1, creating test tables

Now that we need to test, we need to build a test table in the database, which is very simple and the SQL statement is:

Mysql

# # Structure for table "user_t" #DROP table IF EXISTS ' user_t '; CREATE TABLE ' user_t ' (  ' id ' int (one) not null auto_increment,  ' user_name ' varchar (+) NOT null,  ' password ' VA Rchar (255) NOT NULL,  ' age ' int (4) is not NULL,  PRIMARY KEY (' id ')) engine=innodb auto_increment=2 DEFAULT charset=u tf8;## Data for table "user_t" #INSERT into ' user_t ' VALUES (1, ' Test ', ' 123456 ', 24);

4.2.4.2, using MyBatis Generator to create code automatically

Find a location to create a folder (the path is best in English), and then build a src folder inside, download the following two packages, the generatorconfig.xml copy into, finally open cmd, into the folder, execute the following command, the code will be generated into the SRC folder

Mysql-connector-java.jar

Mybatis-generator-core.jar

Generatorconfig.xml

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

CMD command

Java-jar Mybatis-generator-core-1.3.2.jar-configfile Generatorconfig.xml-overwrite

Can be made into a. bat file, put in the directory to run

CMD command

Set current_path= "%cd%" Java-jar mybatis-generator-core-1.3.2.jar-configfile generatorconfig.xml- Overwritepauseexit

Reference post: SSM framework-Automatically create code with MyBatis Generator (Shu_lin)

This automatically creates the entity class, the MyBatis mapping file, and the DAO interface based on the table and copies the files to the project when it is complete.

Iuserservice.java

Package Com.ssm.service;import Com.ssm.pojo.user;public Interface Iuserservice {public    User Getuserbyid (int USERID);}

Userservice.java

Package Com.ssm.service.impl;import Javax.annotation.resource;import Org.springframework.stereotype.Service; Import Com.ssm.dao.usermapper;import com.ssm.pojo.user;import com.ssm.service.IUserService; @Service ("UserService" ) public class UserService implements Iuserservice {    @Resource    private usermapper Userdao;    Public User Getuserbyid (int userid) {        return This.userDao.selectByPrimaryKey (userid);}    }

4.2.4.4, build test class

The test class is established in Src/test/java, and the commented out part of the test class below is a general test method when you do not use spring, and if you use spring then you can use annotations to introduce the configuration file and class, and then inject the service interface object can be tested. If the test is successful, it means that spring and mybatis have been integrated successfully. The output information is printed to the console using log4j.

Testmybatis.java

Package Com.ssm.testmybatis;import Javax.annotation.resource;import Org.apache.log4j.logger;import Org.junit.before;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Com.alibaba.fastjson.json;import Com.ssm.pojo.user;import Com.ssm.service.IUserService; @RunWith (springjunit4classrunner.class)// Represents the inherited Springjunit4classrunner class @contextconfiguration (locations = {"Classpath:spring-mybatis.xml"}) public class    Testmybatis {private static Logger Logger = Logger.getlogger (Testmybatis.class);    Private ApplicationContext AC = null;    @Resource private Iuserservice userservice = null;    @Before//public void before () {//AC = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); UserService =(Iuserservice) Ac.getbean ("UserService");        } @Test public void Test () {User user = Userservice.getuserbyid (1);        System.out.println (User.getusername ());        Logger.info ("Value:" +user.getusername ());    Logger.info (json.tojsonstring (user)); }}

Test:

Clean item first (can be skipped), then Maven->update project ... (focus), just to update the project settings (right-click the project->run as->junit Test)

At this point, the integration of the two frameworks of spring and MyBatis is completed, and the SPRINGMVC integration is continued below.

If the test fails please refer to the Netizen method, general clean project and right-click Project->maven->update ... Update the project settings to resolve:

4.3, integrated Springmvc

The above has completed the consolidation of the 2 frameworks, the SPRINGMVC configuration file is placed separately, and then the integration is configured in Web. Xml.

4.3.1, configuration Spring-mvc.xml

Configuration inside the note is also very detailed, this is not said, mainly automatic scanning controller, view mode, annotated start of these three.

Spring-mvc.xml

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.3.2, configuring the Web. xml file

This is the case with the introduction of Spring-mybatis.xml and the configuration of the Spring-mvc servlet in order to complete SSM integration, the previous 2 framework consolidation does not need to be configured here. The configuration has the same detailed comment, not much explanation.

Xml

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

4.3.3, testing

So far has completed the SSM three framework of integration, next Test, if successful, then congratulations, if you fail, continue to debug it, as a programmer is constantly fighting against bugs!

4.3.3.1, new JSP page

user.jsp This page only outputs the user name to complete a simple process.

user.jsp

<%@ 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" >

4.3.3.2, establishing Usercontroller class

Usercontroller.java

Package Com.ssm.controller;import Javax.annotation.resource;import Javax.servlet.http.httpservletrequest;import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.web.bind.annotation.requestmapping;import Com.ssm.pojo.user;import Com.ssm.service.IUserService, @Controller @requestmapping ("/user") public class Usercontroller {    @Resource    Private Iuserservice UserService;    @RequestMapping ("/showuser") public    String Toindex (httpservletrequest request, model model) {        int userId = Integer.parseint (Request.getparameter ("id"));        User user = This.userService.getUserById (userId);        Model.addattribute ("user", user);        return "User";    }}

4.3.3.3, Deployment Projects

Test again (right-click on Project->run As->run on Serser), enter address: http://localhost:8080/app/user/showUser?id=1

If successful please don't be too happy, maven->update Project ... or copy the item to another machine and it will appear immediately 404! Shu_lin and other bloggers have not made any follow-up instructions for this purpose and have added this blog post.

Add:

Whether it's the Shu_lin SSM framework-The detailed integration tutorial (spring+springmvc+mybatis) or someone else's blog, none of the Maven->update Project ... Will cause the project to not run, there will be a problem with the spring package classnotfoundexception error,

(For my Novice (Java 0 Basic Novice, Eclipse is not familiar with) head big ... It took me nearly one months to learn this Hello world. Is stuck on this issue. )

Questions begin, find Maven

With this question? The first time to find Maven, but strange, all included?! Why can't I find a class?

From Baidu to find a number of answers, finally found the problem is that the compile time does not copy the dependency package into the Web-inf/lib, the compilation is not generated Lib folder

Temporary method:(PS: Feeling method Not very right, give up)

Baidu has a way to teach you to modify. classpath, manually add/web-inf/lib

<classpathentry kind= "Con" path= "Org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER" >    <attributes>        <attribute name= "maven.pomderived" value= "true"/>        <attribute name= " Org.eclipse.jst.component.dependency "value="/web-inf/lib "/>    </attributes></classpathentry>

Temporary method:

Right-click the project->properties->deployment assembly->add->java Build Path entries->maven dependencies-> Finish Add, then click OK to close

Test again (right-click on Project->run As->run on Serser), enter address: http://localhost:8080/app/user/showUser?id=1, run ok!

Perfect solution:

But after all, it's a temporary method, Maven->update Project ... will still cause the project not to run, because the configuration was maven Restore!!! No, this is still no solution, but also need to find, a few twists finally found!

Open cmd, navigate to the project directory, execute the following command

cmd command (according to the list of Java Build paths, it is not necessary to run this command again as long as the package is not changed)

MVN eclipse:eclipse-dwtpversion=2.0

Can be made into a. bat file, put in the project root directory to run

CMD command

Set current_path= "%cd%" MVN eclipse:eclipse-dwtpversion=2.0pauseexit

After executing the command, clean project and maven->update projects ... , Deployment assembly and Java Build path are changed

Test again (right-click on Project->run As->run on Serser), enter address: http://localhost:8080/app/user/showUser?id=1, run ok! Perfect!

Look at Web-inf again, finally automatically generate Lib folder

MAVEN+SSM Framework (Spring+springmvc+mybatis)-Hello World (forwarding)

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.