如果您还没有这样做,请查看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