Display data from java class in JSP - java

I am trying to make a web project. My question can I display java properties on the JSP page using JSTL? I am quite new in JSP.
As far I am now , I created the login page which is handled by servlet. What I want to achieve is that user log in with his credentials. And based on the credentials the data are processed on the background and displayed on page. (after login user clicks on page my info and the data are automatically populated). Creating another servlet is not a good option, so I probably need to call the data from the normal class(without needing a form).
Login.jsp
<form action="LoginServlet" method="post">
<table>
<tr><td>Login : </td><td><input type="text" name="login"/></td></tr>
<tr><td>Password :</td><td><input type="password" name="password"/></td></tr>
<tr><td><input type="submit" value="Login"/></td><td></td></tr>
</table>
</form>
LoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
request.setAttribute("login", login);
request.setAttribute("password", password);
LoginService.setPublicID(login);
boolean result = LoginService.Auth(login, password);
System.out.println(result);
if(result==true){
getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
}
else{
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
LoginService.java (auth. handler) [i used static publicID because based on this, other stuff is done]
public class LoginService {
public static String publicID;
public static String getPublicID() {
return publicID;
}
public static void setPublicID(String login) {
LoginService.publicID = login;
}
public static boolean Auth(String login, String password){
System.out.println(password);
if(password.equals("gw") && login.equals("servo")){
return true;
}
else
{
return false;
}
}
}
This redirects me to the main.jsp.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<h2>Login successful!</h2>
UserInfo
Welcome <c:out value="${login}"/>
</body>
</html>
UserInfoService.java
public class UserInfoService {
static String userName;
static String lastName;
static String mobile;
static String email;
public static String getUserName() {
return userName;
}
public static void setUserName(String userName) {
userName = LoginService.getPublicID();
UserInfoService.userName = userName;
}
public static String getEmail() {
return email;
}
public static void setEmail(String email) {
UserInfoService.email = email;
}
}
And finally.
UserInfo.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="org.UserInfo.UserInfoService"%>
<!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>
<c:out value="${UserInfoService.getUserName}"/>
</body>
</html>
But this is always empty. Can you please tell me where I am wrong?

UserInfoService resolves to null, You need to register it as a bean see here

You are not calling the UserInfoService.setUserName() method from anywhere in the code.

Related

I can't find the error from .jsp

I can't figure it out why that is not working. That is the jsp that make me problems. I follow a tutorial from youtube and my jsp looks the same like the jsp from the video. I adapted the code from the video but i don't think that is the problem because the controller and the jsp are the same like those from the video.
here is the tutorial, jsp is at min 24
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!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>Upload Page</title>
</head>
<body>
<spring:url value="/doUpload" var="doUplodaURL" />
<form:form method="post" modelAttribute="formUpload" action="${doUplodaURL
}" enctype="multipart/form-data" >
<form:input path="files" type="file" multiple="multiple"/>
<form:errors path="files" /><br/>
<button type="submit" >Upload</button>
</form:form>
</body>
</html>
and that is my controller
#Controller
public class CsvController {
#Autowired
FileValidator fileValidator;
#Autowired
CsvServices csvServices;
#RequestMapping(value = "/uploadPage", method = RequestMethod.GET)
public ModelAndView getPage() {
ModelAndView model = new ModelAndView("upload_page");
FileUpload formUpload = new FileUpload();
model.addObject("formUpload", formUpload);
return model;
}
#RequestMapping (value="/doUpload", method=RequestMethod.POST)
public String doUpload(#ModelAttribute("formUpload") FileUpload fileUpload, BindingResult result, RedirectAttributes redirectAttributes ) throws IOException {
fileValidator.validate(fileUpload, result);
if(result.hasErrors()) {
return "uploadPage";
} else {
redirectAttributes.addFlashAttribute("fileNames", uploadAndImportDb(fileUpload));
return "redirect:/succes";
}
}
#RequestMapping(value = "/succes", method = RequestMethod.GET)
public ModelAndView succes() {
ModelAndView model = new ModelAndView("succes");
return model;
}
private List<String> uploadAndImportDb(FileUpload fileUpload) throws IOException{
List<String> fileNames = new ArrayList<String>();
List<String> paths = new ArrayList<String>();
CommonsMultipartFile[] commonsMultipartFiles = fileUpload.getFiles();
String filePath = null;
for(CommonsMultipartFile multipartFile : commonsMultipartFiles) {
filePath = "C:\\Users\\bogda\\Desktop\\input\\" + multipartFile.getOriginalFilename();
File file = new File(filePath);
FileCopyUtils.copy(multipartFile.getBytes(), file);
fileNames.add(multipartFile.getOriginalFilename());
paths.add(filePath);
}
//parse and import
csvServices.process(paths);
return fileNames;
}
}
Kindly add commons-fileupload-x.x.jar inside WEb_INF/lib folder.

Pass specific element to jsp from arraylist in model from servlet

So to be more specific what Im trying to solve. How can I show the first element in my Arraylist:"sortedDomainList" in my jsp?
EDIT : Model and ArrayList working tried in normal java application.
MODEL short version.
public ArrayList<String> sortedDomainList = new ArrayList<String>();
public ArrayList<String> getSortedDomainList() {
return sortedDomainList;
}
public void setSortedDomainList(ArrayList<String> sortedDomainList) {
this.sortedDomainList = sortedDomainList;
}
}
CONTROLLER/SERVLET
package com.comparebet.controller;
import com.comparebet.model.*;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
request.setAttribute("d", sortedDomainList);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
}
}
VIEW/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>CompareBet</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Comparebet" method="get" accept-charset="UTF-8"></form>
<h1> ${d.sortedDomainList[0]}</h1>
</body>
</html>
This is my first try on MVC so I feel really lost when it comes down to 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>CompareBet</title>
</head>
<body>
<%
ArrayList<String> sortedDomainList= request.getAttribute("d");
for(String domain:sortedDomainList){
%>
<h1> <%= domain %> </h1>
<% } %>
</body>
</html>

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.

struts action class parameters not printing in jsp

I am trying a simple struts application. And I have added few fields in action class and trying to print those fields in JSP class.
Everything is working fine and action methods are called properly except the properties are not printing on JSP page.
And also I cannot see any errors in logs.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>
<s:property value="test" />
</body>
</html>
Action class code :
public class ActionClass {
private String test="hello";
public String execute() {
System.out.println("hello ");
return "success";
}
}
Any help would be appreciated
change your code
public class ActionClass {
private String test="hello";
public String execute() {
System.out.println("hello ");
return "success";
}
//you can remove setter.
public void setTest(String test)
{
this.test = test;
}
public String getTest()
{
return test;
}
}
Make some changes in class--
import com.opensymphony.xwork2.ActionSupport;
public class ActionClass extends ActionSupport{
private String test= "Name from test.java";
public String getTest() {
return test;
}
public String execute() throws Exception {
return SUCCESS;
}
}

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