JAVA-Spring学习之环境搭建

来源:互联网 发布:苏州php培训 编辑:程序博客网 时间:2024/05/16 07:22

spring框架是JAVAEE中的一个重要框架,spring最主要的作用是管理项目中的对象。当然,它的作用不仅仅于此,Spring是全面的和模块化的。Spring有分层的体系结构,这意味着你能选择使用它孤立的任何部分,它的架构仍然是内在稳定的。spring具有以下特点(引用自百度百科):

1.轻量——从大小与开销两方面而言Spring都是轻量的。完整的Spring框架可以在一个大小只有1MB多的JAR文件里发布。并且Spring所需的处理开销也是微不足道的。此外,Spring是非侵入式的:典型地,Spring应用中的对象不依赖于Spring的特定类。

2.控制反转——Spring通过一种称作控制反转(IoC)的技术促进了低耦合。当应用了IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。你可以认为IoC与JNDI相反——不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。

3.面向切面——Spring提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。

4.容器——Spring包含并管理应用对象的配置和生命周期,在这个意义上它是一种容器,你可以配置你的每个bean如何被创建——基于一个可配置原型(prototype),你的bean可以创建一个单独的实例或者每次需要时都生成一个新的实例——以及它们是如何相互关联的。然而,Spring不应该被混同于传统的重量级的EJB容器,它们经常是庞大与笨重的,难以使用。

5.框架——Spring可以将简单的组件配置、组合成为复杂的应用。在Spring中,应用对象被声明式地组合,典型地是在一个XML文件里。Spring也提供了很多基础功能(事务管理、持久化框架集成等等),将应用逻辑的开发留给了你。

6.MVC——Spring的作用是整合,但不仅仅限于整合,Spring 框架可以被看做是一个企业解决方案级别的框架。客户端发送请求,服务器控制器(由DispatcherServlet实现的)完成请求的转发,控制器调用一个用于映射的类HandlerMapping,该类用于将请求映射到对应的处理器来处理请求。HandlerMapping 将请求映射到对应的处理器Controller(相当于Action)在Spring 当中如果写一些处理器组件,一般实现Controller 接口,在Controller 中就可以调用一些Service 或DAO 来进行数据操作 ModelAndView 用于存放从DAO 中取出的数据,还可以存放响应视图的一些数据。 如果想将处理结果返回给用户,那么在Spring 框架中还提供一个视图组件ViewResolver,该组件根据Controller 返回的标示,找到对应的视图,将响应response 返回给用户。


那么我们开始spring环境的搭建:

 1.先现在spring的jar包(这里用的4.3.2)http://repo.spring.io/release/org/springframework/spring/


2.在IDE工具中(MYEclipse/IDEA等)创建一个web项目,在项目的lib文件夹下加入下列jar包



3.在src下创建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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">   <context:annotation-config></context:annotation-config>   <context:component-scan base-package="com.xwl.estore"></context:component-scan></beans>


4.在web.xml中配置spring的配置文件路径,并实例化spring容器,具体代码如下:

<?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>testSpring</display-name><!-- Spring 文件路径 --><context-param><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><listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>


