JAVAEE Course Design "Shopping Mall"

1. Early stage of development

1. Development environment:

Currently using myeclipse jdk1.8 tomcat 6

2. Create a project

new —— web project —— remember to check web.xml

3. SSM framework integration configuration

Adding dependencies
There are two commonly used ways to add dependencies:

Create a project through maven, add dependencies through maven
Import the corresponding jar package locally, beginners can use it, but there are more additions
We now use the local import WEB-INF --lib folder

Add configuration file
1. Configuration of spring's basic configuration
applicationContext.xml file
Since there are many things to configure, we can configure it
in multiple files. Here: applicationContext-dao.xml applicationContext-service.xml applicationContext-tx.xml

Basic configuration: namespace and constraints, templates from the official website
2, basic configuration
of springMVC Create springMVC.xml file, add constraints
3, configuration of mybatis
4, configuration of log4j.properties
In general, we use the general configuration, if there are special requirements , you can learn the configuration syntax of log4j

Second, start the integration configuration

1. Inweb.xml(Configuration file that comes with the project) Configure other configuration files to start or associate

1.1. Instantiate and start the spring container (load the applicationContext to make this configuration file work)

   <!--实例化spring的容器 -->
  <context-param>
  		<!-- 指定一下applicationContext的路径 -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext-*.xml</param-value>
  </context-param>
  <!--添加监听器,启动spring的容器  -->
  <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

1.2, add the configuration of springmvc

<!-- 添加springmvc的配置文件  -->
  <servlet>
     <servlet-name>DispatcherServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <!--当springMVC.xml文件不在默认位置(webroot下web-inf),那么需要我们手动配置  -->
     <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:springMvc.xml</param-value>
     </init-param>
  </servlet>
  <servlet-mapping>
     <servlet-name>DispatcherServlet</servlet-name>
     <url-pattern>*.action</url-pattern>
  </servlet-mapping>

Note 1: What is DispatcherServlet?

  • The servlet is used to process user requests. The front-end controller (DispatcherServlet) is similar to the previous servlet and is used to receive user requests.
  • SpringMVC is also an implementation of Servlet, but SpringMVC adds a DispatchServlet, all http requests are mapped to this servlet, and after the request enters this servlet, even if it enters the framework, this servlet will uniformly allocate http Request to each Controller.

About what is DispatcherServlet, Servlet, recommend this blog

1.3, add encoding filter

 <!-- 避免中文乱码 -->
  <filter>
     <filter-name>characterFilter</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>characterFilter</filter-name>
       <!-- 匹配所有的请求,拦截下来 -->
      <url-pattern>/* </url-pattern>
  </filter-mapping>

Other configurations should be configured here according to the normal development process (as a beginner, we configure when needed)

2. The ability to access the web interface on the browser

1. Create the front-end interface

Generally, our front-end interface is placed in the folder created by ourselves under WEB-INF, because under the webRoot folder, except for WEB-INF, it is open to the outside world.
Our interface source code should be protected.

2. Create a controller

Create a separate package to hold all the controllers

@Controller
public class IndexController {
    
    
	
	//匹配访问路径
	@RequestMapping("/index")
	public String index(){
    
    
		System.out.println("进来");
		//返回的是你要访问的页面的名字(不包含后缀)
		return "index";
	}

}

3. Configure the scanner and view parser in the springMvc.xml file

<!-- 配置扫描器:配置的是控制器的包名 -->
    <context:component-scan base-package="com.qfedu.controller"></context:component-scan>
    <!-- 配置视图解析器 -->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver"
           id="internalResourceViewResolver">
           
         <!-- 前缀 -->
         <property name="prefix" value="/WEB-INF/jsp/"></property>
         <!--后缀  -->
         <property name="suffix" value=".jsp"></property>
    </bean>

For specific explanations of relevant parameters, this blog is recommended

4. Test

Browser access: http://loalhost:8080/GouWuShangCheng/index.action

Summary: access page data flow runs through the process

insert image description here

3. SSM framework data loading process (model of springMVC)

1. Database configuration

Configure dataSource in applicationContext-dao.xml file

1.1 Configure the database connection (the database driver and database version must match), configure the connection pool, and the database connection

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	      <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
	      <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8"></property>
	      <property name="user"  value="root"></property>
	      <property name="password" value="123456"></property>
</bean>

1.2 Configure the sqlsession of mybatis and inject the dataSource into it

<!--加载sqlsession工厂,同时加载mybatis.xml   注入数据源 -->
	 <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
	      <!--name中的值是java文件中对应的对象名,ref是数据源配置的id值-->
	 	  <property name="dataSource"  ref="dataSource"></property>
	 	  <property name="configLocation" value="classpath:mybatis.xml"></property>
 </bean>

1.3 Configure the transaction management of the data source in applicationContext-tx.xml

<!--添加事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       
       <property name="dataSource"   ref="dataSource"></property>
    </bean>

1.4 Simple configuration of mybatis (or not)

<configuration>
   <settings>
	   <!--是否开启懒加载-->
      <setting name="lazyLoadingEnabled" value="true"/>
      <setting name="aggressiveLazyLoading" value="false"/>
      
      <setting name="cacheEnabled" value="true"/>
   </settings>
</configuration>

2. Operating the database is actually the writing of the Mapper mapper

2.1, write CategoryMapper.java file

Create an interface interface file

public interface CategoryMapper {
    
    
	/*查询所有目录的方法*/
	public List<Category> selectALLCategory();
	}
	

