SPRINGMVC Details (iv)------SSM Three framework integration of login function implementation

Source: Internet
Author: User

For the sake of explaining later, we get the data from the database, so let's talk about the integration of the three frameworks (Spring, SPRINGMVC, MyBatis). Before explaining MyBatis, wrote a MyBatis and Spring integration, interested can first look: http://www.cnblogs.com/ysocean/p/7368499.html, then we go directly to the topic!

This blog source download link: Http://pan.baidu.com/s/1skAfNRZ Password: N3FN

1. Integration Ideas

  

①, the performance layer, that is, controller, by the SPRINGMVC to control, and Springmvc is a spring module, it does not need to be integrated.

②, the business layer, which is service, typically manages the service interface by Spring, and we use the XML configuration to configure the service interface to the spring configuration file. Also, transaction control is typically configured at the service level.

③, the persistence layer, which is the DAO layer, and includes the entity class, managed by MyBatis, manages the Mapper interface through spring, and uses the Mapper scanner to automatically scan the Mapper interface for registration in spring.

It is clear that spring occupies a critical position in the integration of the three frameworks, akin to a great housekeeper, who MyBatis and Springmvc together.

2. Preparation environment

①, database environment

Database type: MySQL 5.1

Database name: SSM

Data sheet: User

    

②, development tools Eclipse

③, JDK 1.7

④, MyBatis 3.3

⑤, Springmvc 4.2.4

⑥, Spring 4.2.4

⑦, database connection pool dbcp1.2.2

⑧, database driver package mysql5.1.26

⑨, log log4j 1.2

  Case requirements: Enter user name and password for login verification

  The specific jar download see the source download link above!

The directory structure of the project is:

  

3. Integrated Dao Layer

Which is to integrate MyBatis and Spring

  ①, in the Db.properties file, save the basic information of the database connection

#db. propertiesdatasource=org.apache.commons.dbcp.basicdatasourcedriver=com.mysql.jdbc.driverurl=jdbc:mysql:// Localhost:3306/ssmusername=rootpassword=root

Database connection pool data source, database connection driver, database connection URL, database connection user name, database connection password, respectively.

  ②, mybatis global configuration file Mybatis-configuration.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--Global Setting configuration, add-->< as needed  !--turn on level two cache  --><settings><setting Name= "cacheenabled" value= "true"/></settings><!--configuration alias--><typealiases><!--Batch Scan alias-- <package name= "Com.ys.po"/></typealiases><!--configuration Mapper, thanks to the MyBatis scan using the spring and mapper integration packages, No configuration required here: Mapper.xml and Mapper.java files have the same name and are in the same directory-<!--<mappers> </mappers>--></ Configuration>

Through the mapper interface to load the mapping file, specifically, you can read this blog: http://www.cnblogs.com/ysocean/p/7301548.html, must meet the following four points:

1. The Xxxmapper interface must have the same name as the Xxxmapper.xml file and under the same package, that is, the namespace in the Usermapper.xml file is the full class name of the Usermapper interface.

2. The method name in the Xxxmapper interface is consistent with the ID defined in the Xxxmapper.xml file

3, Xxxmapper interface input parameter type to be consistent with the parametertype defined in the Xxxmapper.xml

4. Xxxmapper interface returns data type consistent with Resulttype defined in Xxxmapper.xml

  ③, configuring Spring files

We need to configure the data source, Sqlsessionfactory and Mapper scanner, as this is the integration of the DAO layer, behind the business layer, the performance layer, and so on, in order to make the entry more fresh, we create a new config/spring folder, Here the configuration file is named Spring-dao.xml into it.

Spring-dao.xml

<?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:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/     Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context htt P://www.springframework.org/schema/context/spring-context-3.2.xsd 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 "><!--First step: Configure Data Source--<!--load the contents of the Db.properties file, the key name in the Db.properties file must have a certain particularity--><context:property-placeholder location= " Classpath:db.properties "/><bean id=" DataSource "class=" Org.apache.commons.dbcp.BasicDataSource " Destroy-method= "Close" ><property name= "Driverclassname" value= "${jdbc.driver}" ></property>< Property name= "url" value= "${jdbc.url}" ></property><property name= "username" value= "${jdbc.username}" ></property><property name= "Password" value= "${jdbc.password}" ></property><property name= "Maxactive" value= "></property><property name=" Maxidle "value=" 5 "></property></bean > <!--Step two: Create Sqlsessionfactory. Production Sqlsession--<bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <!--data Library Connection pool-<property name= "DataSource" ref= "DataSource" ></property> <!--load MyBatis Global configuration file, note the directory of this file-- > <property name= "configlocation" value= "classpath: Mybatis/mybatis-configuration.xml "></property> </bean> <!--step Three: Configure Mapper Scanner * Interface class name and mapping file must have the same name * The interface class and the mapping file must be in the same directory * Map file namespace name must be the full class path name of the interface * The method name of the interface must be the same as the ID of the map statement--><bean class= "Org.mybatis.spri Ng.mapper.MapperScannerConfigurer "><!--scanned package path, if you need to scan multiple packages, use commas between <property name=" Basepackage " Value= "Com.ys.mapper" ></property> <property name= "Sqlsessionfactorybeanname" value= "sqlsessionfactory "></property> </bean> </beans>

  ④, generating PO classes and Mapper files based on reverse engineering

