1、创建maven web项目,配置spring依赖
a、idea创建maven项目,添加spring framework组件,具体配置步骤太多人写了
b、在pom.xml中配置spring依赖
<!-- spring框架依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
然后更新项目即可
注:maven默认下载源下载速度可能会比较慢,可以换其他速度快的镜像
找到 apache-maven-3.5.2\conf 目录中的 settings.xml 文件
添加阿里源 ,找到 <mirrors> </ mirrors>标签,在标签内部 添加内容如下:
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
速度不能飞起来但比原来的快多了
PS:
依照上文项目搭建完毕,结构如下图
测试spring IOC的简单实现
a、首先在java文件夹中创建一个student类,用来封装数据
public class Student {
private int stuNum;
private String stuName;
private String stuAddress;
public void setStuAddress(String stuAddress) {
this.stuAddress = stuAddress;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public void setStuNum(int stuNum) {
this.stuNum = stuNum;
}
public int getStuNum() {
return stuNum;
}
public String getStuAddress() {
return stuAddress;
}
public String getStuName() {
return stuName;
}
@Override
public String toString() {
return "Student{" +
"stuNum=" + stuNum +
", stuName='" + stuName + '\'' +
", stuAddress='" + stuAddress + '\'' +
'}';
}
}
b、然后在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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="top.voidplus.entity.Student">
<property name="stuNum" value="1"></property>
<property name="stuName" value="ada"></property>
<property name="stuAddress" value="china"></property>
</bean>
</beans>
c、新建一个servlet,在servlet中将bean打印出来
package top.voidplus.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.voidplus.entity.Student;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// spring IOC
// 获取 applicationContext的上下文对象 ,注意applicationContext的路径应该都是这个
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
Student student = (Student)context.getBean("student");
System.out.println(student.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
d、在jsp页面中写一个超链接,用于向servlet提交get请求,调用doget方法
<h1>hello21312124</h1>
<a href="TestServlet">testservlet</a>
e、结果