国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

論壇系統(tǒng)(Spring+SpringMVC+Mybatis)

2019-11-08 01:47:29
字體:
供稿:網(wǎng)友

論壇系統(tǒng)(SPRing+SpringMVC+Mybatis)

接著上一篇文章介紹的論壇系統(tǒng)——基于Spring+Struts1+Hibernate實(shí)現(xiàn),本文章要介紹的是基于Spring+SpringMVC+Mybatis實(shí)現(xiàn)的論壇系統(tǒng)。之所以心血來潮把框架換了,是因?yàn)閯倢W(xué)完SpringMVC和Mybatis,只有幾個SSM的例程,得不到做一個系統(tǒng)的實(shí)踐經(jīng)驗(yàn),所以就嘗試換了框架,經(jīng)過幾天的努力,最后把功能都還原了,整個小項(xiàng)目從創(chuàng)建到完成,還是挺有點(diǎn)成就感的,畢竟是自己把代碼一個個敲出來,把功能一步步完成。目前,很多公司都使用SSM組合框架,而SSM也得到了越來越多web開發(fā)者的追捧,所以很有必要學(xué)習(xí)。個人覺得SpringMVC比Struts好得多,在以后的開發(fā)中,我更傾向于SpringMVC,畢竟是同一家公司的產(chǎn)品,SpringMVC比Struts更容易契合Spring技術(shù);而Hibernate和Mybatis各有其優(yōu)點(diǎn),可以根據(jù)系統(tǒng)的需求而選擇Hibernate還是Mybatis。對兩者做一些小總結(jié):Hibernate對數(shù)據(jù)庫結(jié)構(gòu)提供了較為完整的封裝,只需定義好POJO 到數(shù)據(jù)庫表的映射關(guān)系,即可通過Hibernate 提供的方法完成持久層操作;而Mybatis側(cè)重于POJO 與SQL之間的映射關(guān)系,然后通過映射配置文件,將SQL所需的參數(shù),以及返回的結(jié)果字段映射到指定POJO。Mybatis優(yōu)勢:MyBatis可以進(jìn)行更為細(xì)致的SQL優(yōu)化,可以減少查詢字段MyBatis容易掌握,而Hibernate門檻較高Hibernate優(yōu)勢:Hibernate的DAO層開發(fā)比MyBatis簡單,Mybatis需要維護(hù)SQL和結(jié)果映射Hibernate對對象的維護(hù)和緩存要比MyBatis好,對增刪改查的對象的維護(hù)要方便。(我最大的感悟是Mybatis只提供級聯(lián)查詢,而不能級聯(lián)插入、更新)Hibernate數(shù)據(jù)庫移植性很好,MyBatis的數(shù)據(jù)庫移植性不好,不同的數(shù)據(jù)庫需要寫不同SQL。Hibernate有更好的二級緩存機(jī)制,可以使用第三方緩存。MyBatis本身提供的緩存機(jī)制不佳,更新操作不能指定刷新指定記錄,會清空整個表,但是也可以使用第三方緩存。當(dāng)然,Hibernate的缺點(diǎn)也很明顯,如果涉及到多張關(guān)聯(lián)表的調(diào)用時:多表關(guān)聯(lián)等比較復(fù)雜,使用的成本并不低效率比較低,在大型項(xiàng)目中很少使用,因?yàn)閟ql都是自動生成,不太好人工優(yōu)化。說點(diǎn)閑話,開始有點(diǎn)喜歡寫一下博客,記錄一下自己所學(xué)的知識還是挺好的,嗯,得堅持!!!!奮斗回到正事!該基于SSM的系統(tǒng)直接用的是上一篇文章的數(shù)據(jù)庫,懶得創(chuàng)建了。整個工程目錄以及數(shù)據(jù)表如下:         效果圖我就不貼出來了,界面跟上一篇貼出來的都一樣,我只是把框架給換了,在jsp中把所有Struts的標(biāo)簽都換成spring提供的form標(biāo)簽!

1、使用Mybatis-Generator自動生成DAO、Model、Mapping相關(guān)文件

