CDI - Java EE Servlet saving variables to a managed bean - html

I have a Java EE class that currently reads info from a form and prints it out.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Response extends HttpServlet
{
String date = "0";
public void init() throws ServletException
{
//Get Election Date from xml
String initial = getInitParameter("electionDate");
date = initial;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
//Get values from form
PrintWriter out = response.getWriter();
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
String address=request.getParameter("address");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zip=request.getParameter("zip");
String phone = request.getParameter("phone");
String affil=request.getParameter("affil");
//Print Summary of Voter Registration
out.println("<html>");
out.println("<head><title>Registration Summary</title></head>");
out.println("<body>");
out.println("<p>Registration Summmary</p>");
out.println("<p>First Name: " + firstName + "</p>");
out.println("<p>Last Name: " + lastName + "</p>");
out.println("<p>Address : " + address + "</p>");
out.println("<p>City : " + city + "</p>");
out.println("<p>State : " + state + "</p>");
out.println("<p>Zip: " + zip + "</p>");
out.println("<p>Phone Number: " + phone + "</p>");
out.println("<p>Affiliation: " + affil + "</p>");
out.println("<p>Next Election Date: " + date + "</p></p>");
out.println("<p>Is the above information correct?</p>");
out.println("<button>Yes</button>");
out.println("<button>No</button>");
out.println("</body></html>");
out.close();
}
}
I want to get the values (firstName, lastName, etc.) from this Java servlet and inject to a bean.
Then when this file calls another servlet I want the values from the bean to be available in that servlet.
I just want to know how to store the variables I created above into a managed bean and then have the other servlet reference and retrieve the variables in that bean.
I have beans.xml, web.xml, pom.xml (I'm using Maven) files set up already.

You cannot simply inject Strings, so you will have to use a qualifier (the simplest one is #Named, see if that is sufficient).
In your servlet, say
#Produces
#Named("foo")
String lastName;
...
void doPost() {
lastName = getParameter(...);
}
and in the target bean, use
#Inject
#Named("foo")
String lastName;
Since you are in a Request-Scope, keep in mind that injecting request-scoped values into longer living instances (EJBs for example) might lead to unpredictable behavior. I seriously doubt that your approach will make you happy. Perhaps you could tell us more about what you are trying to do?

Related

Json cannot add dependencies

Spring Boot version is using version 4.5.2. How can I add Json dependencies to this version?
This error occurs when accessing the current site.
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Feb 28 03:31:40 KST 2020
There was an unexpected error (type=Internal Server Error, status=500).
No converter found for return value of type: class com.example.demo.Dto.TestVo
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.demo.Dto.TestVo
at
Source code of TestVo class:
package com.example.demo.Dto;
public class TestVo {
private int seq;
private String title;
private String contents;
private String author;
private String password;
private int reads = 0;
private String deleted = "N";
#Override
public String toString() {
return "TestVo [seq=" + seq + ", title=" + title + ", contents=" + contents + ", author=" + author + ", password=" + password + ", reads=" + reads + ", deleted=" + deleted + "]";
}
}
Your question isn't quite clear, we need to see your dto code, but try and see if adding the following dependency to your pom.xml, solves your problem.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.2</version>
</dependency>
You have not added any getter, and setter methods for member variables for TestVo class.
Add getter and setter methods.

#JsonCreator annotation want an enum value for attribute mode, but is allready given

When creating a shared library for automated deployment with jenkins I use a rest service that provides me with Json objects. Now when I run the pipeline the following error occurs:
Expected enum Value for attribute mode in #com.fasterxml.jackson.annotation.JsonCreator
The interesting thing is that this error does not occur on another Jenkins instance.
The code:
import com.cloudbees.groovy.cps.NonCPS
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
#JsonIgnoreProperties(ignoreUnknown = true)
class Asset {
final String downloadUrl
final String path
final String repository
final String format
#JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
Asset(
#JsonProperty('downloadUrl') String downloadUrl,
#JsonProperty('path') String path,
#JsonProperty('repository') String repository,
#JsonProperty('format') String format
){
this.downloadUrl = downloadUrl
this.path = path
this.repository = repository
this.format = format
}
#Override #NonCPS
String toString() {
return "Asset{" +
"downloadUrl='" + downloadUrl + '\'' +
", path='" + path + '\'' +
", repository='" + repository + '\'' +
", format='" + format + '\'' +
'}';
}
}

JPA difference Windows / Unix System?

For development purposes i'm using a windows environment (Eclipse / Jboss)
There i have a userDAO, that offers the method to rerieve a UserEntity by first- and lastname. This Query runs well on the dev environment. However on the Unix-Environment, i get a javax.persistence.NoResultException: No entity found for query Exception.
Situation in Detail:
A REST-Service is beeing called, containing many Data, along with a firstname and lastname. this parameters needs to be used to obtain the actuall userEntity. (It fails for ANY user on Unix.)
So, the rest service is doing this:
#Consumes("application/json")
#Produces("application/json")
public String create(String plaindata) {
JSONObject data = new JSONObject(plaindata);
String ownerFirstname = data.getString("userFirstname"); //Yes userX, not ownerX
String ownerLastname = data.getString("userLastname");
UserEntity owner = null;
try {
owner = userDataService.getUserDetailsByName(ownerFirstname, ownerLastname);
} catch (Exception e) {
throw new Exception("Found zero possible users for the given name '" + ownerFirstname + " " + ownerLastname
+ "'. Cannot invoke process.", e);
}
...
}
The userDataService looks (stripped) like this:
private static String GET_USER_BY_FIRSTNAME_LASTNAME_QUERY = "SELECT * FROM " + DBConstants.USER_TABLE_NAME
+ " user WHERE user.FIRST_NAME = :firstnameValue AND user.LAST_NAME = :lastnameValue";
public UserEntity getUserDetailsByName(String firstname, String lastname) {
Query query = em.createNativeQuery(GET_USER_BY_FIRSTNAME_LASTNAME_QUERY, UserEntity.class);
query.setParameter("firstnameValue", firstname);
query.setParameter("lastnameValue", lastname);
UserEntity u = (UserEntity) query.getSingleResult();
return u;
}
DBConstants contains the table name like:
public static final String DATATABLE_PREFIX = "pre_";
public static final String USER_TABLE_NAME = DATATABLE_PREFIX+"user_entity";
Column Names in mySQL are Capitalized, so everything seems right.
this works on a Windows Environment, but NOT in the Unix Environment :(
String ownerFirstname = data.getString("userFirstname").trim();
String ownerLastname = data.getString("userLastname").trim();
And it works... Strange thing - what could be the difference between windows and unix towards this issue? (The Exception logged absolutely NO Whitespace)

pass authentication parameter in webservice

I am building a webservice server side. In my webservice, every client needs to pass their authentication parameter, via POST method in json format, for every request they make. Is passing parameter via post a good practice?
A guy told me, I should always use GET method to retrieve data; POST should be used for insertion only. If this is so, how am I going to pass the authentication param? One could be through URL and the other through header value. Which way should I use?
try to implement this web service. This web service permits to pass their authentication parameter through header value.
#WebService(serviceName="authentication")
public class WSAuthentication {
String name = null;
String password = null;
public WSAuthentication() {
super();
}
public WSAuthentication(String name, String password) {
this.name = name;
this.password = password;
}
private static String getData(WSAuthentication sec) {
System.out.println("********************* AUTHENTICATION ********************" + "\n" +
"**********USER: " + sec.name + "\n" +
"******PASSWORD: " + sec.password + "\n" +
"******************************** AUTHENTICATION ****************************");
return sec.name + " -- " + sec.password;
}
#WebMethod(operationName="security", action="authenticate")
#WebResult(name="answer")
public String security(#WebParam(header=true, mode=Mode.IN, name="user") String user, #WebParam(header=true, mode=Mode.IN, name="password") String password) {
WSAuthentication secure = new WSAuthentication(user, password);
return getData(secure);
}
}
And I use POST method for response. I hope help you.

Datanucleus JDO setting fields to null

In an attempt to find another issue, my tests came up with the following bit of code.
public class TestPersistance {
private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
public static final PersistenceManager pm = PMF.getPersistenceManager();
static final TestUserDataDB ud = new TestUserDataDB();
public static void main(String args[])
{
TestPersistance tp = new TestPersistance();
tp.createData();
}
#Test public void createData()
{
assertTrue("Null machined id at start", ud.machineId != null);
pm.currentTransaction().begin();
try
{
pm.makePersistent(ud);
}
finally
{
pm.currentTransaction().commit();
}
assertTrue("Null machined id at end", ud.machineId != null);
}
}
where the second assert fails. ie. my object that I am asking to be persisted is being changed by the makePersistent call. The data is being stored in the database.
Any ideas? Can any one confirm this.
using
jdo-api-3.0.jar
datanucleus-core-2.2.0-release.jar
datanucleus-enhancer-2.1.3.jar
datanucleus-rdbms-2.2.0-release.jar
mysql-connector-java-5.1.13.jar
in eclipse with MySql database.
#PersistenceCapable
public class TestUserDataDB {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Long id;
#Persistent
public String userid = "test1";
#Persistent
public String machineId = "test2";
// local userid
#Persistent
public long uid = 1L;
#Persistent
public long systemTime = 123L;
public long chk = 1234L;
public long createTime = System.currentTimeMillis();
public TestUserDataDB()
{
}
#Override
public String toString() {
return "TestUserDataDB [chk=" + chk + ", createTime=" + createTime
+ ", id=" + id + ", machineId=" + machineId + ", systemTime="
+ systemTime + ", uid=" + uid + ", userid=" + userid + "]";
}
}
Properties file is
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.jdo.JDOPersistenceManagerFactory
datanucleus.metadata.validate=false
javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver
javax.jdo.option.ConnectionURL=jdbc:mysql://localhost/test
javax.jdo.option.ConnectionUserName=root
javax.jdo.option.ConnectionPassword=yeahRight
datanucleus.autoCreateSchema=true
datanucleus.validateTables=false
datanucleus.validateConstraints=false
Why are you accessing fields directly ? Is the accessing class declared as PersistenceAware ? Well it isn't so you can't do that - use the getters.
What is "ud" object state before persist ? (transient?) what is it after persist ? (hollow?) What does the log say ? Chances are that it is in hollow state and then you access a field directly and it has no value (by definition, as per the spec) ... but since you didn't bother calling the getter it hasn't a chance to retrieve the value. And you likely also don't have "RetainValues" persistent property set
Suggest you familiarise yourself with the JDO spec and object lifecycle states
In some cases, it is necessary to access deserialized objects' attributes directly (i.e. if using GSON library for JSON serialization). In that case you can use:
MyClass copy = myPersistencyManager.detachCopy(myRetrievedInstance);