Linking a jsp page to a java class - java

I have written a hello world program in jsp and now i am trying to process forms via JSP.
My jsp form(GetName.jsp) looks like this
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<FORM METHOD=POST ACTION="SaveName.jsp">
Name <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
Email <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
Age <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
</body>
</html>
Similarly SaveName.jsp looks like this
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="userData" class="javabeans.UserData" scope="session"/>
<jsp:setProperty name="userData" property="*"/>
</BODY>
</HTML>
</body>
</html>
And in the same project in a package named javabeans the class named UserData looks like this.
package javabeans;
public class UserData {
String username;
String email;
int age;
public void setUsername( String value )
{
username = value;
}
public void setEmail( String value )
{
email = value;
}
public void setAge( int value )
{
age = value;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public int getAge() { return age; }
}
Now when run GetName.jsp i get the following errors
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:56: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
UserData user = null;
^
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:58: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = (UserData) _jspx_page_context.getAttribute("user", PageContext.SESSION_SCOPE);
D:\javaworkspace\Netbeans7-2\HelloWeb\build\generated\src\org\apache\jsp\SaveName_jsp.java:60: cannot find symbol
symbol : class UserData
location: class org.apache.jsp.SaveName_jsp
user = new UserData();
3 errors
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:930: The following error occurred while executing this line:
D:\javaworkspace\Netbeans7-2\HelloWeb\nbproject\build-impl.xml:284: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 2 seconds)

You need to import UserData class inside SaveName.jsp
Add this to the top of your jsp code in SaveName.jsp
<%# page import="javabeans.UserData" %>

I'm not sure what you want to implement over here but i can give you simple idea about jsp servlets
first you can create a simple jsp program. it will ask the user for name and email id and on form action redirect it to abc servlet.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> My first JSP </title>
</head>
<body>
<form action="abc">
Please enter a name <br>
<input type="text" name="name"size="20px">
Please enter an email <br>
<input type="text" name="email"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
and then create the "abc" servlet
place this code in your servlet. it will get the value from jsp page and display it.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class abc extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// reading the user input
String name= request.getParameter("name");
String email= request.getParameter("email");
String msg="I'm"+name+"id is"+email;
PrintWriter out = response.getWriter();
out.println (
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html> \n" +
"<head> \n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html;
charset=ISO-8859-1\"> \n" +
"<title> Hi </title> \n" +
"</head> \n" +
"<body> \n" +
msg +
"</font> \n" +
"</body> \n" +
"</html>"
);
}
}
Define your servlet in "web.xml" . you need to do servlet mapping in web.xml file.
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>abc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>

Related

Data Injection from controller to jsp page

I want to pass a data from controller method to jsp page. In doing so, using HttpServletRequest.setAttribute().
Now, I can pass it to the just next jsp page. But, I want to hold that data for few more pages.
In this case, what should I do?
Flow of Data:
Controller method1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> Controller method2
I tried setting attribute in each page but it returns null value, as follows
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
You have to use session in jsp when sending data from one page to another.
A demo to show this.
For example :
Create a DemoController class.
#Controller
public class DemoController {
#RequestMapping(value = "/getid", method = RequestMethod.POST)
public String getAccountID(Model model) {
model.addAttribute("accountId", "ABC1234"); // example
return "account";
}
}
Suppose, create an account.jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accountId = request.getAttribute("accountId");
out.println("account.jsp -> " + accountId);
session.setAttribute("accId", accountId);
%>
<form action="account2.jsp" method="post">
<input type="submit" name="Submit">
</form>
</body>
</html>
Create another page with the name account2.jsp :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accId = (String) session.getAttribute("accId");
out.println("account2.jsp -> " + accountId);
// now you want to sent it to the another controller
// set the parameter in the session and retrieve it in the controller.
session.setAttribute("accountId", accId);
%>
</body>
</html>
Create a DemoController2 class :
#Controller
public class DemoController2 {
#RequestMapping(value = "/getid2", method = RequestMethod.POST)
public String getAccountId2(HttpSession session) {
String id = (String) session.getAttribute("accountId"); // example
System.out.println(id);
return "some-page-name";
}
}

Don't want to display constructor initialization in the jsp page?

I am working on web application, where I used a class Calculator with following information:-
public class Calculator {
private static String name,familyname;
public Calculator() {
name = "Roberto";
familyname = "Sanchez";
}
public static String getName() {
return name;
}
public static String getFamilyname() {
return familyname;
}}
In my index.jsp file, I used following code:-
<%--
Document : login
Created on : Nov 3, 2016, 6:21:46 AM
Author : yati
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Information</title>
</head>
<body bgcolor="#00FFFF">
<%=new com.algeb.Calculator()%> <br>
First Name: <%= com.algeb.Calculator.getName()%> <br>
Family Name: <%= com.algeb.Calculator.getFamilyname()%> <br>
Check Result
</body>
</html>
Now, my webpage looks like this:-
My problem is that I don't to display the first line (Calling class with the help of object) i.e. com.algeb.Calculator#3490ac94. This is also important step as without this, I cannot initialize the first name and last name. Please help?
Try to use JSP beans:
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className"/>
And than use id to call getName() and getFamilyname() methods, for example:
${instanceName.getFamilyname()}
${instanceName.getFamilyname()}