Mybatis屬于半自動ORM,在使用這個框架中,工作量最大的就是書寫Mapping的映射文件,由于手動書寫很容易出錯,我們可以利用Mybatis-Generator來幫我們自動生成文件。(說到底是自己懶,哈哈)盡管是這樣,確實(shí)是會減少一點(diǎn)額外的工作。但我通常都會把生成的xxExample.java文件刪掉,并對xxMapper.java、xxMapper.xml文件進(jìn)行適當(dāng)?shù)膭h減,留下幾個有用的,在此基礎(chǔ)上再添加自己的操作語句。generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" ><generatorConfiguration>	<classPathEntry		location="D:/software/MySQL-connector/mysql-connector-java-5.1.39-bin.jar" />			<context id="context">		<!-- 為了防止生成的代碼中有很多注釋,比較難看,加入下面的配置控制 -->		<commentGenerator>			<property name="suppressAllComments" value="true" />			<property name="suppressDate" value="true" />		</commentGenerator>				<jdbcConnection driverClass="com.mysql.jdbc.Driver"			connectionURL="jdbc:mysql://localhost:3306/forum" userId="root"			passWord="5845201314" />		<!-- 生成模型的包名和位置 --> 		<javaModelGenerator targetPackage="model" targetProject="Forum_SSM" />		<!-- 生成的映射文件包名和位置 -->		<sqlMapGenerator targetPackage="mapper" targetProject="Forum_SSM" />		<!-- 生成DAO的包名和位置 --> 		<javaClientGenerator targetPackage="mapper" targetProject="Forum_SSM" type="XMLMAPPER" />		<!-- 數(shù)據(jù)庫名以及對應(yīng)的表 -->		<table schema="forum" tableName="person">		</table>	</context></generatorConfiguration>

2、相關(guān)配置文件

2.1、web.xml

這里主要配置了Spring的DispatcherServlet,讓它攔截所有以.do結(jié)尾的請求,還配置了一個字符過濾器,防止亂碼問題(個人習(xí)慣了,不管有沒有用,加上去再說)
<?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"	version="3.0">	<display-name>Forum_SSM</display-name>	<!-- spring配置文件加載 -->	<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>	<!-- mvc控制器 -->	<servlet>		<servlet-name>spring</servlet-name>		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>		<init-param>			<param-name>contextConfigLocation</param-name>			<param-value>classpath:mvc-config.xml</param-value>		</init-param>		<load-on-startup>1</load-on-startup>	</servlet>	<servlet-mapping>		<servlet-name>spring</servlet-name>		<url-pattern>*.do</url-pattern>	</servlet-mapping>	<!-- 字符編碼過濾器 -->	<filter>		<filter-name>CharacterEncodingFilter</filter-name>		<filter-class>filter.CharacterEncodingFilter</filter-class>		<init-param>			<param-name>characterEncoding</param-name>			<param-value>UTF-8</param-value>		</init-param>		<init-param>			<param-name>enabled</param-name>			<param-value>true</param-value>		</init-param>	</filter>	<filter-mapping>		<filter-name>CharacterEncodingFilter</filter-name>		<url-pattern>/*</url-pattern>	</filter-mapping></web-app>

2.2、applicationContext.xml

component-scan標(biāo)簽?zāi)J(rèn)情況下自動掃描指定路徑下的包(含所有子包),將帶有@Component、@Repository、@Service、@Controller標(biāo)簽的類自動注冊到spring容器。對標(biāo)記了@Required、@Autowired等注解的類進(jìn)行對應(yīng)的操作使注解生效。

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"	xmlns:context="http://www.springframework.org/schema/context"	xsi:schemaLocation="http://www.springframework.org/schema/beans 	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd	http://www.springframework.org/schema/tx       http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 	http://www.springframework.org/schema/aop	http://www.springframework.org/schema/aop/spring-aop-3.1.xsd	http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.1.xsd">	<bean id="exceptionHandler" class="exception.ForumExceptionHandler" />	<!-- 掃描DAO和SERVICE包,controller包在springmvc中掃描 -->	<context:component-scan base-package="ServiceImpl,DAOImpl" />	<bean id="dataSource"		class="org.springframework.jdbc.datasource.DriverManagerDataSource">	<!-- 定義數(shù)據(jù)源 -->		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>		<property name="url"			value="jdbc:mysql://localhost:3306/forum?characterEncoding=UTF-8"></property>		<property name="username" value="root"></property>		<property name="password" value="5845201314"></property>	</bean>	<!-- 會話工廠 :session 工廠可以使用 SqlSessionFactoryBuilder 來創(chuàng)建。而在 MyBatis-spring 		中,則使用 SqlSessionFactoryBean 來替代 -->	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">		<property name="dataSource" ref="dataSource" />		<!-- 當(dāng)SqlSessionFactoryBean提供的配置不能滿足使用時,你可以使用mybatis-config.xml配置文件配置其他屬性 -->		<property name="configLocation" value="classpath:mybatis-config.xml"></property>		<property name="mapperLocations" value="classpath:mapper/*.xml"></property>	</bean>	<!-- 事務(wù)管理器 -->	<bean id="transactionManager"		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">		<property name="dataSource" ref="dataSource" />	</bean>	<!-- 配置事務(wù)的傳播特性 -->	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">		<!-- 指定具體需要攔截的方法 -->		<tx:attributes>			<tx:method name="insert*" propagation="REQUIRED"></tx:method>			<tx:method name="delete*" propagation="REQUIRED"></tx:method>			<tx:method name="update*" propagation="REQUIRED"></tx:method>			<tx:method name="select*" propagation="SUPPORTS"></tx:method>		</tx:attributes>	</tx:advice>	<!-- 配置哪些類的哪些方法參與事務(wù) -->	<aop:config>		<aop:pointcut id="serviceCut" expression="execution(public * Service.*.*(..))" />		<aop:advisor pointcut-ref="serviceCut" advice-ref="transactionAdvice" />	</aop:config>	<!-- spring和mybatis的整合 -->	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">		<property name="basePackage" value="mapper" />	</bean></beans>

