博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(五)sturts2+spring整合
阅读量:7081 次
发布时间:2019-06-28

本文共 11200 字,大约阅读时间需要 37 分钟。

 

一、Spring与Struts的整合

1.1:加入Spring的jar包。
1.2:加入Struts的jar包。
1.3:加入Struts与Spring的整合jar//struts2-spring-plugin-2.3.28.jar。  

  •  功能:将Struts中的Action对象交给Spring来管理。Spring可以往Action中依赖注入对象。

1.4 : 配置文件

  web.xml:

spring_struts2_1
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
contextConfigLocation
classpath:spring.xml
encoding
filter.EncodingFilter
encoding
/*
org.springframework.web.context.ContextLoaderListener
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
  • struts.xml
main.jsp
  • 注意配置<constant name="struts.objectFactory" value="spring"></constant>
  • <constant name="struts.objectFactory.spring.autoWire" value="name"></constant> 这两个常量,第一个用于struts的action交给spring管理,并且spring注入的方式是根据名称来注入,比如TesetAction中有一个成员属性UserService userService(必须有set方法) 然后在spring.xml中配置一个bean 的id为"userService"的(必须与acton中的成员属性名一致),这样spring.xml的bean会自动关联到TestAction的userService里了。

spring.xml

 

1.5 写action、servlet、dao等

 

二、案例

  • 配置文件:web.xml、struts.xml、spring.xml如上面所述。
  • index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%String path=request.getContextPath(); %>
Insert title here spring和struts2整合
  • TestAction.java
package action;import java.util.List;import org.apache.struts2.components.ActionComponent;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.util.ValueStack;import bean.UserBean;import service.UserServiceI;import util.BaseAction;public class TestAction extends BaseAction{    private UserServiceI userService;        public void setUserService(UserServiceI userService) {        this.userService = userService;    }    @Override    public String execute() throws Exception {            return null;    }        public String list(){        List
userList=userService.getUserList(); ValueStack valuestack=ActionContext.getContext().getValueStack(); valuestack.set("userList", userList); return "main"; } }
 
  • UserServiceI .java
package service;import java.util.List;import bean.UserBean;public interface UserServiceI {    List
getUserList();}
  • UserServiceImpl.java
package service;import java.util.List;import bean.UserBean;import dao.UserDao;public class UserServiceImpl implements UserServiceI {        private UserDao userdao;        public void setUserdao(UserDao userdao) {        this.userdao = userdao;    }    public List
getUserList() { return userdao.getUserList(); }}
  • UserDao.java
package dao;import java.util.List;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.support.JdbcDaoSupport;import bean.UserBean;public class UserDao extends JdbcDaoSupport{    public List
getUserList() { String sql="select * from user"; List
userList=this.getJdbcTemplate().query(sql, new BeanPropertyRowMapper
(UserBean.class)); return userList; }}
  • UserBean.java
package bean;public class UserBean {    private String userName;    private int age;    private String sex;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }}
  • BaseAction.java
package util;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;import org.apache.struts2.util.ServletContextAware;import com.opensymphony.xwork2.ActionSupport;public abstract class BaseAction extends ActionSupport implements        ServletRequestAware, ServletResponseAware, ServletContextAware {    protected HttpServletRequest request;    protected HttpServletResponse response;    protected ServletContext context;    protected HttpSession session;    protected PrintWriter out;    public void setServletRequest(HttpServletRequest request) {        this.request = request;        if (this.request != null) {            this.session = this.request.getSession();        }    }    public void setServletResponse(HttpServletResponse response) {        this.response = response;        if (this.response != null) {            try {                this.response.setContentType("text/html");                this.out = this.response.getWriter();            } catch (IOException e) {                e.printStackTrace();            }        }    }    public void setServletContext(ServletContext context) {        this.context = context;    }    public abstract String execute() throws Exception;}

EncodingFilter.java

package filter;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;/** * 此过滤器用于解决get和post请求中问乱码的问题。 */public class EncodingFilter implements Filter {    public EncodingFilter() {          }    public void destroy() {            }/** *     要解决乱码问题首先区别对待POST方法和GET方法, *     1.如果是POST方法,则用request.setCharacterEncoding("UTF-8"); 即可 *     2.如果是GET方法,则麻烦一些,需要用decorator设计模式包装request对象来解决 */    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {         HttpServletRequest request=(HttpServletRequest)req;         HttpServletResponse response=(HttpServletResponse)res;                 //获取request请求是get还是post         String method=request.getMethod();                 if(method.equals("GET") || method.equals("get")){  //注意大小写都要判断,一般来说是大写的GET             /**              * request请求为get请求,则用包装类对request对象的getParameter方法进行覆盖。              */             response.setContentType("text/html;charset=UTF-8");             MyGetHttpServletRequestWrapper requestWrapper=new MyGetHttpServletRequestWrapper(request);             chain.doFilter(requestWrapper, response);                                   }else{             //post请求              response.setContentType("text/html;charset=UTF-8");             request.setCharacterEncoding("UTF-8");             chain.doFilter(request, response);                      }    }    public void init(FilterConfig fConfig) throws ServletException {    }}class MyGetHttpServletRequestWrapper extends HttpServletRequestWrapper{        HttpServletRequest request;    public MyGetHttpServletRequestWrapper(HttpServletRequest request) {        super(request);        this.request=request;            }    /**     *       servlet API中提供了一个request对象的Decorator设计模式的默认实现类HttpServletRequestWrapper,     *               (HttpServletRequestWrapper类实现了request接口中的所有方法,但这些方法的内部实现都是仅仅调用了一下所包装的的     *               request对象的对应方法) 以避免用户在对request对象进行增强时需要实现request接口中的所有方法。     *               所以当需要增强request对象时,只需要写一个类继承HttpServletRequestWrapper类,然后在重写需要增强的方法即可     * 具体步骤:      *1.实现与被增强对象相同的接口       *2、定义一个变量记住被增强对象     *3、定义一个构造函数,接收被增强对象 4、覆盖需要增强的方法 5、对于不想增强的方法,直接调用被增强对象(目标对象)的方法     */        @Override    public String getParameter(String name) {            String old_value=super.getParameter(name);        String new_value=null;                if(old_value!=null && !old_value.equals("")){            try {                new_value=new String(old_value.getBytes("ISO-8859-1"),"UTF-8");            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }                    }                return new_value;    }    @Override    public String[] getParameterValues(String name) {                String[] old_value=request.getParameterValues(name);        String[] new_value=new String[old_value.length];                if(old_value!=null && !old_value.equals("")){            String temp_value=null;            for(int i=0;i
map = this.request.getParameterMap(); // 接受客户端的数据 Map
newmap = new HashMap(); for (Map.Entry
entry : map.entrySet()) { String name = entry.getKey(); String values[] = entry.getValue(); if (values == null) { newmap.put(name, new String[] {}); continue; } String newvalues[] = new String[values.length]; for (int i = 0; i < values.length; i++) { String value = values[i]; value = new String(value.getBytes("iso8859-1"), this.request.getCharacterEncoding()); newvalues[i] = value; // 解决乱码后封装到Map中 } newmap.put(name, newvalues); } return newmap; } catch (Exception e) { throw new RuntimeException(e); } }}
  • main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%@ taglib prefix="s"  uri="/struts-tags" %>
Insert title here
姓名 年龄 性别

结果:



 

 所有代码都在这里:   (数据库文件user.sql在webContent里)

 

转载于:https://www.cnblogs.com/shyroke/p/6736411.html

你可能感兴趣的文章
Java:如何检查枚举是否包含给定的字符串?
查看>>
Webstorm/Phpstorm中将ES6文件转为普通js文件
查看>>
为什么Go不支持函数和运算的重载
查看>>
「征文」我和极光有个约会
查看>>
js鼠标滚轮事件
查看>>
java 调用摄像头
查看>>
阿里云maven库地址 和maven跳过测试 和常见maven命令
查看>>
Android网络防火墙实现初探
查看>>
欲保长寿,先补亏损 —胡海牙
查看>>
数据容量进制转换
查看>>
Spring Cloud Zuul过滤器详解
查看>>
使用DOM4J创建一个新的XML文件
查看>>
VIM使用系列:搜索功能
查看>>
SOAP--------Golang对接WebService服务实战
查看>>
7大维度看国外企业为啥选择gRPC打造高性能微服务?
查看>>
初创公司电商系统建立思考
查看>>
微服务框架Spring Cloud介绍 Part2: Spring Cloud与微服务
查看>>
linux系统下设置时间同步
查看>>
dubbo源码学习笔记----整体结构
查看>>
zipfile
查看>>