First, create a simple user table
CREATE TABLE ' users ' (
' ID ' int (a) is not NULL auto_increment,
' Name ' varchar (not NULL),
' Age ' int (DEFAULT NULL),
PRIMARY KEY (' id ')
) Engine=innodb auto_increment=19 DEFAULT Charset=utf8;
-- ----------------------------
--Records of users
-- ----------------------------
INSERT into ' users ' VALUES (' 1 ', ' Du Chong ', ' 10 ');
INSERT into ' users ' VALUES (' 2 ', ' Huangchunyu ', ' 12 ');
INSERT into ' users ' VALUES (' 11 ', ' text Jay ', ' 2 ');
INSERT into ' users ' VALUES (' 12 ', ' He Liang ', ' 20 ');
INSERT into ' users ' VALUES (' 13 ', ' super brother ', ' 25 ');
INSERT into ' users ' VALUES (' 14 ', ' po ', ' 10 ');
Ii. using MyEclipse to build a Web engineering SSI
2.1. Jar Package
2.2 Directory Structure
2.3, Springmvc's core servlet ssi-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"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.1.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
<context:component-scan base-package= "Org.ssi.controller"/>
<!--auto-register resolvers and Adapters--
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<aop:aspectj-autoproxy proxy-target-class= "true"/>
<!--the splitter for the View parser--
<bean class= "Org.springframework.web.servlet.view.ContentNegotiatingViewResolver" >
<!--check the suffix name of the request first, and if there is no match, spring checks the ContentType set in the request header to find the appropriate mediatype to return a mediatype
MediaTypes This property stores the name of the suffix you requested or the mediatype that corresponds to the parameter.
-
<property name= "MediaTypes" >
<map>
<entry key= "Atom" value= "Application/atom+xml"/>
<entry key= "html" value= "text/html"/>
<entry key= "JSON" value= "Application/json"/>
</map>
</property>
<!--specific parser--
<property name= "Viewresolvers" >
<list>
<bean class= "Org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/jsp/"/>
<property name= "suffix" value= ". jsp"/>
</bean>
</list>
</property>
</bean>
</beans>
2.4. Web. xml
<?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/web-app_2_5.xsd" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 ">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssi</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
Classpath:applicationContext.xml
</param-value>
</context-param>
<session-config>
<session-timeout>0</session-timeout>
</session-config>
</web-app>
2.5, Conf.xml actually this file can not
<?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>
<typeAliases>
<typealias type= "Org.ssi.model.User" alias= "User"/>
</typeAliases>
</configuration>
2.6. Configure Spring Container Applicationcontext.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:p= "http://www.springframework.org/schema/p"
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-4.1.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
">
<!--Load Database Properties profile
<context:property-placeholder location= "Classpath:db.properties" ignore-unresolvable= "true"/>
-
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<!--
<property name= "Driverclassname" value= "${jdbc.driver}" ></property>
<property name= "url" value= "${jdbc.url}" ></property>
<property name= "Password" value= "${jdbc.password}" ></property>
<property name= "username" value= "${jdbc.username}" ></property>
-
<property name= "Driverclassname" value= "Com.mysql.jdbc.Driver" ></property>
<property name= "url" value= "Jdbc:mysql://localhost:3306/mybatis" ></property>
<property name= "username" value= "root" ></property>
<property name= "Password" value= "root" ></property>
<!--maxactive: Maximum number of connections--
<property name= "maxactive" value= "/>"
<!--minidle: Minimum idle connection--
<property name= "Minidle" value= "5"/>
<!--maxidle: Maximum idle connection--
<property name= "Maxidle" value= "/>"
<!--initialsize: Initialize Connection--
<property name= "initialsize" value= "/>"
< whether the connection is printed when!--is compromised
<property name= "logabandoned" value= "true"/>
<!--removeabandoned: Whether the auto-recycle timeout is connected--
<property name= "removeabandoned" value= "true"/>
<!--removeabandonedtimeout: Time-out (in seconds)-
<property name= "Removeabandonedtimeout" value= "ten"/>
<!--maxwait: Timeout wait time in milliseconds of 1000 equals 60 seconds--
<property name= "maxwait" value= "/>"
<!--the time value, in milliseconds, that sleeps while the idle connection collector thread is running. -
<property name= "Timebetweenevictionrunsmillis" value= "10000"/>
<!--the number of connections that are checked at run time for each idle connection collector thread (if any)-
<property name= "Numtestsperevictionrun" value= "ten"/>
<!--1000 * 60 * 30 connections remain idle in the pool and not be idle connection to the collector thread--
<property name= "Minevictableidletimemillis" value= "10000"/>
</bean>
<bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" >
<property name= "configlocation" value= "Classpath:conf.xml"/>
<property name= "DataSource" ref= "DataSource"/>
<property name= "mapperlocations" value= "Classpath:org/ssi/mapper/*.xml"/>
</bean>
<!--configuration Scanner--
<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >
<!--scan Org.ssi.dao This package and all mapped interface classes under its sub-package--
<property name= "Basepackage" value= "Org.ssi.dao"/>
<property name= "Sqlsessionfactorybeanname" value= "Sqlsessionfactory"/>
</bean>
<!--Configure things--
<bean id= "Txmanager"
class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource" ref= "DataSource"/>
</bean>
<!--annotation transactions--
<tx:annotation-driven transaction-manager= "Txmanager"/>
<context:annotation-config/>
<!--
-
<context:component-scan base-package= "Org.ssi.service,org.ssi.dao,"/>
</beans>
2.7, DAO interface, do not provide implementation class, implementation class has mybatis implementation
Package Org.ssi.dao;
Import java.util.List;
Import Org.ssi.model.User;
Public interface Usermapperi {
/**
* Increase
* @param user
*/
public void AddUser (user user);
/**
* Change
* @param user
*/
public void UpdateUser (user user);
/**
* Delete
* @param ID
*/
public void deleteuser (int id);
/**
* Check
* @param ID
* @return
*/
Public User getUser (int id);
/**
* Check All
* @return
*/
Public list<user> getAllUsers ();
}
Corresponds to the class file and path in the configuration file,
2.8, Pojo class User.java
Package Org.ssi.model;
public class User {
private int id;
private String name;
private int age;
public User (int ID, String name, int age) {
Super ();
This.id = ID;
THIS.name = name;
This.age = age;
}
Public User () {
Super ();
}
public int getId () {
return ID;
}
public void setId (int id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
@Override
Public String toString () {
Return "User [id=" + ID + ", name=" + name + ", age=" + Age + "]";
}
}
2.9, Usermapperi.xml
<?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" >
<!--
Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql the map file name so that the value of the namespace is guaranteed to be unique
For example namespace= "Org.ssi.dao.UserMapperI" is Org.ssi.dao (package name) +usermapperi (usermapperi.xml file removal suffix)
-
<mapper namespace= "Org.ssi.dao.UserMapperI" >
<!--<resultMap> tags to handle mismatches between the properties of Pojo objects and table fields
<resultmap id= "Userresultmap" type= "User" >
<id property= "id" column= "userid"/>
<result property= "name" column= "username"/>
<result property= "Age", column= "age"/>
</resultMap>
-
<!--
To write the query's SQL statement in the Select tab, set the ID property of the Select tag to the Getuser,id property value must be unique,
The ParameterType property cannot be reused to indicate the type of parameter used when querying, and the Resulttype property indicates the type of result set returned by the query
Resulttype= "Org.mybatis.model.User" means the object that encapsulates the query result as a User class returns
The user class is the entity class corresponding to the Users table
-
<!--
Get a user object based on ID query
-
<select id= "GetUser" parametertype= "int"
Resulttype= "User" >
SELECT * from users where id=#{id}
</select>
<insert id= "AddUser" parametertype= "User" >
Insert into users (name, age) VALUES (#{name},#{age})
</insert>
<delete id= "DeleteUser" parametertype= "int" >
Delete from users where Id=#{id}
</delete>
<update id= "UpdateUser" parametertype= "User" >
Update users set Name=#{name},age=#{age} where Id=#{id}
</update>
<select id= "GetAllUsers" resulttype= "User" >
SELECT * from Users
</select>
</mapper>
The IDs of the various operations in the XML file must correspond to the method name one by one in the DAO interface, and no side will error.
In accordance with the above configuration, SPRINGMVC integrated MyBatis's overall architecture has been completed,
Third, write code to test
Controller controllers Ssicontroller.java
Package Org.ssi.controller;
Import java.util.List;
Import Javax.servlet.http.HttpServletRequest;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.PathVariable;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.ssi.dao.UserMapperI;
Import Org.ssi.model.User;
@Controller
@RequestMapping (value= "/controller")
public class Ssicontroller {
@Autowired
Private Usermapperi Umi;
Private list<user> ulist;
@RequestMapping (value= "/all", method = Requestmethod.get)
Public String uList (HttpServletRequest request) {
Ulist=this.umi.getallusers ();
for (int i = 0; i < ulist.size (); i++) {
System.out.println (Ulist.get (i));
}
Request.setattribute ("Ulist", ulist);
return "AllUsers";
}
@RequestMapping (value = "/addu", method = Requestmethod.post)
Public String Addu (User u) {
This.umi.addUser (U);
return "Redirect:all";
}
@RequestMapping (value = "/delete/{id}", method = Requestmethod.get)
Public String deleteu (httpservletrequest request, @PathVariable Integer ID) {
This.umi.deleteUser (ID);
return "Redirect:/controller/all";
}
@RequestMapping (value = "/get/{id}", method = Requestmethod.get)
Public String Getuserbyid (httpservletrequest request, @PathVariable Integer ID) {
User U=this.umi.getuser (ID);
Request.setattribute ("User", u);
return "UserInfo";
}
@RequestMapping (value = "/update/{id}", method = Requestmethod.post)
Public String updateu (httpservletrequest request, @PathVariable Integer id,user u) {
User Uu=this.umi.getuser (ID);
Uu.setname (U.getname ());
Uu.setage (U.getage ());
This.umi.updateUser (UU);
return "Redirect:/controller/all";
}
}
3.1. Test new
index.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >
<title>add user</title>
<meta http-equiv= "Pragma" content= "No-cache" >
<meta http-equiv= "Cache-control" content= "No-cache" >
<meta http-equiv= "Expires" content= "0" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
<meta http-equiv= "description" content= "This is my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-
<body>
<form action= "Controller/addu" method= "POST" >
Name: <input name= "name" type= "text" ><br>
Age: <input name= "Age" type= "text" ><br>
<input type= "Submit" value= "Submit" >
</form>
<br>
</body>
Before adding:
Add to:
After adding:
Click Edit 19 Obama
userinfo.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"
<base href= " <%=basePath%>
<title>userinfo</title>
<meta http-equiv= "Pragma" content= "No-cache",
<meta http-equiv= "Cache-control" content= "No-cache";
<meta http-equiv= "Expires" content= "0" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3";
<meta http-equiv = "description" content= "This is my page"
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css
-->
<body>
<p align= "center" ><font size= ">userinfo edit</font></p>"
<div align= "center" >
<form action= "Controller/update/${user.id}" method= "POST" >
Name: <input type= "text" name= "name" value= "${user.name}" ><br>
Age: <input type= "text" name= "Age" value= "${user.age}" ><br>
<input type= "Submit" value= "Usubmit" >
</form>
</div>
</body>
SPIRNGMVC Integrated MyBatis for CRUD