Spring+SpringMVC+Mybatis 兩種入門級基本配置及登錄實例

ssm入門級配置

    博主是一隻接觸不久JAVA WEB開發的萌新,在最初搭建ssm框架時也參照了好多論壇內大神n年前的博文,可能是由於基礎並不算太紮實,這些博文內的內容弄的我一愣一愣的,在歷經諸多磨難搭建成功之後趕緊開通博客,用於記錄。

博主項目目錄


一、持久層

ssm框架持久層是使用Mybatis框架進行開發的

這邊涉及到一個mybatis與Spring整合的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: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.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">  
  <!-- 自動掃描 -->
<context:component-scan base-package="com.grs" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:resources/jdbc.properties" />
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>


<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/grs/mapper/*.xml"></property>
</bean>


<!-- DAO接口所在包名,Spring會自動查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.grs.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>
</beans>  


配置文件配置完了,就可以寫mapper.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:命名空間,作用就是對sql進行分類化管理,sql隔離  
        注意:在使用mapper的代理方法開發時,有重要作用    
                namespace命名必須與Mapper接口的路徑相同 -->  
<mapper namespace="com.grs.dao.userMapper">  
      
    <!-- 按照id查詢 -->  
    <!-- 將sql語句封裝到MapperStatement中,所以也將id 成爲statement的Id -->  
    <!-- paramerType:指定輸入參數的類型。  
            #{ } :代表佔位符。  
            #{id }:表示接受輸入參數id的值,如果輸入參數是簡單類型,#{ }中的參數名可以任意  
                     ,可以是value或是其他值  
                       
            resultType:表示sql輸出結果的所映射的Javabean的對象類型,resultType指定將單條記錄映射成Java對像-->  
    <select id="login" parameterType="com.grs.domain.TUser"  resultType="int">
    select count(*) from t_user where username = #{username} and password = #{password}
    </select>  

    這個簡單的登錄demo非常簡單,就是在你數據庫中t_user數據表中查詢username與password的數據總數,查到了返回count(*)=1,然後在service層中去判斷是否等於1,等於ok,你登錄成功了,不等於(管他大不大於1...)登陸失敗。

二、dao層

dao層其實tm的就是一個接口,只不過這個接口略微有點特殊,有一些規則需要記住:

     1.xxxMapper.xml中namespace路徑與xxxmapper接口路徑相同

     2.xxxmapper接口中的方法名,與xxxMapper.xml中對應statement的id相同

     3.xxxmapper接口中方法的輸入參數類型和xxxmapper.xml中定義的對應sql的ParameterType的類型相同

     4.xxxmapper接口中方法的返回值類型和xxxmapper.xml中定義的對應sql的ResultType的類型相同

   這就OK了

代碼如下:

public interface userMapper {

  public Integer login(TUser user);

}

三、service層

service層較爲複雜,也是所有業務邏輯實現的地方,較之dao層不同的地方,service層需要按照相應的業務邏輯進行設計


public interface userService {

        //登錄
Map<String,Object> login(TUser user);

}

實現類:

@Service
@Transactional
public class userServiceImpl implements userService {

        @Resource
private userMapper usermapper;


        @Override
public Map<String,Object> login(TUser user) {

              boolean flag = false;

              int i = usermapper.login(user);

              if(i==1){

                flag = true;

               }

             Map<String,Object> map = new HashMap<>();

             map.put("flag",flag);

              return map;

}

}

到這就可以了。


四、action(controller)層

       控制器接受用戶的輸入並調用模型和視圖去完成用戶的需求。當web頁面中的超鏈接和發送HTML時,控制器本身不輸出任何東西和做任何處理。它只接受請求並決定調用哪個模型構件去處理請求,然後決定用哪個視圖來顯示模型處理返回的數據。

       也就是說這貨不去處理業務邏輯,只是負責和前端頁面進行交互。

就拿登錄舉例吧:

/**

*@Controller 用於標記在一個類上,使用它標記的類就是一個SpringMVC Controller 對象。分發處理器將會掃描使用了該註解的類的方法

*也就是說SpringMVC通過這個註解才知道你下面的這個userAction類是個控制器

*/

@Controller
public class userAction {

@Autowired
private userService userservice; 

/** 
     * 登陸
     */ 

     //@ResponseBody這個東西表示下面這個controller是以json字符串格式返回的
@ResponseBody

    //@RequestMapping這個東西是一個用來處理請求地址映射的註解
@RequestMapping(value="login.do",method=RequestMethod.POST)

public Map<String,Object>login(TUser user){
    Map<String,Object> map = userservice.login(user);

            reurn map;
    }
}

完事。


其他的一些配置文件及bean類:

public class TUser implements Serializable{


private static final long serialVersionUID = 1L;


private Integer id;
private String username;

       //transient反序列化
private transient String password;

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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}


jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ghtl
username=root
password=root

------------------------------------------------只是一條分割線---------------------------------------------------------

SpringMVC.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">  
    <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
<context:component-scan base-package="com.grs.action" />
<!--避免IE執行AJAX時,返回JSON出現下載文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- JSON轉換器 -->
</list>
</property>
</bean>
<!-- 定義跳轉的文件的前後綴 ,視圖模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裏的配置我的理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包 -->
<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默認編碼 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />  
        <!-- 內存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
    </bean> 
    <!-- 在實際開發中通常都需配置 mvc:annotation-driven標籤,這個標籤是開啓註解 -->  
        <mvc:annotation-driven></mvc:annotation-driven>  
</beans>  

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" 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>ghtl003</display-name>
<!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:resources/spring-mybatis.xml</param-value>  
    </context-param>  
    <!-- 編碼過濾器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <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>  
    <!-- Spring監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring內存溢出監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
  
    <!-- Spring MVC servlet -->  
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:resources/spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此處可以可以配置成*.do,對應struts的後綴習慣 -->  
        <url-pattern>*.do</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.html</welcome-file>  
    </welcome-file-list>  
</web-app>

登錄頁面:

login.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
</head>


<body>
<form action="login.do" method="post">
<p>&nbsp;</p>
<p>&nbsp;</p>
<table width="531" height="194" border="1" align="center">
  <tr>
    <td width="94">用戶名</td>
    <td width="421"><input type="text" name="username" /></td>
  </tr>
  <tr>
    <td>密碼</td>
    <td><input type="password" name="password" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="Submit" value="提交" /></td>
  </tr>
</table>
</form>
</body>
</html>

相關的jar包的話。。。我也記不大清了,自己去網上找去吧。

學無止境,多練爲真。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章