In addition to Struts, the mainstream Web MVC framework currently also has Spring MVC. This is mainly because Spring MVC is relatively simple to configure and very clear to use. It is very flexible, has good integration with Spring, and supports RESTful APIs better than struts.
MyBatis is an upgraded version of ibatis. As an old rival to hibernate, it is a persistent layer framework that can customize SQL, stored procedures, and advanced mappings.
The main difference with hibernate is that mybatis is semi-automated, while hibernate is fully automatic, so when the application requirements become more and more complex, automated SQL appears to be more clumsy.
Since I took on a project some time ago, I wanted to use springmvc to do it, so I started playing the game of integrating the framework with a practice attitude. People who often build frames should know that the core of frame building is configuration files. So I mainly post a few configuration files codes. The same goes for me, after I wrote the configuration file, I ran the error and added the jar. Here are the jar packages I use (should be the least):
Note: There are some extra jars in the picture above, for example, the database connection pool I use is Alibaba's druid and log frame-based logback, so related jars are introduced. The use and configuration of these two frameworks are very simple, so I won't go into details here.
1. Integrate SpringMVC
springMybatis-servlet.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Enable spring mvc annotation-driven> <!-- Automatically scan the package name, making Spring support automatic detection of components, such as the annotated Controller--> <context:component-scan base-package="com.alibaba.controller" /> <context:component-scan base-package="com.alibaba.service"/> <!-- View parser: define the pre-suffix of the jumped file --> <bean id="viewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> <!-- Can be empty, convenient to implement the logic of the view interpretation class based on the extension --> </bean> <!--Configure the interceptor, Multiple interceptors, executed sequentially --> <mvc:interceptors> <mvc:interceptor> <!-- The matching url path--> <mvc:mapping path="/user/**" /> <mvc:mapping path="/test/**" /> <bean></bean> </mvc:interceptor> <!-- When setting up multiple interceptors, first call the preHandle method in sequence, and then call the postHandle and afterCompletion methods of each interceptor in reverse order--> </mvc:interceptors> </beans>
2. Integrate Mybatis
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:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- The class under this package supports annotations, indicating that it will be processed as {@code mybatis mapper} and then configured, indicating that the mapper class can be automatically introduced--> <mybatis:scan base-package="com.alibaba.dao"/> <!--Introduce property files--> <context:property-placeholder location="classpath:configuration.properties"/> <!--Database connection--> <bean id="dataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- Configure initialization size, minimum, maximum--> <property name="initialSize"><value>1</value></property> <property name="maxActive"><value>5</value></property> <property name="minIdle"><value>1</value></property> <!-- Configure the time to get the connection waiting timeout --> <property name="maxWait"><value>60000</value></property> <!-- Configure filters for monitoring statistics intercepts --> <property name="filters"><value>stat</value></property> <!-- Configure how long it takes to perform a detection interval to detect the idle connection that needs to be closed, in milliseconds --> <property name="timeBetweenEvictionRunsMillis"><value>60000</value></property> <!-- Configure the minimum time for a connection to survive in the pool, in milliseconds --> <property name="minEvictableIdleTimeMillis"><value>300000</value></property> <!-- <property name="validationQuery"><value>SELECT 'x'</value></property> <property name="testWhileIdle"><value>true</value></property> <property name="testOnBorrow"><value>false</value></property> <property name="testOnReturn"><value>false</value></property> <property name="poolPreparedStatements"><value>true</value></property> <property name="maxOpenPreparedStatements"><value>20</value></property> --> </bean> <!-- mybatis configuration--> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> </bean> </beans> 3.web.xml integrates SpringMVC and Mybatis
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- The servlet is provided for containers such as tomcat, jetty, etc., and changes the static resource mapping from / to /static/ directory. For example, when you visited http://localhost/foo.css, now http://localhost/static/foo.css --> <!-- Don't intercept static files --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/js/*</url-pattern> <url-pattern>/css/*</url-pattern> <url-pattern>/images/*</url-pattern> <url-pattern>/fonts/*</url-pattern> </servlet-mapping> <!-- Configuring character set --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- When initializing the DispatcherServlet, the framework looks for a file named [servlet-name]-servlet.xml in the web application WEB-INF directory, and defines the relevant beans there, overriding any beans defined globally --> <servlet> <servlet-name>springMybatis</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMybatis</servlet-name> <!-- All requests will be processed by DispatcherServlet--> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- druid web monitoring--> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page> </web-app>
4.logback.xml log configuration
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="test.LogbackTest" level="TRACE"/> <logger name="com.alibaba.controller.TestController" level="TRACE"/> <logger name="org.springframework.web.servlet.DispatcherServlet" level="DEBUG" /> <logger name="druid.sql" level="INFO" /><!-- If slf4j is not configured in spring-config, the sql log will not be displayed. logback is just an implementation of slf4j --> <root level="debug"> <appender-ref ref="STDOUT" /> </root> </configuration> 5. Configuration.properties configuration
jdbc.url=jdbc/:mysql/://localhost/:3306/druid?useUnicode/=true&characterEncoding/=UTF-8&zeroDateTimeBehavior/=convertToNull jdbc.username=root jdbc.password=123456
6. Test whether the construction is successful, background code
First, log in, use encryption, you can remove it
package com.alibaba.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.alibaba.model.User; import com.alibaba.service.UserService; import com.alibaba.util.RequestUtil; /** * @author tfj * 2014-7-26 */ @Controller public class SystemController { private final Logger log = LoggerFactory.getLogger(SystemController.class); @Resource private UserService userService; @RequestMapping(value = "/",method = RequestMethod.GET) public String home() { log.info("Return to homepage!"); return "index"; } @RequestMapping(value = "/test/hello",method = RequestMethod.GET) public String testHello() { log.info("Execute the testHello method!"); return "testHello"; } @RequestMapping(value = "/login",method = RequestMethod.POST) public String testLogin(HttpServletRequest request,@RequestParam String username, @RequestParam String password) { log.info("Execute the testLogin method! "); User user = userService.findUserByName(username); if(user!=null){ if(user.getPassword().equals(DigestUtils.md5Hex(password))){ request.getSession().setAttribute("userId", user.getId()); request.getSession().setAttribute("user", username); return "redirect:" + RequestUtil.retrieveSavedRequest();//Skip to access page}else{ log.info("Password error"); request.getSession().setAttribute("message", "User name and password are incorrect, please log in again"); return "login"; } }else{ log.info("user name does not exist"); request.getSession().setAttribute("message", "User name does not exist, please log in again"); return "login"; } } } I won't write about service and model, I'll write about mybatis' mapper class map
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.alibaba.dao.UserMapper"> <select id="findUserByName" resultType="com.alibaba.model.User"> select id, username , password from sysuser where username = #{username} </select> </mapper> 7. The front desk jsp is mainly a page where login and login is successful, so I won't write it
Post a screenshot:
At this point, the integration of springmvc+mybatis has been successful. Subsequently complex functions to be added
Things to note
1. The configurations of druid and logback in the framework are copied from the official website, so they are all the most basic. Readers can ignore them, or they can be replaced with database components and log frameworks that readers are familiar with, such as c3p0 and log4j.
2. The code has permission management added, that is, you need to log in before accessing, and then jump to the page to be accessed after logging in. For permission management of springmvc, please see: http://www.VeVB.COM/article/99569.htm
3. This article is the simplest and most basic code that has been stripped out from my test code. Please forgive me for some of the areas that have not been stripped out.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.