Method one using Setter method
Package Com.swift; Public class Book { private String bookname; Public void Setbook (String bookname) { this. BookName= bookname; } @Override public String toString () { return ' book [book= ' + bookname + "]"; }}
In the spring framework, it is assumed that the object of the book class cannot be generated directly from the Servlet class, and that the property values of string bookname are injected
And the way to configure file 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" xsi:schemalocation=" http://http://www.springframework.org/schema/beans/spring-beans.xsd"> Class= "Com.swift.Book" ><property name= "BookName" value= "three-body-dark forest" ></property>< /bean></beans>
Servlet Class Code:
PackageCom.swift;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; @WebServlet ("/book") Public classBookservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; PublicBookservlet () {Super(); } protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); Response.getwriter (). Append ("Served at:"). Append (Request.getcontextpath ()); @SuppressWarnings ("Resource") //that's the bottom line.ApplicationContext context=NewClasspathxmlapplicationcontext ("A.xml"); Book Book= (book) Context.getbean ("book")); String BookInfo=Book.fun (); Response.getwriter (). println (); Response.getwriter (). append (BookInfo); } protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
Attention
Beans, context, core, and expression kernel jar packages
As well as commons-logging and log4j two jar packages not missing
Method two using the method of constructing a parameter
Spring injection properties based on XML configuration file