2.3、SpringMVC配置文件——mvc-config.xml

該配置文件主要服務(wù)于SpringMVC流程。在mvc-config.xml中,最重要的工作是控制轉(zhuǎn)發(fā),這個配置文件中做了最簡單的轉(zhuǎn)發(fā)操作,只能轉(zhuǎn)發(fā)頁面,如果想要通過Ajax實(shí)現(xiàn)轉(zhuǎn)發(fā)數(shù)據(jù),那么需要重寫ViewResolver來實(shí)現(xiàn)這個功能。把jsp文件放在WEB-INF下,這樣就只能通過Controller進(jìn)行訪問。
<?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-3.1.xsd	http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">	<!-- 掃描controller包 -->    <context:component-scan base-package="Controller"></context:component-scan>        <!-- 完成請求和注解POJO的映射 -->    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>	<!-- 配置JSP前綴后綴 -->	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">		<property name="prefix">			<value>/WEB-INF/jsp/</value>		</property>		<property name="suffix">			<value>.jsp</value>		</property>	</bean>		<!--攔截器 -->    <mvc:interceptors>    <!--多個攔截器,順序執(zhí)行 -->        <mvc:interceptor>            <mvc:mapping path="/**"/>            <bean class="Interceptor.LoginInterceptor"></bean>        </mvc:interceptor>    </mvc:interceptors>		<!-- 支持文件上傳 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    </bean></beans>

2.4、mybatis-config.xml

在mybatis-config.xml中不需要額外的配置,它只是個空文件。

3、用戶模塊

3.1、Person.java

