Project structure
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<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>/*</url-pattern>
</filter-mapping>
</web-app>
HelloWorldAction.java
package com.example.web.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#Override
public String execute() throws Exception {
System.out.println("Hello from HelloWorldAction class!");
setMessage("Hello World!");
return super.execute();
}
}
hello-world.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello World JSP</title>
</head>
<body>
This is message ${message}
</body>
</html>
When I link to /hello-world I see only "This is message" text but there is no value of ${message}. Also the console doesn't show message by System.out.println(). Hence, HelloWorldAction doesn't call. What do I do wrong?
P.S. I'm using struts2-convention-plugin-2.3.16.3.
After plugging of log4j and viewing of logs this trouble was solved. There wasn't asm libraries at my classpath.
Related
I have a problem with my application. When I send JSON data I get return error 415 - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
I am new in this and I still trying understanding this.
JSP page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
$("#form-temp").submit(function(event) {
event.preventDefault();
searchViaAjax();
});
});
function searchViaAjax() {
var temp = {}
temp["temp"] = $("#temp").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "/update",
data : JSON.stringify(temp),
dataType : 'json',
cache: false,
timeout: 600000,
success : function(temp) {
console.log("SUCCESS: ", data);
//display(temp);
}
});
}
/* function display(temp) {
var json = "<h4>Ajax Response</h4><pre>"+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
} */
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Formularz wprowadzania temperatury</title>
</head>
<body>
<form id="form" method="post" action="update" id="form-temp">
<div><label for="temp">Podaj temperaturę</label></div>
<div><input type="text" name="temp" id="temp"/></div>
<div><button id="sendBtn">Dodaj</button></div>
</form>
<form id="form" method="get" action="stats">
<div><button id="sendBtn">Lista temperatur</button></div>
</form>
</body>
</html>
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import pl.e.rekrutacja.domain.repository.TempRepository;
import pl.e.rekrutacja.model.Temp;
#RestController
public class UpdateController {
#Autowired
private TempRepository tempRepository;
// #ResponseBody
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public String startPage(#RequestBody Temp temp){
tempRepository.addTemp(temp);
return "input_form_temp";
}
}
Model class:
public class Temp {
private double value;
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public Temp(double value) {
super();
this.value = value;
}
}
Application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven enable-matrix-variables="true"/>
<context:component-scan base-package="pl.e.rekrutacja" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id= "tempRepositoryImpl" class="pl.e.rekrutacja.domain.repository.impl.TempRepositoryImpl"/>
</beans>
web.xml:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/webcontext/DispatcherServlet-context.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Your controller is returning a view name to the requested resource. Instead it must return the state of the Temp object in JSON format.
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Temp tempStartPage(#PathVariable(#RequestBody Temp temp)) {
return tempRepository.addTemp(temp);
}
The #ResponseBody will handle the consumes = "application/json", produces = "application/json" .
I am currently developing a Java Web Dynamic Project and I have a Menu bar in my html page. When a user clicks one of the available options appearing on the menu, I want to be able to control which part of the code, in the matching Servlet, will be executed.
Your menu item is associated with a link, similar to this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>simple Servlet</title>
</head>
<body>
<ul>
<li>that Action</li>
<li>this Action</li>
</ul>
</body>
</html>
The deployment descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>de.so.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/action</url-pattern>
</servlet-mapping>
</web-app>
And the servlet code:
package de.so;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class ActionServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
String action = request.getParameter("action");
Writer out=response.getWriter();
if (action == null || action.isEmpty())
{
out.write("Action empty");
}
else if (action.equals("doThis"))
{
out.write("perform this Action");
}
else if (action.equals("doThat"))
{
out.write("perform that Action");
}
}
}
I'm trying to implement a simple guestbook.
When user clicks "Submit", the UnregisteredUserPost CDI bean is supposed to be instantiated. However, instead I get the following exception:
javax.servlet.ServletException: /guestbook.xhtml #11,57 value="#{unregisteredUserPost.name}": Target Unreachable, identifier 'unregisteredUserPost' resolved to null
I will appreaciate if you help me to find the root cause of the problem.
guestbook.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>#{msg.page_title}</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
</h:head>
<h:body>
<h:form>
<h:outputText value="#{msg.your_name} "/>
<h:inputText value="#{unregisteredUserPost.name}"/>
<br/><br/>
<h:outputText value="#{msg.your_msg}"/>
<br/>
<h:inputTextarea
rows="5" cols="100" value="#{unregisteredUserPost.content}"/>
<br/><br/>
<h:commandButton
value="#{msg.submit}" action="#{unregisteredUserPost}"/>
</h:form>
</h:body>
</html>
UnregisteredUserPost.java
package learning.javaee.guestbook;
import java.time.OffsetDateTime;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class UnregisteredUserPost extends AbstractPost {
private String name;
private OffsetDateTime dateTime;
public UnregisteredUserPost() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OffsetDateTime getDateTime() {
return dateTime;
}
public void setDateTime(OffsetDateTime dateTime) {
this.dateTime = dateTime;
}
}
AbstractPost.java
package learning.javaee.guestbook;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Named;
import javax.interceptor.AroundConstruct;
import javax.interceptor.InvocationContext;
#Named
public abstract class AbstractPost implements Serializable {
private String content;
#Inject
private static Logger log;
#AroundConstruct
private void logConstruction(InvocationContext ic) {
try {
ic.proceed();
log.fine("Created " + getClass().getName());
} catch (Exception e) {
log.severe(e.toString());
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>guestbook1</display-name>
<welcome-file-list>
<welcome-file>guestbook.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config 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-facesconfig_2_2.xsd"
version="2.2">
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>MessagesBundle</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
Looks like you're missing bean-discovery-mode="all" in your beans.xml . CDI needs this directive to inject the bean, from your explicit archive.
Related
CDI deployment configuration
I'm currently working on a school project. We have to do a small market website in Java.
I've a small problem. I have an Index.jsp where i want to include a servlet (RandomArticle.jsp). This servlet have a .jsp and a .java and just shuffle a collection and return names.
When I display index.jsp, the html of RandomArticle.jsp is well displayed (so the include is correct) but the returned name are "null".
Here is some code:
Index.jsp (in WebContent of eclipse)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Market</title>
</head>
<body>
<header>
<h1>market 2013</h1>
<h2>Bievenue </h2>
</header>
<nav>
<% String include = "/WEB-INF/RandomArticle.jsp"; %>
<jsp:include page='<%=include%>' />
</nav>
</body>
</html>
RandomArticle.jsp (in WEB-INF):
<h1>Liste des produits EpiMarket</h1>
<%
String productName1 = (String) request.getAttribute("productName1");
String productName2 = (String) request.getAttribute("productName2");
String productName3 = (String) request.getAttribute("productName3");
%>
<p>Acheter <% out.println(productName1); %></p>
<p>Acheter <% out.println(productName2); %></p>
<p>Acheter <% out.println(productName3); %></p>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Market</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>fr.market.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RandomArticle</servlet-name>
<servlet-class>fr.market.servlets.RandomArticle</servlet-class>
</servlet>
</web-app>
and RandomARticle.java
public class RandomArticle extends HttpServlet {
private ArrayList<Object> allProducts;
public String getProductName(int index){
return (((AbstractProduct) allProducts.get(index)).getName());
}
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
ADAO<AbstractProduct> dao = new DAOProduit();
allProducts = ((DAOProduit) dao).getAll();
Collections.shuffle(allProducts);
request.setAttribute("productName1", getProductName(0));
request.setAttribute("productName2", getProductName(1));
request.setAttribute("productName3", getProductName(2));
this.getServletContext().getRequestDispatcher( "/WEB-INF/RandomArticle.jsp" ).forward( request, response );
}
}
I think that the .java is never called, but I don't understand why.
Thanks for your time.
Gilles
I'm following "Struts 2 in Action" book and under the first chapter of that book, there is a sample basic application to be developed. I tried to follow it and the action class is not calling properly. But I can view the success result JSP page. When I use the debug mode and try to debug the execute method of the action class, it is not calling. I'm using struts-2.3.15.1 libraries to develop this application.
My Action class is below :
package manning.chapterTwo;
import org.apache.struts2.config.Result;
import com.opensymphony.xwork2.ActionSupport;
#Result(name="SUCCESS", value="/chapterTwo/HelloWorld.jsp" )
public class AnnotatedHelloWorldAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private static final String GREETING = "Hello ";
public String execute() {
setCustomGreeting( GREETING + getName() );
return "SUCCESS";
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String customGreeting;
public String getCustomGreeting()
{
return customGreeting;
}
public void setCustomGreeting( String customGreeting ){
this.customGreeting = customGreeting;
}
}
JSP Page to get the Input looks like below (NameCollector.jsp) :
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Name Collector</title>
</head>
<body>
<hr>
<h4>Enter your name so that we can customize a greeting just for you!</h4>
<s:form action="annotatedHelloWorld">
<s:textfield name="name" label="Your name"/>
<s:submit/>
</s:form>
<hr>
</body>
</html>
Output JSP :
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<hr>
<h3>Custom Greeting Page</h3>
<h4><s:property value="customGreeting"/></h4>
<hr>
</body>
</html>
web.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts2HelloWorldXML</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>manning</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
How to resolve it?
You should add an action annotation to the action class or method
#ParentPackage("chapterTwo");
#Action(value="HelloWorld", results=#Result(name="SUCCESS", value="/chapterTwo/HelloWorld.jsp" ))
public class AnnotatedHelloWorldAction extends ActionSupport {
Supposed the author either using conventions to map your action or added the action annotation in the errata. Also added the parent package annotation to which the action belongs to. And don't forget to add struts2-convention-plugin to the library set, because it's missed in the examples.