创建 spring web project 和 下载服务器
ctrl + N
spring project
simple Spring Web Maven
服务器用的是自带的
右击工程,Maven , Update Project
下载服务器; Maven , maven install
sample
实现对class MyBean1中message的修改,
get -> post -> get
--index.xml 通过jsp获取message
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h1>
<pre>${mybean}</pre>
</h1>
<form action="BeanServlet" method="post">
<input type="text" id="message" name="message">
<input type="submit" value="add">
</form>
</body>
</html>
---application-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and add your base-package here:
<context:component-scan
base-package="org.springframework.samples.service"/> -->
<bean id="mybean1" class = "com.luffy.code.MyBean1">
<property name="message" value="2131231"></property>
</bean>
</beans>
通常的写法
--BeanServlet.java
package com.luffy.code;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
/**
* Servlet implementation class BeanServlet
*/
public class BeanServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ApplicationContext app;
/**
* @see HttpServlet#HttpServlet()
*/
public BeanServlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init();
app = new ClassPathXmlApplicationContext("/spring/application-config.xml");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("get");
MyBean1 myBean1 = (MyBean1)app.getBean("mybean1");
request.setAttribute("mybean", myBean1);
request.getRequestDispatcher("/index.jsp").forward(request, response); // servlet -> jsp
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("post");
MyBean1 myBean1 = (MyBean1)app.getBean("mybean1");
myBean1.setMessage(request.getParameter("message"));
response.sendRedirect("BeanServlet"); // servlet -> servlet 重新定向
}
第二种方法 直接使用Bean
@Autowired
会自动和设置好的class MyBean绑定,然 后自动创建一个对象myBean2,在application-config.xml中也不需要配置对象
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
自动注入
所以在application-config.xml中不需要定义ID.
(因为现在仍然通过XML文件管理对象,所以类的地址还必须配置)
----application-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and add your base-package here:
<context:component-scan
base-package="org.springframework.samples.service"/> -->
<bean class = "com.luffy.code.MyBean1">
<property name="message" value="2131231"></property>
</bean>
</beans>
package com.luffy.code;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
public class BeanServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Autowired
private MyBean1 myBean2;
public BeanServlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init();
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("get");
request.setAttribute("mybean", myBean2);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("post");
myBean2.setMessage(request.getParameter("message"));
response.sendRedirect("BeanServlet");
}
}
通过class来进行配置(新创建一个属性类MyBean2进行实验)
package com.luffy.code;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
// 一个Configurable下只能有一个Bean
@Configurable
// 检索场所
@ComponentScan(basePackages = "com.luffy.code")
public class AutoMyBeanConfig {
@Bean
public MyBean2 myBean2() {
// set MyBean
// 在这里创建实际产品
return new MyBean2("213132");
}
}
配置一下web.xml
之前的配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
重新配置后、
指定contextConfigLocation模式为AutoMyBeanConfig类,
contextClass中指定AnnotationConfigWebApplicationContext类
这样的话就可以通过AutoMyBeanConfig读取到MyBean2的信息
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.luffy.code.AutoMyBeanConfig</param-value>
</context-param>
最后记得在调试时候把Servlet中的MyBean1改成MyBean2使用
字符问题,为了不乱码,使用过滤器自动设置字符格式
在web.xml里配置过滤器
<filter>
<filter-name>EncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
使用时,直接在配置文件中设置。
// 一个Configurable下只能有一个Bean
@Configurable
// 检索场所
@ComponentScan(basePackages = "com.luffy.code")
public class AutoMyBeanConfig {
@Bean
public MyBean2 myBean2() {
// set MyBean
// 在这里创建实际产品
return new MyBean2("213132");
}
// 指定监听类
@Bean
public MyApplicationListener appListener() {
return new MyApplicationListener();
}
}
总结
2种配置Bean的方式:
- xml文件(在src/main/resources下,默认application-config.xml)
- Java class ,通过关键词 @Configurable @Bean。在web.xml中设置指定的配置文件为这个java class
在servlet中2种使用Bean的方式
- 首先指定配置方法,然后获取到bean
- 使用@Autowired关键词自动绑定Bean类,并在初始化时候自动注入对象。