Spring+SpringMVC+MyBatis實現資料庫連線的登入功能
阿新 • • 發佈:2018-12-25
在使用SSM框架實現連線資料的登入功能時,
第一步首先匯入相應的jar包,然後配置web.xml檔案
第二步,配置SpringMVC層配置檔案servlet-mvc.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" 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>SSM</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- Spring的配置資訊 --> <!-- 通過全域性上下文引數來載入Spring配置檔案 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 監聽器:通過監聽器讓Spring執行起來 --> <!-- 給Spring配置一個監聽器,讓Spring運作起來 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- SpringMVC的配置資訊 --> <!-- 通過servlet標籤配置dispatcherServlet --> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 載入SpringMVC配置檔案 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:servlet-mvc.xml</param-value> </init-param> <!-- 容器啟動就載入這個servlet,第一個先要被執行 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 中文亂碼解決 --> <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> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
然後配置連線資料的DAO層的配置檔案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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 使用註解的包,包括子集 --> <context:component-scan base-package="com.jredu.controller" /> <!-- 新增資料轉換的註解驅動 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> <!-- 檢視解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp"></property> </bean> <!-- 上傳元件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 設定上傳的編碼格式 --> <property name="defaultEncoding" value="utf-8"/> <!-- 設定最大上傳大小 --> <property name="maxUploadSize" value="5242880"/> </bean> </beans>
第三步,編寫實體類User.java<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.jredu.dao" /> <context:component-scan base-package="com.jredu.service" /> <context:component-scan base-package="com.jredu.entity"/> <!-- 引入配置檔案,可以使用${}語法,location:指定讀取檔案的路徑 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置資料來源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" p:initialPoolSize="${jdbc.initialSize}" p:maxPoolSize="${jdbc.maxActive}"/> <!-- 配置mybatis的sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mappers.xml檔案 --> <property name="mapperLocations" value="classpath:mybatis/mappers/*.xml"></property> <!-- mybatis配置檔案 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> </bean> <!-- DAO介面所在包名,Spring會自動查詢其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jredu.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事務通知屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 定義事務傳播屬性 --> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!-- 配置事務切面 --> <aop:config> <aop:pointcut id="serviceOperation" expression="execution(* com.jredu.service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config> <!-- 異常統一處理 --> <!-- <bean id="exceptionResolver" class="com.jredu.util.HandlerException"/> --> </beans>
public class User {
private int id;
private String name;
private String pwd;
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
在src下建立資料夾mybatis,並編寫配置檔案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.jredu.entity"/>
</typeAliases>
</configuration>
第四步,在控制層(controller)編寫控制類UserController.java
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jredu.entity.User;
import com.jredu.service.UserService;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService service;
@RequestMapping("login.do")
public String login(User user,Map<String,Object> map,HttpSession session){
//業務邏輯層,返回模型資料
User realUser=service.getUser(user);
if (realUser!=null) {
//把使用者資料儲存在session中
session.setAttribute("user", user);
//登入成功
return "success";
}else {
//登入失敗
map.put("error", "賬號或密碼錯誤");
return "login";
}
}
}
呼叫業務處理層service層UserService.java
import com.jredu.entity.User;
/**
* 使用者業務處理
* @author Administrator
*
*/
public interface UserService {
/**
* 將前臺拿到的User到dao層查詢,返回User型別
* @param user
* @return
*/
User getUser(User user);
}
對service層介面實現UserServiceImpl.java,並呼叫dao層import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao dao;
@Override
public User getUser(User user) {
// TODO Auto-generated method stub
//呼叫dao層查詢結果
return dao.selectByCondition(user);
}
}
第五步,dao層UserDao.java
import com.jredu.entity.User;
public interface UserDao {
User selectByCondition(User user);
}
在剛建的資料夾mybatis下建立資料夾mybatis.mappers,並編寫對資料庫的操作的配置檔案UserDao.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">
<!-- namespace對應介面地址 -->
<mapper namespace="com.jredu.dao.UsersDao">
<select id="selectByCondition" parameterType="User" resultType="User">
select * from users where name=#{name} and pwd=#{pwd}
</select>
</mapper>
一個完整的運用SSM框架的登入操作就分為這幾步,
還有一個重要的點是,連線資料庫(Oracle)的檔案jdbc.properties,放在src下
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
jdbc.username=mybatis
jdbc.password=12345
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570
jdbc.initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570
jdbc.maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2
jdbc.maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2
jdbc.minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4
jdbc.maxWait=60000