SpringMVC (iv) ------ login Implementation of SSM integration based on three frameworks; springmvc ------ ssm

Source: Internet
Author: User

SpringMVC (iv) ------ login Implementation of SSM integration based on three frameworks; springmvc ------ ssm

For the sake of further explanation, we will retrieve data from the database. So here we will talk about the integration of the three major frameworks (Spring, SpringMVC, and MyBatis. I explained MyBatis earlier, wrote a MyBatis and Spring integration, interested can look at: http://www.cnblogs.com/ysocean/p/7368499.html, then we directly enter the subject!

This blog source code download link: http://pan.baidu.com/s/1skAfNRZ password: n3fn

1. Integration ideas

  

 

① The presentation layer, that is, the Controller, is controlled by SpringMVC. SpringMVC is a module of Spring and therefore does not need to be integrated.

② The service layer, that is, the service, is usually managed by Spring. We will configure the service interface to the spring configuration file using xml configuration. In addition, transaction control is generally configured at the service layer.

③ Persistence layer, that is, dao layer, and including entity classes, managed by MyBatis and managed by spring ER interface through spring, use the er scanner to automatically scan mapper interfaces for registration in spring.

Obviously, spring plays a crucial role in the integration of the three frameworks. Similar to a big manager, it integrates MyBatis and SpringMVC.

 

 

2. Prepare the environment

①. Database environment

Database Type: MySQL 5.1

Database Name: ssm

Data Table: user

    

 

②. Development Tool eclipse

③ JDK 1.7

④ Mybatis 3.3

⑤ SpringMVC 4.2.4

6. Spring 4.2.4

7. Database Connection Pool dbcp1.2.2

Connector and database driver package mysql5.1.26

Logging, log log4j 1.2

 

  Case requirement: Enter the user name and password for login verification

  For specific jar downloads, see the source code download link above!

The directory structure of the project is as follows:

  

 

3. Integrate the Dao Layer

That is, the integration of MyBatis and Spring

  ① Save the basic information of the database connection in the db. properties file.

#db.propertiesdataSource=org.apache.commons.dbcp.BasicDataSourcedriver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/ssmusername=rootpassword=root

These are database connection pool data sources, database connection drivers, database connection URLs, database connection usernames, and database connection passwords.

  ② Mybatis global profile mybatis-configuration.xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- Add global setting configuration as needed --> <! -- Enable Level 2 Cache --> <settings> <setting name = "cacheEnabled" value = "true"/> </settings> <! -- Configure the alias --> <typeAliases> <! -- Batch scan aliases --> <package name = "com. ys. po"/> </typeAliases> <! -- Configure mapper. Because the er package of spring and mybatis is used for mapper scanning, you do not need to configure mapper. xml and mapper. java files with the same name and under the same directory --> <! -- <Mappers> </mappers> --> </configuration>

You can use the mapper interface to load the ing file. For details, refer to this blog: http://www.cnblogs.com/ysocean/p/7301548.html:

1. The xxxMapper interface must be in the same package as the xxxMapper. xml file. That is to say, the namespace in the UserMapper. xml file is the full Class Name of the UserMapper interface.

2. The method names in the xxxMapper interface are the same as those defined in the xxxMapper. xml file.

3. The input parameter type of the xxxMapper interface must be consistent with the parameterType defined in xxxMapper. xml.

4. The returned data type of the xxxMapper interface must be consistent with the resultType defined in xxxMapper. xml.

 

  ③ Configure the Spring File

We need to configure the data source, SqlSessionFactory, and mapper scanner, because this is an integration of the Dao layer, followed by integration of the business layer, presentation layer, and so on, in order to make the entries more fresh, we create a new config/spring folder, where the configuration file named spring-dao.xml is put.

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 ht Tp: // 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 http://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.sprin Gframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <! -- Step 1: configure the data source --> <! -- Load db. content in the properties file, db. the key name in the properties file must be special --> <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> <p Roperty name = "password" value = "$ {jdbc. password} "> </property> <property name =" maxActive "value =" 30 "> </property> <property name =" maxIdle "value =" 5 "> </ property> </bean> <! -- Step 2: Create sqlSessionFactory. Produce sqlSession --> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. SqlSessionFactoryBean"> <! -- Database connection pool --> <property name = "dataSource" ref = "dataSource"> </property> <! -- Load the mybatis global configuration file. Pay attention to the directory of this file --> <property name = "configLocation" value = "classpath: mybatis/mybatis-configuration.xml "> </property> </bean> <! -- Step 3: configure mapper scanner * Interface Class Name and ing file must have the same name * interface class and ing file must be in the same directory * nameing file namespace name must be interface full class path name * interface method name must be consistent with the id mapped to Statement --> <bean class = "org. mybatis. spring. mapper. mapperScannerConfigurer "> <! -- Path of the scanned package. To scan multiple packages, use commas to separate them. --> <property name = "basePackage" value = "com. ys. mapper "> </property> <property name =" sqlSessionFactoryBeanName "value =" sqlSessionFactory "> </property> </bean> </beans>

  ④ Generate po class and ER er File Based on Reverse Engineering

For how to use reverse engineering, refer to this blog:

  

The following code is added to UserMapper. java for logon authentication:

Package com. ys. mapper; import com. ys. po. user; import java. util. list; import org. apache. ibatis. annotations. param; public interface UserMapper {// query User selectUserByUsernameAndPassword (user User) using the User name and password );}

UserMapper. xml

<! -- Query User by User name and password --> <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 integration of the dao layer, we should conduct a test to develop the habit of testing each small module. Step by step. If the entire project is configured and tested, troubleshooting becomes very difficult.

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 ClassPathXmlApplicationContext("classpath:spring/application-dao.xml");}@Testpublic void testSelectByPrimaryKey(){UserMapper userMapper = (UserMapper) context.getBean("userMapper");User user = userMapper.selectByPrimaryKey(1);System.out.println(user.getPassword());}}