How to use reverse engineering, you can refer to this blog: http://www.cnblogs.com/ysocean/p/7360409.html, we reverse engineering if an additional project generates the PO class and the Mapper file we need, Copy it into our current project, as follows:

  

Since we are here for login verification, add the following code in Usermapper.java:

Package Com.ys.mapper;import Com.ys.po.user;import Java.util.list;import Org.apache.ibatis.annotations.Param; Public interface Usermapper {    //username and password to query user user    Selectuserbyusernameandpassword;}

Usermapper.xml

<!--query by username and password user--  <select id= "Selectuserbyusernameandpassword" resulttype= "Com.ys.po.User" Parametertype= "Com.ys.po.User" >  select * from User where username = #{username,jdbctype=varchar} and password = #{ Password,jdbctype=varchar}  </select>

  

After the DAO layer has been integrated, we conduct a test to get into the habit of having to test every little module that is done. Step by step, if the entire project is configured and then tested, then it becomes difficult to troubleshoot problems.

Package Com.ys.test;import Org.junit.before;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.ys.mapper.usermapper;import Com.ys.po.user;public class Daotest {ApplicationContext context = null; @Beforepublic void init () {context = new classpathx Mlapplicationcontext ("Classpath:spring/application-dao.xml");} @Testpublic void Testselectbyprimarykey () {Usermapper usermapper = (usermapper) context.getbean ("Usermapper"); User user = Usermapper.selectbyprimarykey (1); System.out.println (User.getpassword ());}}

This is a query based on the ID of the user table. If you can print out the value of the user object, the previous configuration is OK.

4. Integrated service

In front of us, this layer is using spring to manage the service interface, and we will use the XML configuration to configure the service interface to the spring configuration file. and transaction control is also configured at the service layer.

Here we log in

  ①, defining Service Interfaces

Package Com.ys.service.impl;import Com.ys.po.user;public Interface Iuserservice {//user name and password query userpublic user Selectuserbyusernameandpassword (user user);}

②, writing service implementation classes

Package Com.ys.service;import Org.springframework.beans.factory.annotation.autowired;import Com.ys.mapper.usermapper;import Com.ys.po.user;import Com.ys.service.impl.iuserservice;public Class Userserviceimpl implements iuserservice{@Autowiredprivate Usermapper Usermapper; Inject usermapper//through @autowired to the Spring container user@overridepublic user Selectuserbyusernameandpassword by username and password User U = Usermapper.selectuserbyusernameandpassword (user); return u;}}

By injecting usermapper into the spring container through @autowired, it is scanned by the spring-fitted scanner and loaded into the spring container.

  

  ③, configuring the Service interface in the Spring container, where we use XML

  Under the Config/spring directory, create a new spring-service.xml

<?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:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/     Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context htt P://www.springframework.org/schema/context/spring-context-3.2.xsd 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 "><!--configuration Userserviceimpl --><bean id= "UserService" class= "Com.ys.service.UserServiceImpl" ></bean> </beans> 

  

  

 ④, configuring transactions in the Spring container

Under the Config/spring directory, create a new spring-transaction.xml

<?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:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/     Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context htt P://www.springframework.org/schema/context/spring-context-3.2.xsd 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 "><!--transaction manager--><!--to MyBatis Operational Data transaction control, Spring uses the JDBC transaction control class--><bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <!--Data source datasource configured in Spring-dao.xml-- > <property name= "dataSource" ref= "DataSource"/></bean><!--notice--><tx:advice id= "Txadvice" tr Ansaction-manager= "TransactionManager" > <tx:attributes> <tx:method name= "save*" propagation= "Requi RED "/> <tx:method name=" delete* "propagation=" REQUIRED "/> <tx:method name=" update* "Propagatio n= "REQUIRED"/> <tx:method name= "insert*" propagation= "REQUIRED"/> <tx:method name= "find*" prop         agation= "SUPPORTS" read-only= "true"/> <tx:method name= "get*" propagation= "SUPPORTS" read-only= "true"/> <tx:method name= "select*" propagation= "SUPPORTS" read-only= "true"/> &LT;/TX:ATTRIBUTES&GT;&LT;/TX:ADVICE&G T;<aop:config> <!--Com.ys.service.impl Pack All the classes, all the methods, any parameters--<aop:advisor advice-ref= "Txadvice" pointcut= "Execution (* com.ys.service.impl.*.* (..))" /></aop:config> </beans>

4, integrated SPRINGMVC

  ①, configuring the front-end controller

Add the following code to the Web. xml file:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name>SpringMVC_01< /display-name> <!--Configuring the front-end controller Dispatcherservlet-<servlet> <servlet-name>springmvc</    Servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Springmvc.xml is a SPRINGMVC global profile created by itself, loaded with contextconfiglocation as the parameter name if you do not configure Contextconfiglocation, the default load is/ Web-inf/servlet name-servlet.xml, here is Springmvc-servlet.xml--<init-param> <param-name>cont Extconfiglocation</param-name> <param-value>classpath:spirng/springmvc.xml</param-value> </ init-param> </servlet> <servlet-mapping> <servlet-name>sprinGmvc</servlet-name> <!--The first configuration: *.do, can also write *.action and so on, indicating that URLs with a. Do ending or ending with. Action are parsed by the front-end controller Dispatcherservlet The second configuration:/, all access URLs are resolved by Dispatcherservlet, but it is best to configure static files not by Dispatcherservlet to parse the error configuration:/*, note that this is not configured this way, should be written as such, and then forwarded to the JSP      Page, will still be resolved by the Dispatcherservlet, and this time will not find the corresponding handler, thus error!!! -<url-pattern>/</url-pattern> </servlet-mapping></web-app>

  

  ②, configuring processor Mapper, processor adapter, view resolver

Create a new Springmvc.xml file under the config/spring directory

<?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:mvc= "Http://www.springframework.org/schema/mvc" xmlns:c        ontext= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" 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.2.xsd Http://www.springframework.org/schema /MVC http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd Http://www.springframework.org/schema/co ntext http://www.springframework.org/schema/context/spring-context.xsd Http://www.springframework.org/schema        /AOP http://www.springframework.org/schema/aop/spring-aop-4.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.oRg/schema/tx/spring-tx.xsd "><!--use Mvc:annotation-driven to replace the above mapper and adapter this will load many parameter binding methods by default, such as the JSON conversion parser is loaded by default, So first use the following configuration--><mvc:annotation-driven></mvc:annotation-driven><!--bulk Configuration Handler, specify the package name to scan-- <context:component-scan base-package= "Com.ys.controller" ></context:component-scan><!--Configuration View Resolver-- ><bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" ></bean></ Beans>

  

  

  ③, write Handler, that is, Controller

Create a new Usercontroller.java file under the Com.ys.controller package

Package Com.ys.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.modelandview;import Com.ys.po.user;import com.ys.service.impl.iuserservice;@ Controllerpublic class Usercontroller {@Autowiredpublic iuserservice userservice; @RequestMapping ("/login") public Modelandview Login (user user) {modelandview mv = new Modelandview (); User U = Userservice.selectuserbyusernameandpassword (user);//query for username and password, if present, jump to success.jsp page if (u! = null) { Mv.addobject ("username", U.getusername ()) mv.addobject ("User", u); Mv.setviewname ("view/success.jsp");} else{//If it does not exist, jump to the login.jsp page and log back in to return to new Modelandview ("redirect:/login.jsp");} return MV;}}

  

, loading Spring container

We created spring-dao.xml,spring-service.xml,spring-transaction.xml these files in the Classpath/spring directory with our configured mapper, Controller,service, how do you load these into the spring container?

Add the following code to the Web. xml file:

<!--loading Spring container--><context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:spring/spring-*.xml</param-value></context-param><listener >   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>

Because the configuration file is more, we use the way of the wildcard Fugazai. Note: This code is best added to the front of the front controller.

At this point, the SSM three framework integration is complete, then we will test.

  

5. Testing

Create login.jsp pages in the WebContent directory, as well as success.jsp pages, such as:

  

login.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" >

success.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" >

1, publish the project to Tomcat, how to publish can refer to this blog: http://www.cnblogs.com/ysocean/p/6893446.html

2, in the browser input: http://localhost:8080/SSMDemo/login.jsp

  

Click Submit:

    

SPRINGMVC Details (iv)------SSM Three framework integration of login function implementation

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.