mybatis的實(shí)體類和hibernate實(shí)體類的不同是mybatis的實(shí)體類不需要加載到spring的beanFactory中,而是通過操作數(shù)據(jù)庫的mapper來持久化數(shù)據(jù)。
package model;public class Person {    private Integer id;    private Date datecreated;    private Boolean deleted;    private Integer version;    private String account;    private String birthday;    private Date datelastactived;    private String email;    private String ipcreated;    private String iplastactived;    private String name;    private String password;    private String sex;	//省略setter和getter方法}

3.2、PersonMapper映射接口

對Mybatis-Generator生成的personMapper.java進(jìn)行刪減,只留下在該系統(tǒng)中可能用到的,并添加需要用到的操作方法。
package mapper;public interface PersonMapper {	Person getPerson(Person person);	Person selectByAccount(String account);	List<Board> selectBoardByPersonId(int id);	List<Person> selectAll();	int deleteByBoardId(Integer id);	int insertBoardAdministrator(@Param("boardId") int boardId, @Param("personId") int personId);	/*以上為自己實(shí)現(xiàn)的方法,保留了下面可能用到的方法*/	int deleteByPrimaryKey(Integer id);	int insert(Person record);	int insertSelective(Person record);	Person selectByPrimaryKey(Integer id);	int updateByPrimaryKeySelective(Person record);	int updateByPrimaryKey(Person record);}

3.3、PersonMapper.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="mapper.PersonMapper" >  <resultMap id="BaseResultMap" type="model.Person" >    <id column="id" property="id" jdbcType="INTEGER" />    <result column="dateCreated" property="datecreated" jdbcType="TIMESTAMP" />    <result column="deleted" property="deleted" jdbcType="BIT" />    <result column="version" property="version" jdbcType="INTEGER" />    <result column="account" property="account" jdbcType="VARCHAR" />    <result column="birthday" property="birthday" jdbcType="VARCHAR" />    <result column="dateLastActived" property="datelastactived" jdbcType="TIMESTAMP" />    <result column="email" property="email" jdbcType="VARCHAR" />    <result column="ipCreated" property="ipcreated" jdbcType="VARCHAR" />    <result column="ipLastActived" property="iplastactived" jdbcType="VARCHAR" />    <result column="name" property="name" jdbcType="VARCHAR" />    <result column="password" property="password" jdbcType="VARCHAR" />    <result column="sex" property="sex" jdbcType="VARCHAR" />  </resultMap>  <resultMap id="BoardResultMap" type="model.Board" extends="mapper.BoardMapper.BaseResultMap">  </resultMap>    <sql id="Base_Column_List" >    id, dateCreated, deleted, version, account, birthday, dateLastActived, email, ipCreated,     ipLastActived, name, password, sex  </sql>  <sql id="Board_Column_List" >    id, dateCreated, deleted, version, description, name, replyCount, threadCount, category_id,     last_reply_id, last_thread_id  </sql>    <select id="getPerson" resultMap="BaseResultMap" parameterType="model.Person" >    select     <include refid="Base_Column_List" />    from person    where account=#{account,jdbcType=VARCHAR} and password=#{password,jdbcType=VARCHAR}  </select>    <select id="selectByAccount" resultMap="BaseResultMap" parameterType="String" >    select     <include refid="Base_Column_List" />    from person    where account = #{account,jdbcType=VARCHAR}  </select>    <select id="selectBoardByPersonId" resultMap="BoardResultMap" parameterType="java.lang.Integer" >    select     <include refid="Board_Column_List" />    from board    where id in (select board_id from board_administrator where person_id = #{person_id,jdbcType=INTEGER})  </select>    <select id="findPersonByBoardId" resultMap="BaseResultMap" parameterType="java.lang.Integer" >    select     <include refid="Base_Column_List" />    from person    where id in (select person_id from board_administrator where board_id = #{board_id,jdbcType=INTEGER})  </select>    <select id="selectAll" resultMap="BaseResultMap" >    select     <include refid="Base_Column_List" />    from person    where deleted=false  </select>    <delete id="deleteByBoardId" parameterType="java.lang.Integer" >	delete from board_administrator	where board_id = #{boardId,jdbcType=INTEGER}  </delete>    <insert id="insertBoardAdministrator">  	insert into board_administrator  	values (#{boardId}, #{personId})  </insert>    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >    select     <include refid="Base_Column_List" />    from person    where id = #{id,jdbcType=INTEGER}  </select>  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >    delete from person    where id = #{id,jdbcType=INTEGER}  </delete>  <insert id="insert" parameterType="model.Person" >    insert into person (id, dateCreated, deleted,       version, account, birthday,       dateLastActived, email, ipCreated,       ipLastActived, name, password,       sex)    values (#{id,jdbcType=INTEGER}, #{datecreated,jdbcType=TIMESTAMP}, #{deleted,jdbcType=BIT},       #{version,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{birthday,jdbcType=VARCHAR},       #{datelastactived,jdbcType=TIMESTAMP}, #{email,jdbcType=VARCHAR}, #{ipcreated,jdbcType=VARCHAR},       #{iplastactived,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},       #{sex,jdbcType=VARCHAR})  </insert>  <insert id="insertSelective" parameterType="model.Person" >    insert into person    <trim prefix="(" suffix=")" suffixOverrides="," >      <if test="id != null" >        id,      </if>      <if test="datecreated != null" >        dateCreated,      </if>      <if test="deleted != null" >        deleted,      </if>      <if test="version != null" >        version,      </if>      <if test="account != null" >        account,      </if>      <if test="birthday != null" >        birthday,      </if>      <if test="datelastactived != null" >        dateLastActived,      </if>      <if test="email != null" >        email,      </if>      <if test="ipcreated != null" >        ipCreated,      </if>      <if test="iplastactived != null" >        ipLastActived,      </if>      <if test="name != null" >        name,      </if>      <if test="password != null" >        password,      </if>      <if test="sex != null" >        sex,      </if>    </trim>    <trim prefix="values (" suffix=")" suffixOverrides="," >      <if test="id != null" >        #{id,jdbcType=INTEGER},      </if>      <if test="datecreated != null" >        #{datecreated,jdbcType=TIMESTAMP},      </if>      <if test="deleted != null" >        #{deleted,jdbcType=BIT},      </if>      <if test="version != null" >        #{version,jdbcType=INTEGER},      </if>      <if test="account != null" >        #{account,jdbcType=VARCHAR},      </if>      <if test="birthday != null" >        #{birthday,jdbcType=VARCHAR},      </if>      <if test="datelastactived != null" >        #{datelastactived,jdbcType=TIMESTAMP},      </if>      <if test="email != null" >        #{email,jdbcType=VARCHAR},      </if>      <if test="ipcreated != null" >        #{ipcreated,jdbcType=VARCHAR},      </if>      <if test="iplastactived != null" >        #{iplastactived,jdbcType=VARCHAR},      </if>      <if test="name != null" >        #{name,jdbcType=VARCHAR},      </if>      <if test="password != null" >        #{password,jdbcType=VARCHAR},      </if>      <if test="sex != null" >        #{sex,jdbcType=VARCHAR},      </if>    </trim>  </insert>  <update id="updateByPrimaryKeySelective" parameterType="model.Person" >    update person    <set >      <if test="datecreated != null" >        dateCreated = #{datecreated,jdbcType=TIMESTAMP},      </if>      <if test="deleted != null" >        deleted = #{deleted,jdbcType=BIT},      </if>      <if test="version != null" >        version = #{version,jdbcType=INTEGER},      </if>      <if test="account != null" >        account = #{account,jdbcType=VARCHAR},      </if>      <if test="birthday != null" >        birthday = #{birthday,jdbcType=VARCHAR},      </if>      <if test="datelastactived != null" >        dateLastActived = #{datelastactived,jdbcType=TIMESTAMP},      </if>      <if test="email != null" >        email = #{email,jdbcType=VARCHAR},      </if>      <if test="ipcreated != null" >        ipCreated = #{ipcreated,jdbcType=VARCHAR},      </if>      <if test="iplastactived != null" >        ipLastActived = #{iplastactived,jdbcType=VARCHAR},      </if>      <if test="name != null" >        name = #{name,jdbcType=VARCHAR},      </if>      <if test="password != null" >        password = #{password,jdbcType=VARCHAR},      </if>      <if test="sex != null" >        sex = #{sex,jdbcType=VARCHAR},      </if>    </set>    where id = #{id,jdbcType=INTEGER}  </update>  <update id="updateByPrimaryKey" parameterType="model.Person" >    update person    set dateCreated = #{datecreated,jdbcType=TIMESTAMP},      deleted = #{deleted,jdbcType=BIT},      version = #{version,jdbcType=INTEGER},      account = #{account,jdbcType=VARCHAR},      birthday = #{birthday,jdbcType=VARCHAR},      dateLastActived = #{datelastactived,jdbcType=TIMESTAMP},      email = #{email,jdbcType=VARCHAR},      ipCreated = #{ipcreated,jdbcType=VARCHAR},      ipLastActived = #{iplastactived,jdbcType=VARCHAR},      name = #{name,jdbcType=VARCHAR},      password = #{password,jdbcType=VARCHAR},      sex = #{sex,jdbcType=VARCHAR}    where id = #{id,jdbcType=INTEGER}  </update></mapper>

3.4、PersonDAO層及其實(shí)現(xiàn)

本系統(tǒng)繼續(xù)沿用了DAO層和Service層的編程習(xí)慣。
package DAO;public interface PersonDAO {	public void save(Person person);	public int insert(Person person);	public Person selectById(int id);	public List<Board> selectBoardByPersonId(int id);	public List<Person> selectAll();	public Person findPersonByAccount(String account);	public Person getPerson(Person person);	public int deleteByBoardId(int id);	public int insertBoardAdministrator(int boardId, int personId);}
package DAOImpl;@Repositorypublic class PersonDAOImpl implements PersonDAO{	@Autowired	private PersonMapper personMapper;	@Override	public Person findPersonByAccount(String account) {		return personMapper.selectByAccount(account);	}	@Override	public Person getPerson(Person person) {		return personMapper.getPerson(person);	}	@Override	public void save(Person person) {		personMapper.updateByPrimaryKeySelective(person);	}	@Override	public int insert(Person person) {		return personMapper.insertSelective(person);	}	@Override	public Person selectById(int id) {		return personMapper.selectByPrimaryKey(id);	}	@Override	public List<Board> selectBoardByPersonId(int id) {		return personMapper.selectBoardByPersonId(id);	}	@Override	public List<Person> selectAll() {		return personMapper.selectAll();	}	@Override	public int deleteByBoardId(int id) {		return personMapper.deleteByBoardId(id);	}	@Override	public int insertBoardAdministrator(int boardId, int personId) {		return personMapper.insertBoardAdministrator(boardId, personId);	}}

3.5、PersonService層及其實(shí)現(xiàn)

package Service;public interface PersonService {		public void save(Person person);	public int insert(Person person);	public Person selectById(int id);	public List<Person> selectAll();	public List<Board> selectBoardByPersonId(int id);	public Person findPersonByAccount(String account);	public Person getPerson(Person person);	public int deleteByBoardId(int id);	public int insertBoardAdministrator(int boardId, int personId);}
package ServiceImpl;@Servicepublic class PersonServiceImpl implements PersonService{	@Autowired	private PersonDAO personDAO;	@Override	public Person findPersonByAccount(String account) {		return personDAO.findPersonByAccount(account);	}	@Override	public Person getPerson(Person person) {		Person newper=new Person();		newper.setAccount(person.getAccount());		newper.setPassword(md5Util.calc(person.getPassword()));		return personDAO.getPerson(newper);	}	@Override	public void save(Person person) {		personDAO.save(person);	}	@Override	public int insert(Person person) {		if(findPersonByAccount(person.getAccount())!=null)			throw new RuntimeException("帳號 " + person.getAccount() + " 已經(jīng)存在。");		person.setPassword(MD5Util.calc(person.getPassword()));		return personDAO.insert(person);	}	@Override	public Person selectById(int id) {		return personDAO.selectById(id);	}	@Override	public List<Board> selectBoardByPersonId(int id) {		return personDAO.selectBoardByPersonId(id);	}	@Override	public List<Person> selectAll() {		return personDAO.selectAll();	}	@Override	public int deleteByBoardId(int id) {		return personDAO.deleteByBoardId(id);	}	@Override	public int insertBoardAdministrator(int boardId, int personId) {		return personDAO.insertBoardAdministrator(boardId, personId);	} }

3.6、Person控制器

package Controller;@Controllerpublic class PersonController {	@Autowired	private PersonService personService;		@RequestMapping("person_initAdd.do")	public ModelAndView initAdd(HttpServletRequest request){		request.setAttribute("title", "用戶注冊");		request.setAttribute("person", new Person());		return new ModelAndView("person/addPerson");	}			@RequestMapping("person_add.do")	public ModelAndView add(@ModelAttribute Person person, HttpServletRequest request, HttpServletResponse response){		request.setAttribute("title", "用戶注冊");		person.setIpcreated(request.getRemoteAddr());		person.setIplastactived(request.getRemoteAddr());		person.setDatecreated(new Date());		person.setDatelastactived(new Date());		person.setDeleted(false);		if (person.getAccount() == null|| person.getAccount().trim().length() == 0) {			request.setAttribute("message", "請輸入帳號");			return initAdd(request);		}		if (person.getPassword() == null|| person.getPassword().trim().length() == 0|| !person.getPassword().equals(request.getParameter("password1"))) {			request.setAttribute("message", "密碼不一致");			return initAdd(request);		}		try {			personService.insert(person);//保存到數(shù)據(jù)庫,此時沒有id			PersonUtil.setPersonInf(request, response, personService.findPersonByAccount(person.getAccount()));			request.setAttribute("message", "注冊成功");			return new ModelAndView("person/success");		} catch (Exception e) {			request.setAttribute("message", "注冊失敗,原因:" + e.getMessage());			return initAdd(request);		}	}		@RequestMapping("person_initLogin.do")	public ModelAndView initLogin(HttpServletRequest request){		request.setAttribute("person", new Person());		request.setAttribute("title", "用戶登錄");		return new ModelAndView("person/login");	}		@RequestMapping("person_login.do")	public ModelAndView login(@ModelAttribute Person person,HttpServletRequest request, HttpServletResponse response) throws Exception{		request.setAttribute("title", "用戶登錄");		Person person1=personService.getPerson(person);		if (person1 == null)			throw new AccountException("用戶名密碼錯誤");		PersonUtil.setPersonInf(request, response, person1);		person1.setIplastactived(request.getRemoteAddr());		person1.setDatelastactived(new Date());		personService.save(person1);		request.setAttribute("message", "歡迎回來");		return new ModelAndView("person/success");	}		@RequestMapping("person_logout.do")	public ModelAndView logout(HttpServletRequest request){		request.setAttribute("title", "用戶注銷");		request.getSession(true).setAttribute(PersonUtil.PERSON_INFO, null);		request.setAttribute("person", new Person());		return new ModelAndView("person/login");	}		@RequestMapping("person_view.do")	public ModelAndView view(HttpServletRequest request){		request.setAttribute("title", "查看用戶資料");		int id=Integer.parseInt(request.getParameter("id"));		Person person=personService.selectById(id);		request.setAttribute("person", person);		List<Board> boardList=personService.selectBoardByPersonId(id);		request.setAttribute("boardList", boardList);		return new ModelAndView("person/viewPerson");	}}

4、版面類型模塊

4.1、Category.java

boardList需要自己手動,因?yàn)樗⒉粚儆诒碇械淖侄危壜?lián)查詢時需要用到
package model;public class Category {	private Integer id;	private Date datecreated;	private Boolean deleted;	private Integer version;	private String name;	private List<Board> boardList; //省略setter、getter方法}

4.2、CategoryMapper映射接口

package mapper;public interface CategoryMapper {	List<Category> getList();	Category selectByName(String name);	List<Category> getAll();	/*以上為自己實(shí)現(xiàn)的方法,保留了下面可能用到的方法*/	int deleteByPrimaryKey(Integer id);	int insert(Category record);	int insertSelective(Category record);	Category selectByPrimaryKey(Integer id);	int updateByPrimaryKeySelective(Category record);	int updateByPrimaryKey(Category record);}

4.3、CategoryMapper.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="mapper.CategoryMapper" >  <resultMap id="BaseResultMap" type="model.Category" >    <id column="id" property="id" jdbcType="INTEGER" />    <result column="dateCreated" property="datecreated" jdbcType="TIMESTAMP" />    <result column="deleted" property="deleted" jdbcType="BIT" />    <result column="version" property="version" jdbcType="INTEGER" />    <result column="name" property="name" jdbcType="VARCHAR" />  </resultMap>  <resultMap id="Cate_BoardResultMap" type="model.Category" extends="BaseResultMap">    <collection property="boardList" column="id" select="mapper.BoardMapper.findBoardByCategoryId"></collection>  </resultMap>    <sql id="Base_Column_List" >    id, dateCreated, deleted, version, name  </sql>  <select id="getList" resultMap="Cate_BoardResultMap" >    select     <include refid="Base_Column_List" />    from category    where deleted = false  </select>    <select id="selectByName" resultMap="BaseResultMap" parameterType="String" >    select     <include refid="Base_Column_List" />    from category    where name = #{name,jdbcType=VARCHAR}  </select>    <select id="getAll" resultMap="BaseResultMap" >    select     <include refid="Base_Column_List" />    from category    where deleted = false  </select>    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >    select     <include refid="Base_Column_List" />    from category    where id = #{id,jdbcType=INTEGER}  </select>  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >    delete from category    where id = #{id,jdbcType=INTEGER}  </delete>  <insert id="insert" parameterType="model.Category" >    insert into category (id, dateCreated, deleted,       version, name)    values (#{id,jdbcType=INTEGER}, #{datecreated,jdbcType=TIMESTAMP}, #{deleted,jdbcType=BIT},       #{version,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})  </insert>  <insert id="insertSelective" parameterType="model.Category" >    insert into category    <trim prefix="(" suffix=")" suffixOverrides="," >      <if test="id != null" >        id,      </if>      <if test="datecreated != null" >        dateCreated,      </if>      <if test="deleted != null" >        deleted,      </if>      <if test="version != null" >        version,      </if>      <if test="name != null" >        name,      </if>    </trim>    <trim prefix="values (" suffix=")" suffixOverrides="," >      <if test="id != null" >        #{id,jdbcType=INTEGER},      </if>      <if test="datecreated != null" >        #{datecreated,jdbcType=TIMESTAMP},      </if>      <if test="deleted != null" >        #{deleted,jdbcType=BIT},      </if>      <if test="version != null" >        #{version,jdbcType=INTEGER},      </if>      <if test="name != null" >        #{name,jdbcType=VARCHAR},      </if>    </trim>  </insert>  <update id="updateByPrimaryKeySelective" parameterType="model.Category" >    update category    <set >      <if test="datecreated != null" >        dateCreated = #{datecreated,jdbcType=TIMESTAMP},      </if>      <if test="deleted != null" >        deleted = #{deleted,jdbcType=BIT},      </if>      <if test="version != null" >        version = #{version,jdbcType=INTEGER},      </if>      <if test="name != null" >        name = #{name,jdbcType=VARCHAR},      </if>    </set>    where id = #{id,jdbcType=INTEGER}  </update>  <update id="updateByPrimaryKey" parameterType="model.Category" >    update category    set dateCreated = #{datecreated,jdbcType=TIMESTAMP},      deleted = #{deleted,jdbcType=BIT},      version = #{version,jdbcType=INTEGER},      name = #{name,jdbcType=VARCHAR}    where id = #{id,jdbcType=INTEGER}  </update></mapper>

4.4、CategoryDAO層及其實(shí)現(xiàn)

package DAO;public interface CategoryDAO {	public List<Category> getList();	public int create(Category category);		public Category selectByName(String name);		public List<Category> getAll();}
package DAOImpl;@Repositorypublic class CategoryDAOImpl implements CategoryDAO{	@Autowired	private CategoryMapper categoryMapper;	@Override	public List<Category> getList() {		return categoryMapper.getList();	}	@Override	public int create(Category category) {		return categoryMapper.insertSelective(category);	}	@Override	public Category selectByName(String name) {		return categoryMapper.selectByName(name);	}	@Override	public List<Category> getAll() {		return categoryMapper.getAll();	}}

4.5、CategoryService層及其實(shí)現(xiàn)

package Service;public interface CategoryService {	public List<Category> getList();		public int create(Category category);		public List<Category> getAll();}
package ServiceImpl;@Servicepublic class CategoryServiceImpl implements CategoryService{	@Autowired	private CategoryDAO categoryDAO;	@Override	public List<Category> getList() {		return categoryDAO.getList();	}	@Override	public int create(Category category) {		if(categoryDAO.selectByName(category.getName())!=null)			throw new RuntimeException("類別 " + category.getName() + " 已經(jīng)存在。");		return categoryDAO.create(category);	}	@Override	public List<Category> getAll() {		return categoryDAO.getAll();	}}

4.6、Category控制層

package Controller;@Controllerpublic class CategoryController {		@Autowired	private CategoryService categoryService;		@RequestMapping("category_list.do")	public ModelAndView list(HttpServletRequest request){		request.setAttribute("title", "輕量級 Java EE 論壇程序");		List<Category> categoryList = categoryService.getList();		request.setAttribute("categoryList", categoryList);		return new ModelAndView("category/listCategory");	}		@RequestMapping("category_initAdd.do")	public ModelAndView initAdd(HttpServletRequest request){		request.setAttribute("title", "添加類別");		request.setAttribute("category", new Category());		return new ModelAndView("category/addCategory");	}		@RequestMapping("category_add.do")	public ModelAndView add(@ModelAttribute Category category, HttpServletRequest request){		request.setAttribute("title", "添加類別");		category.setDatecreated(new Date());		category.setDeleted(false);		categoryService.create(category);		return new ModelAndView("category/success");	}}好吧!我承認(rèn)老是貼代碼,毫無營養(yǎng)!版面模塊、帖子模塊和回帖模塊的代碼就不貼出來了。如果是我也沒耐心看完,直接下載源碼學(xué)來得更實(shí)際一些。下載源碼
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 伊吾县| 木兰县| 友谊县| 耿马| 登封市| 吉林市| 廉江市| 宝鸡市| 金沙县| 敦化市| 个旧市| 自贡市| 峡江县| 霞浦县| 灵石县| 黔东| 行唐县| 新兴县| 如东县| 平昌县| 兰坪| 沛县| 万州区| 盐津县| 枣强县| 虹口区| 沧州市| 卓资县| 万源市| 罗平县| 古蔺县| 社旗县| 微山县| 嵊州市| 屯留县| 桦南县| 罗源县| 吉首市| 尖扎县| 锡林浩特市| 炉霍县|