The query is based on the id of the user table. If the user object value can be printed, the preceding configuration is OK.

 

 

4. Integrated service

We have sorted out that this layer uses Spring to manage service interfaces. We will use xml configuration to configure service interfaces to the spring configuration file. In addition, transaction control is configured at the service layer.

Here we log on

  1. Define the service Interface

Package com. ys. service. impl; import com. ys. po. User; public interface IUserService {// query Userpublic User selectUserByUsernameAndPassword (User user User) by User name and password );}

② Compile the service implementation class

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 to the spring container through @ Autowired // query User @ Overridepublic User selectUserByUsernameAndPassword (User user) by User name and password) {User u = userMapper. selectUserByUsernameAndPassword (user); return u ;}}

@ Autowired is used to inject UserMapper into the spring container, which is scanned by the spring scanner and loaded into the spring container.

  

  ③ Configure the Service interface in the spring container. Here we use the xml method.

  Create a spring-service.xml 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: 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 ht Tp: // 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 http://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.sprin Gframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <! -- Configure UserServiceImpl --> <bean id = "userService" class = "com. ys. service. UserServiceImpl"> </bean> </beans>

  

  

 ④ Configure transaction processing in the spring container

Create a spring-transaction.xml 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: 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 ht Tp: // 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 http://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.sprin Gframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <! -- Transaction Manager --> <! -- Control Data transactions for mybatis operations. spring uses the jdbc transaction control class --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager"> <! -- Data Source dataSource is configured in spring-dao.xml --> <property name = "dataSource" ref = "dataSource"/> </bean> <! -- Notification --> <tx: advice id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <tx: method name = "save *" propagation = "REQUIRED"/> <tx: method name = "delete *" propagation = "REQUIRED"/> <tx: method name = "update *" propagation = "REQUIRED"/> <tx: method name = "insert *" propagation = "REQUIRED"/> <tx: method name = "find *" propagation = "SUPPORTS" read-only = "true"/> <tx: method name = "get *" propagation = "SUPPO RTS "read-only =" true "/> <tx: method name =" select * "propagation =" SUPPORTS "read-only =" true "/> </tx: attributes> </tx: advice> <aop: config> <! -- Com. ys. service. all classes, methods, and any parameters in the impl package --> <aop: advisor advice-ref = "txAdvice" pointcut = "execution (* com. ys. service. impl. *. *(..)) "/> </aop: config> </beans>

 

 

4. Integrate SpringMVC

  ① Configure 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> <! -- Configure the front-end controller DispatcherServlet --> <servlet-name> springmvc </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <! -- Springmvc. xml is a self-created SpringMVC global configuration file, with contextConfigLocation as the parameter name to load if not configured contextConfigLocation, then the default load is/WEB-INF/servlet name-servlet. xml, here is the springmvc-servlet.xml --> <init-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: spirng/springmvc. xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> springmvc </servlet-name> <! -- First configuration :*. do, you can also write *. action, and so on. do ends. the URL at the end of the action is parsed by the front-end controller DispatcherServlet. The second configuration is:/. All the accessed URLs are parsed by DispatcherServlet. However, it is best to configure the static file to parse the error configuration by DispatcherServlet: /*. Note that this cannot be configured here. It should be written in this way. When it is finally forwarded to the jsp page, it will still be parsed by DispatcherServlet, and the corresponding Handler will not be found at this time, thus, an error is reported !!! --> <Url-pattern>/</url-pattern> </servlet-mapping> </web-app>

  

  ② Configure the processor er, processor adapter, and view parser

Create a springmvc. xml file in 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: 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 ht Tp: // 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/context 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.springfra Mework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <! -- Using mvc: annotation-driven can replace the above mappers and adapters. Many parameter binding methods are loaded by default. For example, the json conversion parser loads parameters by default, therefore, the following configuration --> <mvc: annotation-driven> </mvc: annotation-driven> <! -- Configure Handler in batches and specify the full name of the scanned package --> <context: component-scan base-package = "com. ys. controller"> </context: component-scan> <! -- Configure the view parser --> <bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver"> </bean> </beans>

  

  

  ③ Compile Handler, that is, Controller

Create a 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; @ Reque Login apping ("/login") public ModelAndView login (User user User) {ModelAndView mv = new ModelAndView (); User u = userService. selectUserByUsernameAndPassword (user); // query the user based on the user name and password. If the user exists, the user is redirected to success. jsp page if (u! = Null) {mv. addObject ("username", u. getUsername (); mv. addObject ("user", u); mv. setViewName ("view/success. jsp ");} else {// jump to login if it does not exist. log on to return new ModelAndView ("redirect:/login. jsp ") ;}return mv ;}}

  

Load Spring containers

We created new spring-dao.xml, spring-service.xml, spring-transaction.xml files under the classpath/spring Directory, which contains the mapper, controller, service we configured, so how to load these into the spring container?

Add the following code to the web. xml file:

<! -- Load the spring container --> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: spring/spring -*. xml </param-value> </context-param> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener>

Because there are many configuration files, we use wildcard loading. Note: This code should be added before the front-end controller.

So far, the integration of the three SSM frameworks has been completed, and we will test it.

  

5. Test

Create a login. jsp page and a success. jsp page in the WebContent directory, for example:

  

 

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. Release the project to tomcat, how to publish can refer to this blog: http://www.cnblogs.com/ysocean/p/6893446.html

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

  

Click to submit:

    

 

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.