My linux world » Java Spring – Struts

Java Spring - Struts


Prerequistes

Please read : Java spring – quickstart

Configuration

If you use maven, add this to your pom.xml

<dependencies>
(...)
 
  <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>${struts.version}</version>
  </dependency>
 
  <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-convention-plugin</artifactId>
    <version>${struts.version}</version>
  </dependency>
 
(...)
</dependencies>

Update WebConfig to add struts filter

public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
(...)
 
@Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        return new Filter[] { characterEncodingFilter, new StrutsPrepareAndExecuteFilter()};
    }
 
(...)
}

Now create an Action :

@Action("/helloworld")
@ResultPath("/WEB-INF/views")
@Result(name = "success", location = "helloworld.jsp")
public class HelloWorldAction extends ActionSupport {
 
	/**
	 * 
	 */
	private static final long serialVersionUID = -5513322593080313637L;
 
	private String message = "Hello world from struts action !";
 
	public String execute() throws Exception {
		return "success";
	}
 
	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}
 
	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}	
}

And create the file ./src/main/webapp/WEB-INF/views/helloworld.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
 
	<br>
	<div style="text-align: center">
		<h2>Message from spring controller :</h2>
		<h3 id="helloworld-text"><s:property value="message"/></h3>
	</div>
 
</body>
</html>

Finally go to http://localhost:8080/helloworld.


Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.