锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
]]>
Step 20 – Add unit test for the SpringappController
Before we create any unit tests, we want to prepare Ant and our build script to be able to handle this. Ant has a built in JUnit target, but we need to add junit.jar to Ant's lib directory. I used the one that came with the Spring distribution spring-framework-1.2/lib/junit/junit.jar. Just copy this file to the lib directory in your Ant installation. I also added the following target to our build script.
<target name="junit" depends="build" description="Run JUnit Tests"> <junit printsummary="on" fork="false" haltonfailure="false" failureproperty="tests.failed" showoutput="true"> <classpath refid="master-classpath"/> <formatter type="brief" usefile="false"/> <batchtest> <fileset dir="${build.dir}"> <include name="**/Test*.*"/> </fileset> </batchtest> </junit> <fail if="tests.failed"> |
Now I add a new sub-directory in the src directory that I name tests. This directory will, as you might have guessed, contain all the unit tests.
After all this, we are ready to start writing the first unit test. The SpringappController depends on both the HttpServletRequest, HttpServletResponse and our application context. Since the controller does not use the request or the response, we can simply pass in null for these objects. If that was not the case, we could create some mock objects using EasyMock that we would pass in during our test. The application context can be loaded outside of a web server environment using a class that will load an application context. There are several available, and for the current task the FileSystemXmlApplicationContext works fine.
springapp/src/tests/TestSpringappController.java |
package tests; |
The only test is a call to handleRequest, and we check the products that are returned in the model. In the setUp method, we load the application context that I have copied into a WEB-INF directory in the src/tests directory. I create a copy just so this file will work during tests with a small set of beans necessary for running the tests. So, copy springapp/war/WEB-INF/springapp-servlet.xml to springapp/src/tests/WEB-INF directory. You can then remove the “messageSource”, "urlMapping" and "viewResolver" bean entries since they are not needed for this test.
springapp/src/tests/WEB-INF/springapp-servlet.xml |
<?xml version="1.0" encoding="UTF-8"?> |
When you run this test, you should see a lot of log messages from the loading of the application context.
Step 21 – Add unit test and new functionality for ProductManager
Next I add a test case for the ProductManager, and I also add a test for a new method to increase the prices that I am planning on adding to the ProductManager.
springapp/src/tests/TestProductManager .java |
package tests; |
For this test, there is no need to create an application context. I just create a couple of products in the setUp method and add them to the product manager. I add tests for both getProducts and increasePrice. The increasePrice method is a cross the board increase based on the percentage passed in to the method. I modify the ProductManager class to implement this new method.
springapp/src/bus/ProductManager.java |
package bus; |
Next I build and run the tests. As you can see, this test is just like any regular test – the business classes don't depend on any of the servlet classes so these classes are very easy to test.
Step 22 – Adding a form
To provide an interface in the web application, I add a form that will allow the user to enter a percentage value. This form uses a tag library named “spring” that is provided with the Spring Framework. We have to copy this file from the Spring distribution spring-framework-1.2/dist/spring.tld to the springapp/war/WEB-INF directory. Now we must also add a <taglib> entry to web.xml.
springapp/war/WEB-INF/web.xml |
<?xml version="1.0" encoding="UTF-8"?> |
We also have to declare this taglib in a page directive in the jsp file. We declare a form the normal way with a <form> tag and an <input> text field and a submit button.
springapp/war/WEB-INF/jsp/priceincrease.jsp |
<%@ include file="/WEB-INF/jsp/include.jsp" %> |
The <spring:bind> tag is used to bind an <input> form element to a command object PriceIncrease.java, that is used together with the form. This command object is later passed in to the validator and if it passes validation it is passed on to the controller. The ${status.errorMessage} and ${status.value} are special variables declared by the framework that can be used to display error messages and the current value of the field.
springapp/src/bus/PriceIncrease.java |
package bus; |
This is a very simple JavaBean class, and in our case there is a single property with a getter and setter. The validator class gets control after the user presses submit. The values entered in the form will be set on the command object by the framework. The method validate is called and the command object and an object to hold any errors are passed in.
springapp/src/bus/PriceIncreaseValidator.java |
package bus; |
Now we need to add an entry in the springapp-servlet.xml file to define the new form and controller. We define properties for command object and validator. We also specify two views, one that is used for the form and one that we will go to after successful form processing. The latter which is called the success view can be of two types. It can be a regular view reference that is forwarded to one of our JSP pages. One disadvantage with this approach is, that if the user refreshes the page, the form data is submitted again, and you would end up with a double priceincrease. An alternative way is to use a redirect, where a response is sent back to the users browser instructing it to redirect to a new url. The url we use in this case can't be one of our JSP pages, since they are hidden from direct access. It has to be a url that is externally reachable. I have choosen to use 'hello.htm' as my redirect url. This url maps to the 'hello.jsp' page, so this should work nicely.
springapp/war/WEB-INF/springapp-servlet.xml |
<?xml version="1.0" encoding="UTF-8"?> |
Next, let's take a look at the controller for this form. The onSubmit method gets control and does some logging before it calls the increasePrice method on the ProductManager object. It then returns a ModelAndView passing in a new instance of a RedirectView created using the url for the successView.
springapp/src/web/PriceIncreaseFormController.java |
package web; |
We are also adding some messages to the messages.properties resource file.
springapp/war/WEB-INF/classes/messages.properties |
title=SpringApp |
Finally, we have to provide a link to the priceincrease page from the hello.jsp.
springapp/war/WEB-INF/jsp/hello.jsp |
<%@ include file="/WEB-INF/jsp/include.jsp" %> |
Compile and deploy all this and after reloading the application we can test it. This is what the form looks like with errors displayed.
This is what we have to start with.
An introduction page index.jsp.
A DispatcherServlet with a corresponding springapp-servlet.xml configuration file.
A controller springappController.java.
A view hello.jsp.
We will now improve on these parts to build a more useful application.
Step 13 – Improve index.jsp
We will make use of JSP Standard Tag Library (JSTL) so I will start by copying the JSTL files we need to our WEB-INF/lib directory. Copy jstl.jar from the 'spring-framework-1.2/lib/j2ee' directory and standard.jar from the 'spring-framework-1.2/lib/jakarta-taglibs' directory to the springapp/war/WEB-INF/lib directory. I am also creating a “header” file that will be included in every JSP page that I'm going to write. This will make development easier and I will be sure that I have the same definitions in all JSPs. I am going to put all JSPs in a directory named jsp under the WEB-INF directory. This will ensure that only the controller has access to the views - it is not possible to get to these pages by entering them directly as a URL in the browser. This strategy might not work in all application servers and if this is the case with the one you are using, just move the jsp directory up a level. You would then use springapp/war/jsp as the directory instead of springapp/war/WEB-INF/jsp in all the code examples that will follow.
springapp/war/WEB-INF/jsp/include.jsp |
<%@ page session="false"%> |
Now we can change index.jsp to use this include and since we are using JSTL we can use the <c:redirect> tag for redirecting to our Controller. This ties the index.jsp into our application framework.
springapp/war/index.jsp |
<%@ include file="/WEB-INF/jsp/include.jsp" %> |
Step 14 – Improve the view and the controller
I am going to move the view hello.jsp to the WEB-INF/jsp directory. The same include that was added to index.jsp gets added to hello.jsp. I also add the current date and time as output that I will retrieve from the model, passed to the view, using the JSTL <c:out> tag.
springapp/war/WEB-INF/jsp/hello.jsp |
<%@ include file="/WEB-INF/jsp/include.jsp" %> |
For SpringappController.java there are a few changes we need to make. Change the view to WEB-INF/jsp/hello.jsp since we moved the file to this new location. Also add a string containing the current data and time as the model.
springapp/src/SpringappController.java |
import org.springframework.web.servlet.mvc.Controller; |
Now we are ready to try this after we build and deploy this new code. We enter http://localhost:8080/springapp in a browser and that should pull up index.jsp, which should redirect to hello.htm, which in turn gets us to the controller that sends the data and time to the view.
Step 15 – Decouple the view and the controller
Right now the controller specifies the full path of the view, which creates an unnecessary dependency between the controller and the view. Ideally we would like to map to the view using a logical name, allowing us to switch the view without having to change the controller. You can set this mapping in a properties file if you like using a ResourceBundleViewResolver and a SimpleUrlHandlerMapping class. If your mapping needs are simple it is easier to just set a prefix and a suffix on the InternalResourceViewResolver. The latter approach is the one that I will implement now, so I modify the springapp-servlet.xml and include this viewResolver entry. I have elected to use a JstlView which will enable us to use JSTL in combination with message resource bundles and it will also support internationalization.
springapp/war/WEB-INF/springapp-servlet.xml |
<?xml version="1.0" encoding="UTF-8"?> |
So now I can remove the prefix and suffix from the view name in the controller.
springapp/src/SpringappController.java |
import org.springframework.web.servlet.mvc.Controller; |
Compile and deploy and the application should still work.
Step 16 – Add some classes for business logic
So far our application is not very useful. I would like to add a little bit of business logic in form of a Product class and a class that will manage all the products. I name this management class ProductManager. In order to separate the web dependent logic from the business logic I will create two separate packages for the Java source – web and bus. If this was an application for a real company I would name the packages something like com.mycompany.web and com.mycompany.bus, but since this is just a demo application I will keep the package names real short. The Product class is implemented as a JavaBean – it has the default constructor (automatically provided if we don't specify any constructors) and getters and setters for the two instance variables description and price. I also make it Serializable, not necessary for our application, but could come in handy later on if we have to pass this class between different application layers.
springapp/src/bus/Product.java |
package bus; |
The ProductManager holds a List of Products, and again this this class is implemented as a JavaBean.
springapp/src/bus/ProductManager.java |
package bus; |
Next, I modify the SpringappController to hold a reference to this ProductManager class. As you can see, it is now in a separate package called web – remember to move the source to this new location. I also add code to have the controller pass some product information to the view. The getModelAndView now returns a Map with both the date and time and the product manager reference.
springapp/src/web/SpringappController.java |
package web; |
Step 17 – Modify the view to display business data and add support for message bundle
Using the JSTL <c:forEach> tag, I add a section that displays product information. I have also replaced the title, heading and greeting text with a JSTL <fmt:message> tag that pulls the text to display from a provided 'message' source – I will show this source in a later step.
springapp/war/WEB-INF/jsp/hello.jsp |
<%@ include file="/WEB-INF/jsp/include.jsp" %> |
Step 18 – Add some test data to automatically populate some business objects
I am not going to add any code to load the business objects from a database just yet. Instead, we can “wire up” a couple of instances using Spring's bean and application context support. I will simply put the data I need as a couple of bean entries in springapp-servlet.xml. I will also add the messageSource entry that will pull in the messages resource bundle ('messages.properties') that I will create in the next step.
springapp/war/WEB-INF/springapp-servlet.xml |
<?xml version="1.0" encoding="UTF-8"?> |
Step 19 – Add the message bundle and a 'clean' target to build.xml
I create a 'messages.properties' file in the war/WEB-INF/classes directory. This properties bundle so far has three entries matching the keys specified in the <fmt:message> tags that we added to the hello.jsp.
springapp/war/WEB-INF/classes/messages.properties |
title=SpringApp |
Since we moved some source files around, it makes sense to add a 'clean' and an 'undeploy' target to the build scripts. I add the following entries to the build.xml file.
<target name="clean" description="Clean output directories"> <delete> <fileset dir="${build.dir}"> <include name="**/*.class"/> </fileset> </delete> </target> <target name="undeploy" description="Un-Deploy application"> <delete> <fileset dir="${deploy.path}/${name}"> <include name="**/*.*"/> </fileset> </delete> </target> |
Now stop the Tomcat server, run the clean, undeploy and deploy targets. This should remove all old class files, re-build the application and deploy it. Start up Tomcat again and you should see the following:
Prerequisites:
Java SDK (I am currently using version 1.4.2)
Ant (using version 1.6.2)
Apache Tomcat (using version 5.0.28)
You should also be reasonably comfortable using the above software.
I am not going to cover a lot of background information or theory in this document -- there are plenty of books available that covers this in depth. Instead we will dive right into developing the application.
Step 1 – development directory
We are going to need a place to keep all the source and other files we will be creating, so I create a directory that I name 'springapp'. You can place this directory in your home folder or in some other location. I created mine in a 'projects' directory that I already had in my home directory so the full path to my directory is '/Users/trisberg/projects/springapp'. Inside this directory I create a 'src' directory to hold all Java source files. Then I create another directory that I name 'war'. This directory will hold everything that should go into the WAR file, that we would use to deploy our application. All source files other than Java source, like JSPs and configuration files, belongs in this directory.
Step 2 – index.jsp
I will start by creating a JSP page named 'index.jsp' in the war directory. This is the entry point for our application.
springapp/war/index.jsp |
<html> |
Just to have a complete web application, I create a web.xml in a WEB-INF directory that I create under the war directory.
springapp/war/WEB-INF/web.xml |
<?xml version="1.0" encoding="UTF-8"?> |
Step 3 – deploying the application to Tomcat
Next, I write an Ant build script that we are going to use throughout this document. There are tasks for building and deploying the application. A separate build script contains the app server specific tasks There are also tasks for controlling the application under Tomcat.
springapp/build.xml |
<?xml version="1.0"?> |
This script now contains all the targets that we are going to need to make our development efforts easier. I am not going to cover this script in detail since most if not all of it is pretty much standard Ant and Tomcat stuff. You can just copy the above build file and put it at the root of your development directory tree. We also need a build.properties file that you should customize to match your server installation. This file belongs in the same directory as the build.xml file.
springapp/build.properties |
# Ant properties for building the springapp |
If you are on a system where you are not the owner of the Tomcat install, then the Tomcat owner must either grant you full access to the webapps directory or the owner must create a new directory named 'springapp' in the 'webapps' directory of the Tomcat installation, and also give you full rights to deploy to this newly created directory. On Linux I run the command chmod a+rwx springapp to give everybody full rights to this directory.
If you are using a different web application server, then you can remove the Tomcat specific tasks at the end of the build script. You will have to rely on your server's hot deploy feature, or you will have to stop and start your application manually.
Now I run Ant to make sure that everything is working OK. You should have your current directory set to the 'springapp' directory.
[trisberg@localhost springapp]$ ant Buildfile: build.xml usage: [echo] springapp build file [echo] ----------------------------------- [echo] Available targets are: [echo] build --> Build the application [echo] deploy --> Deploy application as directory [echo] deploywar --> Deploy application as a WAR file [echo] install --> Install application in Tomcat [echo] reload --> Reload application in Tomcat [echo] start --> Start Tomcat application [echo] stop --> Stop Tomcat application [echo] list --> List Tomcat applications BUILD SUCCESSFUL Total time: 2 seconds |
Last action here is to do the actual deployment. Just run Ant and specify 'deploy' or 'deploywar' as the target.
[trisberg@localhost springapp]$ ant deploy Buildfile: build.xml build: |
Step 4 – Test the application
Let's just quickly start Tomcat and make sure that we can access the application. Use the 'list' task from our build file to see if Tomcat has picked up the new application.
[trisberg@localhost springapp]$ ant list Buildfile: build.xml list: |
If it is not listed, use the 'install' task to get the application installed in Tomcat.
[trisberg@localhost springapp]$ ant install Buildfile: build.xml install: [install] OK - Installed application at context path /springapp BUILD SUCCESSFUL Total time: 2 seconds |
Now open a browser and browse to http://localhost:8080/springapp/index.jsp.
Step 5 – Download Spring distribution
If you have not already downloaded the Spring Framework Release file, now is the time to do so. I am currently using 'spring-framework-1.2-with-dependencies.zip' that can be downloaded from www.springframework.org/download.html. I unzipped this file in my home directory. We are going to use several files from this download later on.
This completes the setup of the environment that is necessary, and now we can start actually developing our Spring Framework MVC application.
Step 6 – Modify web.xml in WEB-INF directory
Go to the 'springapp/war/ WEB-INF' directory. Modify the minimal 'web.xml' file that we created earlier. Now we will modify it to suit our needs. We define a DispatcherServlet that is going to control where all our request are routed based on information we will enter at a later point. It also has a standard servlet-mapping entry that maps to the url patterns that we will be using. I have decided to let any url with an '.htm' extension be routed to the 'springapp' dispatcher.
springapp/war/WEB-INF/web.xml |
<?xml version="1.0" encoding="UTF-8"?> |
Next, create a file called 'springapp-servlet.xml' in the springapp/war/WEB-INF directory (you can copy an example of this file from the Spring distributions sample/skeletons/webapp-minimal directory). This is the file where definitions used by the DispatcherServlet should be entered. It is named based on the servlet-name from web.xml with '-servlet' appended. This is a standard naming convention used in the Spring Framework. Now, add a bean entry named springappController and make the class SpringappController. This defines the controller that our application will be using. We also need to add a url mapping so the DispatcherServlet knows which controller should be invoked for different url:s.
springapp/war/WEB-INF/springapp-servlet.xml |
<?xml version="1.0" encoding="UTF-8"?> |
Step 7 – Copy jars to WEB-INF/lib
First create a 'lib' directory in the 'war/WEB-INF' directory. Then, from the Spring distribution, copy spring.jar (spring-framework-1.2/dist/spring.jar) to the new war/WEB-INF/lib directory. Also copy commons-logging jars to the war/WEB-INF/lib directory (spring-framework-1.2/lib/jakarta-commons/commons-logging.jar). We are also going to need a log4j jar. Copy log4j-1.2.9.jar to the war/WEB-INF/lib directory (spring-framework-1.2/lib/log4j/log4j-1.2.9.jar). These jars will be deployed to the server and they are also used during the build process.
Step 8 – Create your Controller
Create your Controller – I named mine SpringappController.java and placed it in the springapp/src directory.
springapp/src/SpringappController.java |
import org.springframework.web.servlet.mvc.Controller; |
This is as basic a Controller as you can use. We will be expanding this later on, and we will also later on extend some provided abstract base implementations. The Controller “handles” the request and returns a ModelAndView. We have not yet defined any Views, so right now there is nothing to do.
Step 9 – Build the Application
Run the 'build' task of the build.xml. Hopefully the code compiles OK.
[trisberg@localhost springapp]$ ant build Buildfile: build.xml build: [javac] Compiling 1 source file to /Users/trisberg/projects/springapp/war/WEB-INF/classes BUILD SUCCESSFUL Total time: 2 seconds |
Step 10 – Copy and modify log4j.properties
The Spring Framework uses log4j for logging so we have to create a configuration file for log4j. Copy the log4j.properties from the sample Petclinic application (spring-framework-1.2/samples/petclinic/war/WEB-INF/log4j.properties) to the war/WEB-INF/classes directory (this directory should have been created in the previous step). Now uncomment or modify the log4j.rootCategory property and change the name and location of the logfile that will be written. I decided to have it written to the same directory as all other Tomcat logs.
springapp/war/WEB-INF/classes/log4j.properties |
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml! |
Step 11 – Deploy Application
Run the 'deploy' task and then the 'stop' and 'start' tasks of the build.xml. This will force a reload of the application. We have to check the Tomcat logs for any deployment errors – there could be typos in the above xml files or there could be missing classes or jar files. This is an example of what it should look like. (/Users/trisberg/jakarta-tomcat-5.0.28/logs/springapp.log)
2005-04-24 14:58:18,112 INFO [org.springframework.web.servlet.DispatcherServlet] - Initializing servlet 'springapp' |
Step 12 – Create a View
Now it is time to create our first view. I will use a JSP page that I decided to name hello.jsp. I'll put it in the war directory to begin with.
springapp/war/hello.jsp |
<html> |
Nothing fancy here, but it will do for now. Next we have to modify the SpringappController to forward to this view.
springapp/src/SpringappController.java |
import org.springframework.web.servlet.mvc.Controller; |
While I was modifying this class, I also added a logger so we can verify that we actually got here. Changes are highlighted in red. The model that this class returns is actually resolved via a ViewResolver. Since we have not specified a specific one, we are going to get a default one that just forwards to a url matching the name of the view specified. We will modify this later on.
Now compile and deploy the application. After instructing Tomcat to stop and then start the application, everything should get reloaded.
Let's try it in a browser – enter the url http://localhost:8080/springapp/hello.htm and we should see the following:
We can also check the log – I'm only showing the last entries, but we can see that the controller did get invoked and that it forwarded to the hello view. (/Users/trisberg/jakarta-tomcat-5.0.28/logs/springapp.log)
2005-04-24 15:01:56,217 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'springapp': initialization completed in 372 ms |
Summary
Let's take quick look at the parts of our application that we have created so far.
An introduction page index.jsp that does not do anything useful. It was just used to test our setup. We will later change this to actually provide a link into our application.
A DispatcherServlet with a corresponding springapp-servlet.xml configuration file.
A controller springappController.java with limited functionality – it just forwards a ModelAndView to the ViewResolver. Actually, we only have an empty model so far, but we will fix this later.
A view hello.jsp that again is extremely basic. But the whole setup works and we are now ready to add more functionality.
閰嶇疆struts-config.xml
1錛?閰嶇疆struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"<struts-config>
<!-- ======================================== Form Bean Definitions -->
<form-beans>
<form-bean
name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="user" type="com.jandar.model.User"/>
</form-bean>
</form-beans>
<!-- =================================== Global Forward Definitions -->
<global-forwards>
</global-forwards>
<!-- =================================== Action Mapping Definitions -->
<action-mappings>
<action path="/user" type="com.jandar.web.struts.action.UserAction "
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
</action-mappings>
<!-- ================================ Message Resources Definitions -->
<message-resources parameter="messages"/>
</struts-config>
2錛?閫氳繃struts-config.xml鎶妔truts鍜宻pring緇撳悎璧鋒潵
UserAction.java涓殑UserManager闇瑕侀氳繃渚濊禆娉ㄥ叆錛岄氳繃plug-in鎶鏈皢spring鍔犲埌struts涓紝鍦╯truts-config.xml涓鍔犱竴涓嬩唬鐮?br><plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml,
/WEB-INF/action-servlet.xml"/>
</plug-in>
璁﹕truts鍚姩鍚屾椂鍒濆鍖杝pring錛岃鍙杝pring鐨勯厤緗枃浠禷pplicationContext.xml,騫朵笖鎶妔truts鐨刟ction涔熶氦緇檚pring綆$悊錛屾妸action閰嶇疆鍒癮ction-servlet.xml涓?br>鏂板緩action-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"<beans>
<bean name="/user" class="com.jandar.web.struts.action.UserAction" singleton="false">
<property name="userManager"><ref bean="userManager"/></property>
</bean>
</beans>
鍚屾椂灝哸ction鏄犲皠鍒皁rg.springframework.web.struts.DelegatingActionProxy鍗充慨鏀?br><action path="/user" type="org.springframework.web.struts.DelegatingActionProxy"
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
3錛?鏂板緩web.xml閰嶇疆鏂囦歡
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="
xmlns:xsi="
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file>index.jsp</welcome-file> </welcome-file-list> 4錛?鏂板緩index.jsp,userList.jsp,userForm.jsp <%@ taglib uri="
<%@ taglib uri="
<%@ taglib uri="
<%@ taglib uri="
<%@ taglib uri="
<%@ taglib uri="<html:html locale="true"> <head> <html:base /> </head> <html:link href="user.do?method=list">List all user</html:link> </body> </html:html> userForm.jsp <td><bean:write name="user" property="lastName"/></td></tr>
<servlet-mapping>
<welcome-file-list>
</web-app>
index.jsp
<%@ page language="java"%>
<title>index.jsp</title>
<body>
<%@ page language="java"%>
<%@ taglib uri="<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
<html:base />
<title>userform.jsp</title>
</head>
<body>
<html:form action="user.do?method=save" method="post" focus="id">
<html:hidden property="user.id"/>
<table border="0">
<tr>
<td>id:</td>
<td><html:text property="user.firstname"/></td>
</tr>
<tr>
<td>lastname:</td>
<td><html:text property="user.lastname" /></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit property="tijiao"/></td>
</tr>
</table>
</html:form>
</body>
</html:html>
userList.jsp
<%@ page language="java"%>
<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<html:html locale="true">
<head>
<html:base />
<title>userList.jsp</title>
</head>
<body>
This a struts page. <br>
<table class="list">
<thead>
<tr>
<th>id</th>
<th>firstName</th>
<th>lastName</th>
</tr>
</thead>
<tbody>
<logic:iterate id="user" name="users">
<tr>
<td>
<a href="user.do?method=edit&id=<bean:write name="user" property="id"/>"><bean:write name="user" property="id"/></a>
</td>
<td><bean:write name="user" property="firstName"/></td>
</logic:iterate>
</tbody>
</table>
</body>
</html:html>
]]>
<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration. -->
<!-- Created Mon Jul 24 11:48:15 CST 2006 -->
<hibernate-mapping package="">
<class name="AppUser" table="app_user">
<id name="id" column="id" type="integer">
<generator class="identity"/>
</id>
<property name="firstName" column="firstname" type="string" not-null="true" />
<property name="lastName" column="lastname" type="string" />
</class>
</hibernate-mapping>
2錛庡湪com.jandar.model涓嬪垎鍒緩 BaseObject.java 鍜孶ser.java
package com.jandar.model;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class BaseObject implements Serializable {
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
package com.jandar.model;
public class User extends BaseObject {
private Long id;
private String firstName;
private String lastName;
/**
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(Long id) {
this.id = id;
}
public void getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
鍒涘緩DAO錛岃闂璞?
1錛?鍦╯rc/com.jandar.service.dao鏂板緩IDAO.java鎺ュ彛錛屾墍鏈夌殑DAO閮界戶鎵胯鎺ュ彛
package com.jandar.service.dao;
public interface IDAO {
}
2錛?鍦╯rc/com.jandar.service.dao涓嬫柊寤篒UserDAO.java鎺ュ彛
package com.jandar.service.dao;
import java.util.List;
public interface IUserDAO extends IDAO {
List getUsers();
User getUser(Integer userid);
void saveUser(User user);
void removeUser(Integer id);
}
璇ユ帴鍙f彁渚涗簡璁塊棶瀵硅薄鐨勬柟娉曪紝
3錛?鍦╯rc/com.jandar.service.dao.hibernate涓嬫柊寤篣serDAOHiberante.java
package com.jandar.service.dao.hibernate;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;
import com.jandar.model.User;
import com.jandar.service.dao.IUserDAO;
public class UserDaoHibernate extends HibernateDaoSupport implements IUserDAO {
private Log log=LogFactory.getLog(UserDaoHibernate.class);
/* 錛堥潪 Javadoc錛?
* @see com.jandar.dao.IUserDAO#getUsers()
*/
public List getUsers() {
return getHibernateTemplate().find("from User");
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.dao.IUserDAO#getUser(java.lang.Long)
*/
public User getUser(Integer id) {
// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴
return (User) getHibernateTemplate().get(User.class,id);
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.dao.IUserDAO#saveUser(com.jandar.model.User)
*/
public void saveUser(User user) {
log.debug("xxxxxxx");
System.out.println("yyyy");
getHibernateTemplate().saveOrUpdate(user);
if(log.isDebugEnabled())
{
log.debug("userId set to "+user.getId());
}
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.dao.IUserDAO#removeUser(java.lang.Long)
*/
public void removeUser(Integer id) {
Object user=getHibernateTemplate().load(User.class,id);
getHibernateTemplate().delete(user);
if(log.isDebugEnabled()){
log.debug("del user "+id);
}
}
}
鍦ㄨ繖涓被涓疄鐜頒簡IUserDAO鎺ュ彛鐨勬柟娉曪紝騫朵笖緇ф壙浜咹ibernateDAOSupport綾匯傝繖涓被鐨勪綔鐢ㄦ槸閫氳繃hibernate璁塊棶銆佹搷浣滃璞★紝榪涜屽疄鐜板鏁版嵁搴撶殑鎿嶄綔銆?
鍒涘緩涓氬姟灞傦紝澹版槑浜嬪姟
涓氬姟灞備富瑕佸鐞嗕笟鍔¢昏緫錛屾彁渚涚粰web灞傚弸濂界殑璁塊棶鎺ュ彛鍜屽疄鐜拌闂瓺AO灞傘傜敤涓氬姟灞傜殑鍙︿竴涓ソ澶勬槸錛屽彲浠ラ傚簲鏁版嵁璁塊棶灞備粠Hibernate鎶鏈漿縐誨埌鍏朵粬鏁版嵁璁塊棶鎶鏈?
1錛?鍦╯rc/com.jandar.service涓嬫柊寤轟竴涓狪UserManager鎺ュ彛錛岃鎺ュ彛鏈夊嚑涔庝簬IUserDAO鍚屾牱鐨勬柟娉曪紝涓嶅悓鐨勬槸澶勭悊鍙傛暟錛屽簲涓篒UserManager鏄緵web灞傝闂殑銆?
package com.jandar.service;
import java.util.List;
import com.jandar.model.User;
public interface IUserManager {
User getUser(String userid);
List getUsers();
User saveUser(User user);
void removeUser(String userid);
}
2錛?鍦╯rc/com.jandar.service.spring涓嬫柊寤篒UserManager瀹炵幇綾伙紝UserManager.java
package com.jandar.service.spring;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jandar.model.User;
import com.jandar.service.IUserManager;
import com.jandar.service.dao.IUserDAO;
public class UserManager implements IUserManager {
/* 錛堥潪 Javadoc錛?
* @see com.jandar.service.IUserManager#getUser(java.lang.String)
*/
private static Log log=LogFactory.getLog(UserManager.class);
public IUserDAO userDao;
/**
* @return 榪斿洖 userDao銆?
*/
public IUserDAO getUserDao() {
return userDao;
}
/**
* @param userDao 瑕佽緗殑 userDao銆?
*/
public void setUserDao(IUserDAO userDao) {
this.userDao = userDao;
}
public User getUser(String userid) {
User user=userDao.getUser(Integer.valueOf(userid));
if(user==null){
log.warn(" user id "+userid+" not found in database");
}
if(log.isDebugEnabled()){
log.debug("get a user with id "+userid);
}
return user;
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.service.IUserManager#getUsers()
*/
public List getUsers() {
// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴
return userDao.getUsers();
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.service.IUserManager#saveUser(com.jandar.model.User)
*/
public User saveUser(User user) {
// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴
userDao.saveUser(user);
return user;
}
/* 錛堥潪 Javadoc錛?
* @see com.jandar.service.IUserManager#removeUser(java.lang.String)
*/
public void removeUser(String userid) {
// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴
userDao.removeUser(Integer.valueOf(userid));
}
}
UserManager.java閫氳繃璁塊棶dao鎺ュ彛瀹炵幇涓氬姟閫昏緫鍜屾暟鎹簱鎿嶄綔銆傚悓鏃惰綾諱腑鎻愪緵浜唖et鏂規硶錛岃繍鐢ㄤ簡Spring鐨勪緷璧栨敞鍏ユ満鍒躲備絾灝氭湭浣跨敤spring鐨凙OP鍜屽0鏄庝簨鍔°?
閰嶇疆applicationContext.xml
鍦╓EB-INF 涓嬫柊寤篴pplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
銆銆Spring 妗嗘灦鎻愪緵浜嗘瀯寤?Web 搴旂敤紼嬪簭鐨勫叏鍔熻兘 MVC 妯″潡銆備嬌鐢?Spring 鍙彃鍏ョ殑 MVC 鏋舵瀯錛屽彲浠ラ夋嫨鏄嬌鐢ㄥ唴緗殑 Spring Web 妗嗘灦榪樻槸 Struts 榪欐牱鐨?Web 妗嗘灦銆傞氳繃絳栫暐鎺ュ彛錛孲pring 妗嗘灦鏄珮搴﹀彲閰嶇疆鐨勶紝鑰屼笖鍖呭惈澶氱瑙嗗浘鎶鏈紝渚嬪 JavaServer Pages錛圝SP錛夋妧鏈乂elocity銆乀iles銆乮Text 鍜?POI銆係pring MVC 妗嗘灦騫朵笉鐭ラ亾浣跨敤鐨勮鍥撅紝鎵浠ヤ笉浼氬己榪偍鍙嬌鐢?JSP 鎶鏈係pring MVC 鍒嗙浜嗘帶鍒跺櫒銆佹ā鍨嬪璞°佸垎媧懼櫒浠ュ強澶勭悊紼嬪簭瀵硅薄鐨勮鑹詫紝榪欑鍒嗙璁╁畠浠洿瀹規槗榪涜瀹氬埗銆?/p>
銆銆Spring 鐨?Web MVC 妗嗘灦鏄洿緇?DispatcherServlet 璁捐鐨勶紝瀹冩妸璇鋒眰鍒嗘淳緇欏鐞嗙▼搴忥紝鍚屾椂甯︽湁鍙厤緗殑澶勭悊紼嬪簭鏄犲皠銆佽鍥捐В鏋愩佹湰鍦拌璦銆佷富棰樿В鏋愪互鍙婁笂杞芥枃浠舵敮鎸併傞粯璁ょ殑澶勭悊紼嬪簭鏄潪甯哥畝鍗曠殑 Controller 鎺ュ彛錛屽彧鏈変竴涓柟娉?ModelAndView handleRequest(request, response)銆係pring 鎻愪緵浜嗕竴涓帶鍒跺櫒灞傛緇撴瀯錛屽彲浠ユ淳鐢熷瓙綾匯傚鏋滃簲鐢ㄧ▼搴忛渶瑕佸鐞嗙敤鎴瘋緭鍏ヨ〃鍗曪紝閭d箞鍙互緇ф壙 AbstractFormController銆傚鏋滈渶瑕佹妸澶氶〉杈撳叆澶勭悊鍒頒竴涓〃鍗曪紝閭d箞鍙互緇ф壙 AbstractWizardFormController銆?/p>
銆銆紺轟緥搴旂敤紼嬪簭鏈夊姪浜庣洿瑙傚湴瀛︿範榪欎簺鐗規с傞摱琛屽簲鐢ㄧ▼搴忓厑璁哥敤鎴鋒绱粬浠殑甯愭埛淇℃伅銆傚湪鏋勫緩閾惰搴旂敤紼嬪簭鐨勮繃紼嬩腑錛屽彲浠ュ鍒板浣曢厤緗?Spring MVC 妗嗘灦鍜屽疄鐜版鏋剁殑瑙嗗浘灞傦紝瑙嗗浘灞傚寘鎷?JSTL 鏍囪錛堢敤浜庢樉紺鴻緭鍑虹殑鏁版嵁錛夊拰JavaServer Pages 鎶鏈?/p>
銆銆閰嶇疆 Spring MVC
銆銆瑕佸紑濮嬫瀯寤虹ず渚嬪簲鐢ㄧ▼搴忥紝璇烽厤緗?Spring MVC 鐨?DispatcherServlet銆傝鍦?web.xml 鏂囦歡涓敞鍐屾墍鏈夐厤緗傛竻鍗?1 鏄劇ず浜嗗浣曢厤緗?sampleBankingServlet銆?/p>
娓呭崟 1. 閰嶇疆 Spring MVC DispatcherServlet
<servlet>
<servlet-name>sampleBankingServlet</servlet-name>
<servlet-class>
org.springframework.we.servlet.DispatcherServlet
<servlet-class>
<load-on-startup>1<load-on-startup>
<servlet>
銆銆DispatcherServlet 浠庝竴涓?XML 鏂囦歡瑁呭叆 Spring 搴旂敤紼嬪簭涓婁笅鏂囷紝XML 鏂囦歡鐨勫悕縐版槸 servlet 鐨勫悕縐板悗闈㈠姞涓?-servlet 銆傚湪榪欎釜紺轟緥涓紝DispatcherServlet 浼氫粠 sampleBankingServlet-servlet.xml 鏂囦歡瑁呭叆搴旂敤紼嬪簭涓婁笅鏂囥?
銆銆閰嶇疆搴旂敤紼嬪簭鐨?URL
銆銆涓嬩竴姝ユ槸閰嶇疆鎯寵 sampleBankingServlet 澶勭悊鐨?URL銆傚悓鏍鳳紝榪樻槸瑕佸湪 web.xml 涓敞鍐屾墍鏈夎繖浜涗俊鎭?/p>
娓呭崟 2. 閰嶇疆鎯寵澶勭悊鐨?URL
<servlet-mapping>
<servlet-name> sampleBankingServlet<servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
銆銆瑁呭叆閰嶇疆鏂囦歡
銆銆涓嬮潰錛岃鍏ラ厤緗枃浠躲備負浜嗗仛鍒拌繖鐐癸紝璇蜂負 Servlet 2.3 瑙勮寖娉ㄥ唽 ContextLoaderListener 鎴栦負 Servlet 2.2 鍙婁互涓嬬殑瀹瑰櫒娉ㄥ唽 ContextLoaderServlet銆備負浜嗕繚闅滃悗鍚戝吋瀹規э紝璇風敤 ContextLoaderServlet銆傚湪鍚姩 Web 搴旂敤紼嬪簭鏃訛紝ContextLoaderServlet 浼氳鍏?Spring 閰嶇疆鏂囦歡銆傛竻鍗?3 娉ㄥ唽浜?ContextLoaderServlet銆?/p>
娓呭崟 3. 娉ㄥ唽 ContextLoaderServlet
<servlet>
<servlet-name>context>servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
銆銆contextConfigLocation 鍙傛暟瀹氫箟浜嗚瑁呭叆鐨?Spring 閰嶇疆鏂囦歡錛屽涓嬮潰鐨?servlet 涓婁笅鏂囨墍紺恒?/p>
<context-param>
<param-value>contextConfigLocation</param-value>
<param-value>/WEB-INF/sampleBanking-services.xml</param-value>
</context-param>
銆銆sampleBanking-services.xml 鏂囦歡浠h〃紺轟緥閾惰搴旂敤紼嬪簭鏈嶅姟鐨勯厤緗拰 bean 閰嶇疆銆傚鏋滄兂瑁呭叆澶氫釜閰嶇疆鏂囦歡錛屽彲浠ュ湪 <param-value> 鏍囪涓敤閫楀彿浣滃垎闅旂銆?/p>
銆銆Spring MVC 紺轟緥
銆銆紺轟緥閾惰搴旂敤紼嬪簭鍏佽鐢ㄦ埛鏍規嵁鎯熶竴鐨?ID 鍜屽彛浠ゆ煡鐪嬪笎鎴蜂俊鎭傝櫧鐒?Spring MVC 鎻愪緵浜嗗叾浠栭夐」錛屼絾鏄垜灝嗛噰鐢?JSP 鎶鏈綔涓鴻鍥鵑〉闈€傝繖涓畝鍗曠殑搴旂敤紼嬪簭鍖呭惈涓涓鍥鵑〉鐢ㄤ簬鐢ㄦ埛杈撳叆錛圛D 鍜屽彛浠わ級錛屽彟涓欏墊樉紺虹敤鎴風殑甯愭埛淇℃伅銆?/p>
銆銆鎴戜粠 LoginBankController 寮濮嬶紝瀹冩墿灞曚簡 Spring MVC 鐨?SimpleFormController銆係impleFormContoller 鎻愪緵浜嗘樉紺轟粠 HTTP GET 璇鋒眰鎺ユ敹鍒扮殑琛ㄥ崟鐨勫姛鑳斤紝浠ュ強澶勭悊浠?HTTP POST 鎺ユ敹鍒扮殑鐩稿悓琛ㄥ崟鏁版嵁鐨勫姛鑳姐侺oginBankController 鐢?AuthenticationService 鍜?AccountServices 鏈嶅姟榪涜楠岃瘉錛屽茍鎵ц甯愭埛媧誨姩銆?#8220; 閰嶇疆瑙嗗浘灞炴?”涓鑺備腑鐨勬竻鍗?5 鎻忚堪浜嗗浣曟妸 AuthenticationService 鍜?AccountServices 榪炴帴鍒?LoginBankController銆?娓呭崟 4 鏄劇ず浜?LoginBankController 鐨勪唬鐮併?/p>
娓呭崟 4. LoginBankController 鎵╁睍 SimpleFormController
public class LoginBankController extends SimpleFormController {
public LoginBankController(){
}
protected ModelAndView onSubmit(Object command) throws Exception{
LoginCommand loginCommand = (LoginCommand) command;
authenticationService.authenticate(loginCommand);
AccountDetail accountdetail = accountServices.getAccountSummary(loginCommand.getUserId());
return new ModelAndView(getSuccessView(),"accountdetail",accountdetail);
}
private AuthenticationService authenticationService;
private AccountServices accountServices;
public AccountServices getAccountServices() {
return accountServices;
}
public void setAccountServices(AccountServices accountServices) {
this.accountServices = accountServices;
}
public AuthenticationService getAuthenticationService() {
return authenticationService;
}
public void setAuthenticationService(
AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
}
銆銆閰嶇疆瑙嗗浘灞炴?/strong>
銆銆涓嬮潰錛屽繀欏繪敞鍐屽湪鎺ユ敹鍒?HTTP GET 璇鋒眰鏃舵樉紺虹殑欏甸潰銆傚湪 Spring 閰嶇疆涓敤 formView 灞炴ф敞鍐岃繖涓〉闈紝濡傛竻鍗?5 鎵紺恒俿ucessView 灞炴т唬琛ㄨ〃鍗曟暟鎹彁浜よ屼笖 doSubmitAction() 鏂規硶涓殑閫昏緫鎴愬姛鎵ц涔嬪悗鏄劇ず鐨勯〉闈€俧ormView 鍜?sucessView 灞炴ч兘浠h〃琚畾涔夌殑瑙嗗浘鐨勯昏緫鍚嶇О錛岄昏緫鍚嶇О鏄犲皠鍒板疄闄呯殑瑙嗗浘欏甸潰銆?/p>
娓呭崟 5. 娉ㄥ唽 LoginBankController
<bean id="loginBankController"
class="springexample.controller.LoginBankController">
<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>loginCommand</value></property>
<property name="commandClass">
<value>springexample.commands.LoginCommand</value>
</property>
<property name="authenticationService">
<ref bean="authenticationService" />
</property>
<property name="accountServices">
<ref bean="accountServices" />
</property>
<property name="formView">
<value>login</value>
</property>
<property name="successView">
<value>accountdetail</value>
</property>
</bean>
銆銆commandClass 鍜?commandName 鏍囪鍐沖畾灝嗗湪瑙嗗浘欏甸潰涓椿鍔ㄧ殑 bean銆備緥濡傦紝鍙互閫氳繃 login.jsp 欏甸潰璁塊棶 loginCommand bean錛岃繖涓〉闈㈡槸搴旂敤紼嬪簭鐨勭櫥褰曢〉闈€備竴鏃︾敤鎴鋒彁浜や簡鐧誨綍欏甸潰錛屽簲鐢ㄧ▼搴忓氨鍙互浠?LoginBankController 鐨?onSubmit() 鏂規硶涓殑鍛戒護瀵硅薄媯绱㈠嚭琛ㄥ崟鏁版嵁銆?/p>
銆銆瑙嗗浘瑙f瀽鍣?/strong>
銆銆Spring MVC 鐨?瑙嗗浘瑙f瀽鍣?鎶婃瘡涓昏緫鍚嶇О瑙f瀽鎴愬疄闄呯殑璧勬簮錛屽嵆鍖呭惈甯愭埛淇℃伅鐨?JSP 鏂囦歡銆傛垜鐢ㄧ殑鏄?Spring 鐨?InternalResourceViewResolver錛屽 娓呭崟 6 鎵紺恒?/p>
娓呭崟 6. InternalResourceViewResolver
<bean id="view-Resolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix"><value>/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
銆銆鍥犱負鎴戝湪 JSP 欏甸潰涓嬌鐢ㄤ簡 JSTL 鏍囪錛屾墍浠ョ敤鎴風殑鐧誨綍鍚嶇О瑙f瀽鎴愯祫婧?/jsp/login.jsp錛岃?viewClass 鎴愪負 JstlView銆?/p>
銆銆楠岃瘉鍜屽笎鎴鋒湇鍔?/strong>
銆銆灝卞儚鍓嶉潰鎻愬埌鐨勶紝LoginBankController 鍐呴儴榪炴帴浜?Spring 鐨?AccountServices 鍜?AuthenticationService銆侫uthenticationService 綾誨鐞嗛摱琛屽簲鐢ㄧ▼搴忕殑楠岃瘉銆侫ccountServices 綾誨鐞嗗吀鍨嬬殑閾惰鏈嶅姟錛屼緥濡傛煡鎵句氦鏄撳拰鐢墊眹銆傛竻鍗?7 鏄劇ず浜嗛摱琛屽簲鐢ㄧ▼搴忕殑楠岃瘉鍜屽笎鎴鋒湇鍔$殑閰嶇疆銆?/p>
娓呭崟 7. 閰嶇疆楠岃瘉鍜屽笎鎴鋒湇鍔?/p>
<beans>
<bean id="accountServices"
class="springexample.services.AccountServices">
</bean>
<bean id="authenticationService"
class="springexample.services.AuthenticationService">
</bean>
</beans>
銆銆浠ヤ笂鏈嶅姟鍦?sampleBanking-services.xml 涓敞鍐岋紝鐒跺悗瑁呭叆 web.xml 鏂囦歡涓紝灝卞儚 鍓嶉潰璁ㄨ鐨勯偅鏍楓傛帶鍒跺櫒鍜屾湇鍔¢厤緗ソ鍚庯紝榪欎釜綆鍗曠殑搴旂敤紼嬪簭灝卞畬鎴愪簡銆傜幇鍦ㄦ垜浠潵鐪嬬湅閮ㄧ講鍜屾祴璇曞畠鏃朵細鍙戠敓浠涔?
銆銆閮ㄧ講搴旂敤紼嬪簭
銆銆鎶婄ず渚嬪簲鐢ㄧ▼搴忛儴緗插湪 Tomcat servlet 瀹瑰櫒涓俆omcat 鏄?Java Servlet 鍜?Java ServerPagest 鎶鏈殑瀹樻柟鍙傝冨疄鐜頒腑浣跨敤鐨?servlet 瀹瑰櫒銆傚鏋滀互鍓嶆病榪欎箞鍋氳繃錛岃 涓嬭澆 jakarta-tomcat-5.0.28.exe 騫惰繍琛屽畠鎶?Tomcat 瀹夎鍒拌嚜宸卞枩嬈㈢殑浠諱綍浣嶇疆錛屼緥濡?c:\tomcat5.0銆?/p>
銆銆鎺ヤ笅鏉ワ紝涓嬭澆紺轟緥浠g爜 騫墮噴鏀懼埌椹卞姩鍣紙渚嬪 c:\ 錛変笂銆傚垱寤轟簡 Spring 欏圭洰鐨勬枃浠跺す涔嬪悗錛屾墦寮瀹冨茍鎶?spring-banking 瀛愭枃浠跺す鎷瘋礉鍒?c:\tomvat5.0\webapps銆俿pring-banking 鏂囦歡澶規槸涓涓?Web 妗f錛岄噷闈㈠寘鍚?Spring MVC 紺轟緥搴旂敤紼嬪簭銆俵ib 鏂囦歡澶瑰寘鍚簲鐢ㄧ▼搴忛渶瑕佺殑 Spring 妗嗘灦銆佷笌Spring 鐩稿叧鐨?MVC 搴撲互鍙?JSTL 鏍囪搴撳拰 jar 鏂囦歡銆?/p>
銆銆瑕佸惎鍔?Tomcat 鏈嶅姟鍣紝璇蜂嬌鐢ㄤ互涓嬪懡浠わ細
銆銆cd bin C:\Tomcat 5.0\bin> catalina.bat start
銆銆Tomcat 搴斿綋鍚姩騫墮儴緗?Spring MVC 紺轟緥搴旂敤紼嬪簭銆?/p>
銆銆嫻嬭瘯搴旂敤紼嬪簭
銆銆瑕佹祴璇曞簲鐢ㄧ▼搴忥紝璇鋒墦寮 Web 嫻忚鍣紝鎸囧悜 http://localhost:tomcatport/springbanking 騫剁敤 Tomcat 鏈嶅姟鍣ㄥ疄闄呰繍琛岀殑绔彛鏇挎崲 tomcatport銆傚簲褰撶湅鍒板浘 1 鎵紺虹殑鐧誨綍灞忓箷銆傝緭鍏ョ敤鎴?ID “admin”鍜屽彛浠?#8220;password”錛屽茍鎸変笅鐧誨綍鎸夐挳銆傚叾浠栫敤鎴?ID 鎴栧彛浠や細閫犳垚鏉ヨ嚜楠岃瘉鏈嶅姟鐨勯敊璇?/p>
鍥?1. Spring MVC 紺轟緥鐧誨綍灞忓箷
銆銆鐧誨綍鎴愬姛涔嬪悗錛屼細鐪嬪埌鍥?2 鎵紺虹殑甯愭埛緇嗚妭欏甸潰銆?/p>
鍥?2. Spring MVC 紺轟緥甯愭埛緇嗚妭欏甸潰
Spring MVC妗嗘灦鐨勯珮綰ч厤緗?br>http://dev2dev.bea.com.cn/techdoc/2006068810.html