Struts 2 Hello World Voorbeeld met Annotaties en zonder struts.xml bestand

Dit is het tweede artikel in de reeks van Struts 2 Tutorials. Als je hier direct bent gekomen, raad ik aan om ook de eerdere post te bekijken. Struts 2 Beginners Tutorial In de vorige tutorial hebben we gekeken naar de architectuur van Struts 2, de componenten ervan en een eenvoudige Struts 2-webapplicatie gebouwd met XML-gebaseerde configuratie (struts.xml). In deze tutorial zullen we zien hoe we de struts-configuratiebestand volledig kunnen vermijden door annotaties of benamingconventies te gebruiken.

Struts 2 Conventieconcept

Struts 2 gebruikt twee methodologieën om de actieklassen en resultaatklassen te vinden. We moeten de struts2-convention-plugin API gebruiken om een van deze methodologieën te gebruiken. Als je een normale webapplicatie hebt, kun je het jar-bestand downloaden en het in de lib-map van de webapplicatie plaatsen. Voor Maven-projecten kun je eenvoudig de afhankelijkheid toevoegen zoals hieronder.

<dependency>
	<groupId>org.apache.struts</groupId>
	<artifactId>struts2-convention-plugin</artifactId>
	<version>2.3.15.1</version>
</dependency>
  1. Scannen: In deze methode specificeren we het pakket dat moet worden gescand voor actieklassen. De configuratie moet worden ingesteld in het web.xml-bestand voor de Struts 2-filter, zoals hieronder.

    <filter>
    	<filter-name>struts2</filter-name>
    	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    	<init-param>
    		<param-name>actionPackages</param-name>
    		<param-value>com.journaldev.struts2.actions</param-value>
    	</init-param>
    </filter>
    

    Struts 2 zal actieklassen vinden via de volgende methoden.

    • Elke klasse geannoteerd met @Action of @Actions annotaties.
    • Elke klasse die de Action-interface implementeert of de ActionSupport-klasse uitbreidt.
    • Elke klasse waarvan de naam eindigt op Action en de execute() methode bevat. Voor deze klassen wordt de naamgevingsconventie gebruikt om actie en resultaten te bepalen.
  2. Conventie voor Naamgeving: Struts 2 zal automatisch een actie aanmaken voor klassen waarvan de naam eindigt op Action. De actienaam wordt bepaald door het verwijderen van de Action-suffix en het omzetten van de eerste letter naar kleine letters. Dus als de klassenaam HomeAction is, dan zal de actie “home” zijn. Als deze klassen niet zijn geannoteerd met @Result om het resultaat te specificeren, dan worden de resultaatpagina’s gezocht in de WEB-INF/content map en de naam moet zijn {actie}-{terugkeer_tekst}.jsp. Dus als de HomeAction actieklasse “success” teruggeeft, dan wordt het verzoek doorgestuurd naar de pagina WEB-INF/content/home-success.jsp. Alleen het gebruik van de naamgevingsconventie kan erg verwarrend zijn en we kunnen niet dezelfde JSP-pagina gebruiken voor andere actieklassen. Daarom zouden we moeten proberen dit te vermijden en annotatie-gebaseerde configuratie te gebruiken.

Nu zijn we klaar om onze Hello World Struts 2-toepassing te maken met behulp van annotaties en we zullen geen Struts 2-configuratiebestand hebben. Maak een dynamisch webproject in Eclipse Struts2AnnotationHelloWorld en converteer het naar een Maven-project. Het uiteindelijke project ziet eruit zoals in de onderstaande afbeelding.

Maven-configuratie

We hebben de afhankelijkheden struts2-core en struts2-convention-plugin toegevoegd in het pom.xml-bestand. De uiteindelijke code van pom.xml is:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2AnnotationHelloWorld</groupId>
	<artifactId>Struts2AnnotationHelloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.3.15.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

Implementatiebeschrijving Configuratie

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Struts2AnnotationHelloWorld</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>actionPackages</param-name>
			<param-value>com.journaldev.struts2.actions</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

Merk op dat het init-param element waar we de actieklassenpakket opgeven, zal worden gescand door Struts 2.

Resultaatpagina’s

We hebben drie resultaatpagina’s in onze toepassing. login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login">
	<s:textfield name="name" label="User Name"></s:textfield>
	<s:textfield name="pwd" label="Password" type="password"></s:textfield>
	<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Error Page</title>
</head>
<body>
<h4>User Name or Password is wrong</h4>
<s:include value="login.jsp"></s:include>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="name"></s:property></h3>
</body>
</html>

Laten we nu onze Actieklassen maken die we zullen annoteren om actie- en resultaatpagina’s te configureren.

Actieklassen met annotaties

package com.journaldev.struts2.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

/**
 * An empty class for default Action implementation for:
 * 
 *  <action name="home">
 *		<result>/login.jsp</result>
 *	</action>
 * HomeAction class will be automatically mapped for home.action
 * Default page is login.jsp which will be served to client
 * @author pankaj
 *
 */

@Namespaces(value={@Namespace("/User"),@Namespace("/")})
@Result(location="/login.jsp")
@Actions(value={@Action(""),@Action("home")})
public class HomeAction extends ActionSupport {
}

Merk op dat HomeAction een lege klasse is met als enig doel het verzoek door te sturen naar de pagina login.jsp.

package com.journaldev.struts2.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

/**
 * Notice the @Action annotation where action and result pages are declared
 * Also notice that we don't need to implement Action interface or extend ActionSupport
 * class, only we need is an execute() method with same signature
 * @author pankaj
 *
 */
@Action(value = "login", results = {
		@Result(name = "SUCCESS", location = "/welcome.jsp"),
		@Result(name = "ERROR", location = "/error.jsp") })
@Namespaces(value={@Namespace("/User"),@Namespace("/")})
public class LoginAction {

	public String execute() throws Exception {
		if("pankaj".equals(getName()) && "admin".equals(getPwd()))
		return "SUCCESS";
		else return "ERROR";
	}
	
	//Java Bean om de formulierparameters vast te houden
	private String name;
	private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

Let op het gebruik van de annotaties @Action, @Actions, @Result, @Namespace en @Namespaces, het gebruik spreekt voor zich. Wanneer we onze toepassing uitvoeren, krijgen we de volgende reactiepagina’s. Als je het laatste bericht hebt gelezen waarin we dezelfde toepassing hebben ontwikkeld met de configuratie van struts.xml, zul je merken dat het bijna hetzelfde is. Het enige verschil is de manier waarop we onze toepassingsactieklassen en resultaatpagina’s koppelen.

Download voorbeeldproject Struts2-annotaties

Source:
https://www.digitalocean.com/community/tutorials/struts-2-hello-world-example-with-annotations-and-without-struts-xml-file