如果您還沒有這樣做,請查看Spring MVC分步教程。
Spring MVC tutorial
這會給你如何構建一個簡單的Spring MVC Web應用程序的一個很好的例子。
唯一的問題是它沒有涵蓋在Spring 2.5+中使用Annotations。您將不得不等待Spring 3.0 MVC教程發佈,或者親自查閱官方Spring文檔以瞭解如何使用它。
編輯
下面是一個有關控制形式的例子:
注:彈簧3.0.0
你的控制器:
@Controller
@RequestMapping("/blog.htm")
public class BlogController{
// Service layer class
private final BlogManager blogManager;
// Inject the blog manager into the constructor automatically
@Autowired
public BlogController(BlogManager blogManager){
this.blogManager = blogManager
}
// Set up the form and return the logical view name
@RequestMapping(method=RequestMethod.GET)
public String setupForm(ModelMap model){
model.addAttribute(new EntryForm());
return "addBlog";
}
// Executed when posting the form
@RequestMapping(method=RequestMethod.POST)
public String addBlog(@ModelAttribute("entryForm")EntryForm entryForm){
// Read the entry form command object from the form
String text = entryForm.getText();
// Call your service method
blogManager.addEntry(text);
// Usually redirect to a new logical view name
return "redirect:/homepage";
}
}
形式的命令對象:
public class EntryForm{
private String text;
// setters and getters for text
}
這是您的服務層類
public class BlogManager{
private final BlogDAO blogDAO;
@Autowired
public BlogManager(BlogDAO blogDAO){
this.blogDAO = blogDAO;
}
public void addEntry(String text){
int blogID = 100; // simple example id for a blog
Blog blog = blogDAO.findById(blogID);
blog.addEntry(text);
blogDAO.update(blog);
}
}
現在您更新spring.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scan for spring annotations -->
<context:component-scan base-package="test.package"/>
<!-- defined in the xml file and autowired into controllers and services -->
<bean id="blogManager" class="test.package.BlogManager" />
<bean id="blogDAO" class="test.package.dao.BlogDAO" />
<!-- Resolves logical view names to jsps in /WEB-INF/jsp folder -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
請按'向Question'在提出新的問題作爲新問題正確的頂部,只是爲了避免在答案中的噪音:)不要忘記upvote你發現有用的答案,並接受最有用的答案。 – BalusC 2010-01-31 16:27:49