版权声明:程序猴jwang版权所有 https://blog.csdn.net/qq_21046965/article/details/86689688
前言
本章讲解Struts2整合Spring
方法
1.概念
首先,我们知道SpringMVC框架的简洁性和兼容性都要比Struts2要好的多,这也是为什么我只讲解了这么一点Struts2的内容,还有相当一部分的Struts2的内容我没有涉及到,还请大家注意!我们日后接触的还是SpringMVC居多!
2.准备工作
如果需要Struts2整合Spring,那么和使用注解一样,我们需要引入一个插件的jar包
2.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置Struts2分发器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- 加载Spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置欢迎页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
具体的spring配置文件的内容请参照spring章节进行学习!
3.SMS登录功能的实现
配置登录的Action
package cn.edu.ccut.action;
import cn.edu.ccut.service.StudentService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
@ParentPackage("struts-default")
@Namespace("/")
public class LoginAction extends ActionSupport {
private String username;
private String password;
@Autowired
private StudentService studentService;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Action(value = "login", results = {
@Result(name = "success", location = "/admin/list/welcome.jsp"),
@Result(name = "error", location = "/admin/login/login.jsp")})
public String login(){
boolean flag = studentService.login(username, password);
if (flag) {
return "success";
}else {
return "error";
}
}
}
如此同样可以实现我们之前SMS的登录操作,但是大家觉得和SpringMVC比哪个简单啊!
很明显,Struts2居于下风,SpringMVC更胜一筹!!!