5.这一步比较关键,因为我们创建的是web项目(如果是c/s项目就没有这个问题),需要用到servlet,但是servlet和spring都是容器,所以我们得把一方交由另一方管理,防止发生冲突。我查资料学到的一个方法是,创建一个类,将servlet转换为spring管理的一个bean,让spring成为最大的容器管理所有对象。编写一个类,让这个类继承javax.servlet.GenericServlet,具体代码如下:(这部分代码参考自http://blog.csdn.net/xwl617756974/article/details/7451773)

package cn.purplestar.testSpring.servlet;import java.io.IOException;import javax.servlet.GenericServlet;import javax.servlet.Servlet;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;/** * 将Servlet转为Spring管理的Servlet Bean */public class ServletTOBean extends GenericServlet {// 当前客户端请求的Servlet名字private String targetBean;// 代理Servletprivate Servlet proxy;@Overridepublic void init() throws ServletException {super.init();// 初始化Spring容器WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());// 获取Servlet名this.targetBean = getServletName();// 调用ServletBeanthis.proxy = (Servlet) wac.getBean(targetBean);// 调用初始化方法将ServletConfig传给Beanproxy.init(getServletConfig());}@Overridepublic void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {// 在service方法中调用bean的service方法,servlet会根据客户的请求去调用相应的请求方法(Get/Post)proxy.service(request, response);}}


6.编写用于测试的业务逻辑,创建dao层接口及类,创建service层接口及类,创建控制层的servlet,具体代码如下:

dao层接口IHelloWorldDao

package cn.purplestar.testSpring.dao;public interface IHelloWorldDao {public String sayHello();}
dao层实现类HelloWorldDaoImpl
package cn.purplestar.testSpring.dao.impl;import cn.purplestar.testSpring.dao.IHelloWorldDao;public class HelloWorldDaoImpl implements IHelloWorldDao {@Overridepublic String sayHello() {String str = "HelloWorld,这是我第一个Spring应用";System.out.println(str);return str;}}
service层接口IHelloWorldService
package cn.purplestar.testSpring.service;public interface IHelloWorldService {public String sayHello();}
service层实现类HelloWorldServiceImpl
package cn.purplestar.testSpring.service.impl;import cn.purplestar.testSpring.dao.IHelloWorldDao;import cn.purplestar.testSpring.service.IHelloWorldService;/** *  * Title: HelloWorldService * Description: 输出helloworld业务逻辑类 * @author 尚文彬 * @date 2016年11月18日 下午3:37:38 */public class HelloWorldServiceImpl implements IHelloWorldService {private IHelloWorldDao helloWorldDao;public void setHelloWorldDao(IHelloWorldDao helloWorldDao) {this.helloWorldDao = helloWorldDao;}public String sayHello() {return helloWorldDao.sayHello();}}
控制层HelloWorldServlet
package cn.purplestar.testSpring.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.purplestar.testSpring.service.IHelloWorldService;/** * Servlet implementation class HelloWorldServlet */@WebServlet("/HelloWorldServlet")public class HelloWorldServlet extends HttpServlet {private static final long serialVersionUID = 1L;    private IHelloWorldService helloWorldService;        public void setHelloWorldService(IHelloWorldService helloWorldService) {this.helloWorldService = helloWorldService;}        /**     * @see HttpServlet#HttpServlet()     */    public HelloWorldServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String str = helloWorldService.sayHello();request.setAttribute("message", str);request.getRequestDispatcher("/WEB-INF/page/test.jsp").forward(request, response);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}


7.在applicationContext.xml中配置这些类的bean

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">   <context:annotation-config></context:annotation-config>   <context:component-scan base-package="com.xwl.estore"></context:component-scan>   <!-- 配置bean -->   <bean id="helloWorldDao" class="cn.purplestar.testSpring.dao.impl.HelloWorldDaoImpl"/>   <bean id="helloWorldService" class="cn.purplestar.testSpring.service.impl.HelloWorldServiceImpl">   <property name="helloWorldDao" ref="helloWorldDao" />   </bean>   <bean id="helloWorld" class="cn.purplestar.testSpring.servlet.HelloWorldServlet"> <property name="helloWorldService" ref="helloWorldService"></property>   </bean></beans>


8.在web.xml中配置servlet,这一步和正常配置servlet有点不太一样,其中<servlet-name>的值要和applicationContext.xml中的servlet的bean的名字一致,<servlet-class>配置为前面的转换类,具体代码如下:

<?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>testSpring</display-name><!-- Spring 文件路径 --><context-param><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><listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><servlet><servlet-name>helloWorld</servlet-name><servlet-class>cn.purplestar.testSpring.servlet.ServletTOBean</servlet-class></servlet><servlet-mapping><servlet-name>helloWorld</servlet-name><url-pattern>/helloWorld</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

9.在/WEB-INF下创建page文件夹,在此文件夹下创建test.jsp,在test.jsp页面的<body>标签中用${message}就可以接收到testStruts2()方法返回的值“我的第一个struts2应用”。

10.将项目部署到服务器后,启动服务器,在地址栏中输入127.0.0.1:8080/testSpring/helloWorld,查看效果。








2 0