1.在eclipse中配置好“新建動態WEB”,準備好SPRINGMVC/Mybatis相關Jar。
主要代碼:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>springmvcmybatis</display-name>
<servlet>
<servlet-name>springmvcmybatis</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcmybatis</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvcmybatis-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
springmvcmybatis-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<context:component-scan base-package="com.springmvcmybatis.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
springmvcmybatis-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="com.springmvcmybatis.po"></context:component-scan>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/javadb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true" />
<property name="username" value="root" />
<property name="password" value="xxxxxxxxxxx" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven
transaction-manager="transactionManager" />
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:mybatis-config.xml" />
</bean>
<bean id="customerMapper"
class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface"
value="com.springmvcmybatis.mapper.CustomerMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean name="/home" class="com.springmvcmybatis.controller.HomeController"></bean>
</beans>
mybatis-config.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>
<!--配置別名 -->
<typeAliases>
<package name="com.springmvcmybatis.po" />
</typeAliases>
<!--配置Mapper的位置 -->
<mappers>
<!-- <mapper resource="com/springmvcmybatis/po/CustomerMapper.xml" />
-->
<mapper resource="com/springmvcmybatis/mapper/CustomerMapper.xml" />
</mappers>
</configuration>
com.springmvcmybatis.mapper/CustomerMapper.java
package com.springmvcmybatis.mapper;
import com.springmvcmybatis.po.Customer;
public interface CustomerMapper {
Customer findCustomerById(int id);
}
com.springmvcmybatis.mapper/CustomerMapper.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">
<mapper namespace="com.springmvcmybatis.mapper.CustomerMapper">
<!--根據id查詢客戶信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="customer">
select * from t_customer where id = #{id}
</select>
</mapper>
CUSTOMER.java
package com.springmvcmybatis.po;
/**
*
*/
public class Customer {
private Integer id;
private String username;
private String jobs;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getJobs() {
return jobs;
}
public void setJobs(String jobs) {
this.jobs = jobs;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Customer [id=" + id + ", username=" + username +
", jobs=" + jobs + ", phone=" + phone + "]";
}
}
com.springmvcmybatis.controller/HomeController.java
package com.springmvcmybatis.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springmvcmybatis.mapper.CustomerMapper;
import com.springmvcmybatis.po.Customer;
@Controller
public class HomeController {
@RequestMapping("/home")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvcmybatis-config.xml");
CustomerMapper cm = (CustomerMapper)ac.getBean(CustomerMapper.class);
Customer c = cm.findCustomerById(1);
System.out.println(c.getUsername());
mv.addObject("msg","Hi,我是Home的變量。"+c.getUsername());
return mv;
}
}
WEB-INF/jsp/home.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
hello ,I am home.${msg}
</body>
</html>
Jars 列表:
注意:
1.阿里雲服務器 MySql8遠程功能啓用:在mysql的cmd模式下:新建用戶並授權,代碼:
mysql> CREATE USER 'root1'@'%' IDENTIFIED BY 'password'; (您可以創建一個root1)
mysql> grant all privileges on *.* to 'root1'@'%';
程序連接串需要爲:jdbc:mysql://1.2.3.4:3306/javadb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
2.在測試類中一般這樣寫:
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvcmybatis-config.xml");
CustomerMapper cm = (CustomerMapper)ac.getBean(CustomerMapper.class);
Customer c = cm.findCustomerById(1);
以獲得數據庫數據,但正式中應這樣:先寫一個Util,再在config.xml中配置一下即可。
package com.springmvcmybatis.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
//import org.springframework.stereotype.Component;
//@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
}
配置:<bean id="springContextUtil" class="com.springmvcmybatis.SpringContextUtil" scope="singleton"></bean>
最後在Controller中使用時:
CustomerMapper cm = SpringContextUtil.getBean("CustomerMapper");
Customer c = cm.findCustomerById(1);
3.在name-config.xml中寫上 <context:component-scan base-package="com.springmvcmybatis"></context:component-scan>
後,即不用再單個寫有註解的Controller的bean,會自動識別。
4.SSM中css , js 等靜態文件配置方法:
a)將css , js等文件夾放到WebContent目錄下。
b)在name-servlet.xml中配置:
<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/demo/" mapping="/demo/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
5. jsp包含文件中數據傳遞方法:在包含文件中寫:
<jsp:include page="/WEB-INF/jsp/control/header.jsp" flush="true">
<jsp:param value="0" name="id"/>
</jsp:include>
被包含文件中取值方法 : ${param.id} 或 <% String id = request.getParameter("id")%>
6.使用 mybatis pagehelper插件做分頁:參考:https://blog.csdn.net/m0_38105115/article/details/88542059
先下載:https://github.com/pagehelper/Mybatis-PageHelper
和 jsqlparser 放到libs下。
然後在 edu-config.xml中的<bean id="sqlSessionFactory" > 中加入:
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
</bean>
</array>
</property>
然後是代碼
public interface RoleMapper {
Role getById(int id);
Page<Role> getList();
}
<select id="getList" resultType="role">
select * from role
</select>
SERVICE:
public interface RoleService {
Role getById(int id);
Page<Role> getList(int page,int size);
}
@Service("roleService")
class RoleServiceImpl implements RoleService {
RoleMapper rm ;
@Override
public Role getById(int id) {
rm = SpringContextUtil.getBean("roleMapper");
Role r = rm.getById(id);
return r;
}
@Override
public Page<Role> getList(int page,int size){
rm = SpringContextUtil.getBean("roleMapper");
PageHelper.startPage(page, size);
return rm.getList();
}
}
Controller:
public String list(int page,int size,ModelMap model) {
Page<Role> roleInfo = rs.getList(page, size);
List<Role> roleList = roleInfo.getResult();
long count = roleInfo.getTotal();
for(Role r:roleList) {
System.out.println("R:"+r.getName());
}