I am getting "HTTP Status 404 - /MVC_demo/LoginController". Please check if there are any errors in my programs [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
I have made a login validation project using model, view, controller but its not showing the intended result.There might be some error in controller part i guess.please have a look and see if there are any errors in it.
CONTROLLER-
LoginController.java(servlet)
package mvcdemo.controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mcvdemo.model.Authenticator;
import mcvdemo.model.User;
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginController() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
RequestDispatcher rd = null;
Authenticator authenticator = new Authenticator();
String result = authenticator.authenticate(username,password);
if(result.equals("success")){
rd= request.getRequestDispatcher("/success.jsp");
User user = new User(username,password);
request.setAttribute("user", user);
}
else{
rd= request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}
}
VIEW-
1)Login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action = "LoginController" method = "post">
Enter user : <input type="text" name="username" id="username"/>
<br>
Enter password : <input type="text" name="password" id="password"/>
<input type="submit" />
</form>
</body>
</html>
2) Success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
welcome!!!
</body>
</html>
3)error.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Login failed!!!
</body>
</html>
MODEL-
1)Authenticator.java
package mcvdemo.model;
public class Authenticator {
public String authenticate(String username, String password){
if("gaurav".equalsIgnoreCase(username)&&("password".equals(password)))
{
return "success";
}
else{
return "failure";
}
}
}
2)Use.java
package mcvdemo.model;
public class User {
private String username;
private String password;
public User(String username, String password)
{
this.username = username;
this.password = password;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username=username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password=password;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>MVC-demo</display-name>
<servlet>
<description></description>
<display-name>LoginController</display-name>
<servlet-name>LoginController</servlet-name>
<servlet-class>mvcdemo.controllers.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>LoginController</url-pattern>
</servlet-mapping>
</web-app>
The only thing I can see wrong in your code is the following line in web.xml:
<url-pattern>LoginController</url-pattern>
It should be
<url-pattern>/LoginController</url-pattern>
i.e. a / needs to be added before LoginController.

How to compile and run a JSP Beans project using Eclipse

I am a noob trying to learn what I can about JSPs. I am using Eclipse as my ide and have run into a small problem that I hope someone can help me out with. I have a dynamic web project with the following files:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Get Name</title>
</head>
<body>
<form action="saveName.jsp" method="post">
What is your name?
<input type="text" name="username" size="20">
<br>
What is your email address?
<input type="text" name="email" size="20">
<br>
What is your age?
<input type="text" name="age" size="4">
<br>
<input type="submit">
</form>
</body>
</html>
nextPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Next Page</title>
</head>
<body>
You entered
<br>
Name: <%=user.getUserName()%>
<br>
Email: <%=user.getUserEmail()%>
<br>
Age: <%=user.getUserAge()%>
</body>
</html>
saveName.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="user" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Save Name</title>
</head>
<body>
Continue
</body>
</html>
userData.java
package user;
public class UserData {
String userName;
String userEmail;
String userAge;
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #return the userEmail
*/
public String getUserEmail() {
return userEmail;
}
/**
* #param userEmail
* the userEmail to set
*/
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
/**
* #return the userAge
*/
public String getUserAge() {
return userAge;
}
/**
* #param userAge
* the userAge to set
*/
public void setUserAge(String userAge) {
this.userAge = userAge;
}
}
This app runs just fine except that my nextPage.jsp has null for all of the values. I know this is is because the userData.java is not being called.
Here is how the project is set up the html and jsp files are in the WebContent folder. userData.java is in the Java Resources folder under the user package. I am pretty sure the class for userData is supposed to be copied into the WEB-INF folder but it is not and even if I place it there myself the project still does not run right. Can someone show me how to set this up in Eclipse so that it will run correctly and I can experiment more with JSPs.
The problem is the difference between you input name and the setter of UserData, please try to modify the index.html as:
<form action="saveName.jsp" method="post">
What is your name?
<input type="text" name="userName" size="20">
<br>
What is your email address?
<input type="text" name="userEmail" size="20">
<br>
What is your age?
<input type="text" name="userAge" size="4">
<br>
<input type="submit">
</form>
I have test it OK. Wish it helps.

Content-Type not allowed: fileUpload in Struts 2

I am new to Struts 2 and trying to do use fileUpload interceptor. I am attaching all my code layers
Action Class (FileUploadAction):
package com.caveofprogramming.actions;
import java.io.File;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
#Action( value = "/fileUpload",
results={#Result(name="success",location="/success.jsp"),
#Result(name="error",location="/error.jsp"),
#Result(name="input",location="/error.jsp")
},
interceptorRefs={
#InterceptorRef(
params={"allowedTypes","image/jpeg,image/jpg,application/zip",
"maximumSize","1024000"},
value="fileUpload"
),
#InterceptorRef("defaultStack"),
#InterceptorRef("validation")
}
)
public String execute(){
try{
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
public String display() {
return NONE;
}
}
error.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:fielderror/>
</body>
</html>
Success.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success
</body>
</html>
fileUpload.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 <s:file> file upload example</h1>
<s:form method="post" enctype="multipart/form-data" action="fileUpload">
<s:file label="File One" name="fileUpload" />
<s:submit />
</s:form>
</body>
</html>
I am not understanding why I am getting this error
"Content-Type not allowed: fileUpload "photography-104a.jpg" "upload_37fbf440_169b_4687_af65_93c8c967256c_00000000.tmp" image/pjpeg"
Although my uploading file format is .jpg.
You are getting this error probably because you don't allow files with content type image/pjpeg. Use parameter of fileUpload interceptor to define allowed MIME types
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/pjpeg</param>
</interceptor-ref>

Categories

Resources