Spring MVC和Struts都是用于构建Java Web应用程序的MVC框架,它们有一些共同点,但也有一些区别。
struts.xml
文件。以下是一个简单的Spring MVC和Struts的示例,演示了它们的基本用法。
// UserController.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getUser(Model model) {
model.addAttribute("username", "John Doe");
return "user";
}
}
<!-- user.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Page</title>
</head>
<body>
<h1>Welcome, ${username}!</h1>
</body>
</html>
// UserAction.java
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private String username;
public String execute() throws Exception {
username = "John Doe";
return SUCCESS;
}
public String getUsername() {
return username;
}
}
<!-- struts.xml -->
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="user" class="UserAction">
<result>/user.jsp</result>
</action>
</package>
</struts>
在这个示例中,Spring MVC使用注解进行配置,而Struts使用XML配置文件。两者都展示了一个简单的用户页面,但Spring MVC更加灵活,而Struts更加约定大于配置。