2.2, create CategoryMapper.xml file

2.2.1 Since the return of the query statement is a result set, a custom mapping set is required here

 <resultMap type="com.qfedu.pojo.Category" id="allCategory">
   <!--column 的值是数据库表中的列名,property是pojo中的属性名-->
       <id  column="cid"  property="cId" />
       <result column="cname" property="cName" />
       <!--一对多级联使用collection标签-->
       <collection property="second" ofType="com.qfedu.pojo.CategorySecond">
           <id  column="csid" property="csId"/>
           <result column="csname" property="csName"/>
           <result column="cid" property="cId"/>
       </collection>
   </resultMap>

2.2.2 Write sql statement

    <select id="selectALLCategory"  resultMap="allCategory">
      select category.*,categorysecond.* from category,categorysecond where
      category.cid= categorysecond.cid
   </select>

2.3 Configure mapper's scanner in applicationContext-dao.xml

  <!--配置mapper的扫描器-->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.qfedu.mapper"></property>
     <property name="sqlSessionFactoryBeanName"  value="sqlSessionFactory"></property>
 </bean>

3. The editing of business logic code, that is, the writing of service

3.1 Write the service class

In the service, we call the mapper method to obtain the operation result of the database, and then perform logical processing

  public class CategoryService {
    
    
	
	@Autowired
	public CategoryMapper categoryMapper;
	
	/*调用mapper映射器的方法,或者数据库操作结果,并处理
	 * 这里是获取所有的目录*/
	public List<Category>  findAllCategory(){
    
    
		 //调用mapper方法,回去操作结果
	     List<Category> list=categoryMapper.selectALLCategory();
	     if(list!=null&&list.size()!=0){
    
    
	    	 return list;
	     }else{
    
    
	    	 return null;
	     }
	}
	
}

3.2 Configure the service bean in applicationContext-service.xml

<bean id="categoryService" class="com.qfedu.service.CategoryService" > </bean>

3.3 In applicationContext-tx.xml, use service as the entry point of aop, and configure the entry point of the aop aspect

<!--开启注解,添加通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="get*" propagation="SUPPORTS"/>
		</tx:attributes>
	</tx:advice>
	
	<!--配置切面-->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qfedu.service.*.*(..))"/>
	</aop:config> 
    
    </beans>

4. Call the service method in the controller, get the result, and return the result to the front end

@Controller
public class IndexController {
    
    
	
	@Autowired
	public CategoryService  categoryService;
	

	@RequestMapping("/index")
	public String index(Model model){
    
    
		//获取目录的数据,然后返回给前端界面
		List<Category> cList=categoryService.findAllCategory();
		
		model.addAttribute("cList", cList);
		
		return "index";
	}

} 

5. Receive data at the front end

<div class="span6">
				<div class="hotProductCategory">
				     <!--${cList}这个就是接收数据,cList是键值对的键  
				      var="c"  这个c是集合中的一个元素
				      ${c.cId}  cId是pojo的属性名 -->
					<c:forEach var="c" items="${cList}">
						<dl>
							<dt>
								<a
									href="${pageContext.request.contextPath}/findCategorySecond.action?cid=${c.cId}&page=1">
									${c.cName} </a>
							</dt>
							<c:forEach items="${c.second}" var="cs">
								<dd>
									<a
										href="${pageContext.request.contextPath}/findCategorySecond1.action?csid=${cs.csId}&page=1">
										${cs.csName}</a>
								</dd>
							</c:forEach>
						</dl>
					</c:forEach>
				</div>
		

4. Front-end page + database

insert image description here

insert image description here

Fourth, a brief summary

1. SSM integration ideas

When spring is managed, it is very organized. Each layer is managed by spring, and then different layers can call other layers, Handler calls service, service calls mapper, etc.

1 Integrate the dao layer. Mybatis is integrated with spring, and the mapper interface is managed through spring. Use the mapper's scanner to automatically scan the mapper interface for registration in spring.

2 Integrate the service layer. The service interface is managed through spring. Use the configuration method to configure the service interface in the spring configuration file. Implement transaction control.

3 Integrate springmvc. Since springmvc is a spring module, no integration is required.

2. Integrated analysis

1. spring MVC + spring + mybatis is a standard MVC design pattern, which divides the entire system into four layers: display layer, controller layer, service layer, and DAO layer.
Using Spring MVC to be responsible for request forwarding and view management
, spring realizes business object management. mybatis as a persistence engine for data objects.
2. Spring is an open source framework. Spring is a lightweight Inversion of Control (IoC) and Aspect-Oriented (AOP) container framework, which can better integrate other frameworks.
3. The Spring MVC framework has an MVC framework that separates data, business and presentation well by implementing the Model-View-Controller pattern.
4. MyBatis is a Java-based persistence layer framework

The Service layer is built on the DAO layer. After the DAO layer is established, the Service layer can be established, and the Service layer is under the Controller layer. Therefore, the
Service layer should not only call the interface of the DAO layer, but also provide an interface to The class of the Controller layer is called, which happens to be in a middle layer.
Each model has a Service interface, and each interface encapsulates its own business processing methods.

The relationship between the four layers, I recommend this blog
and this blog
This project was originally designed for a specialist course, and now the undergraduate needs it again, so it runs through again. If there is any infringement, please contact and delete it immediately.

Guess you like

Origin blog.csdn.net/qq_30336973/article/details/118076429