How to create multi layout in Spring MVC - java

I know about Apache Tiles in Spring, it seem working same jsp:include, but it doesn't solve my problem:
I want a file with name is layout1.jsp, in this file, I will define a layout like:
<html>
<head>
<style href="style1.css" />
</head>
<body>
<div class="main">
<div class="left">
<ul>
<li>
<li>
<li>
</ul>
</div>
<div class="content">
<h1>${message }</h1>
</div>
<div class="footer">
<span>This is footer</span>
</div>
</div>
</body>
</html>
And a file is layout2.jsp:
<html>
<head>
<style href="style2.css" />
</head>
<body>
<div class="main">
<div class="left2">
<ul>
<li>
<li>
<li>
</ul>
</div>
<div class="content2">
<h1>${message }</h1>
</div>
<div class="footer2">
<span>This is footer</span>
</div>
</div>
</body>
</html>
When user chose layout name on combobox, controller will set layout dynamic before render layout.
How should I do?

For switching the css file an you could use the Spring Theme Resolver. And you can use the same mechanism to change some small parts of your html (like the div classes)
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<style href="<spring:theme code='styleSheet'/>" />
</head>
<body>
...
<div class="<spring:theme code='contentClass'/>">
<h1>${message }</h1>
</div>
...
</body>
</html>
(But I would recommend to use the same html with same classes and just switch the css).
Do not forget to setup the theme resolver!
#See Spring Reference: Chapter Using themes

I found a method to solve this problem:
My application separator to multi module, example "Admin", "Default", each module have a interceptor, example a module interceptor:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String servletPath = request.getServletPath();
if (!servletPath.equals("/") && servletPath.substring(servletPath.length() - 1).equals("/")) {
response.sendRedirect(request.getContextPath() + servletPath.replaceAll("\\/+$", ""));
return false;
}
return true;
}
In view I have a class InternalResourceViewResolver.java:
package view;
import helper.AppHelper;
import java.util.Locale;
import org.springframework.web.servlet.View;
public class InternalResourceViewResolver extends
org.springframework.web.servlet.view.InternalResourceViewResolver {
public View resolveViewName(String viewName, Locale locale)
throws Exception {
AppHelper.setPage("../" + AppHelper.getModule() + "/" + viewName + ".jsp");
return super.resolveViewName("layout/" + AppHelper.getLayout(), locale);
}
}
AppHelper class:
package helper;
public class AppHelper {
private static String module = "default";
private static String layout = "main";
private static String page = "index";
public static String getModule() {
return module;
}
public static void setModule(String module) {
AppHelper.module = module;
}
public static String getLayout() {
return layout;
}
public static void setLayout(String layout) {
AppHelper.layout = layout;
}
public static String getPage() {
return page;
}
public static void setPage(String page) {
AppHelper.page = page;
}
}
In other module, example for Admin:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("ServletPath" + request.getServletPath());
AppHelper.setModule("admin");
AppHelper.setLayout("admin");
return true;
}
And my view page:
In layout:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#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=UTF-8">
<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
<title>Welcome to web</title>
</head>
<body>
<div class="wrapper">
<div class="main">
<div class="header"></div>
<div class="content">
<div class="content-left">
<jsp:include page="<%=helper.AppHelper.getPage() %>"></jsp:include>
</div>
<div class="content-right"></div>
</div>
<div class="footer"></div>
</div>
</div>
</body>
</html>
Placeholder page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<h1>${message }</h1>
<h2>${welcome }</h2>
<c:forEach items="${batches }" var="batch">
${batch.id } - ${batch.name }
</c:forEach>
Here directory struct:
- src\main\webapp\WEB-INF\pages
- admin
- index
- index.jsp
- setting.jsp
- product
- index.jsp
- detail.jsp
- other
...
- default
- index
- index.jsp
- contact.jsp
- product
...
- layout
admin.jsp
main.jsp

You could do this using Tiles too ...
use apache-tiles 2.2.1 or above
In application's tiles.xml where you put layout models do this
<definition name="masterTile" templateExpression="${requestScope.layout} >
<put-attribute name="title" value="" />
<put-attribute name="header" value="/view/header.jsp" />
<put-attribute name="menu" value="/view/menu"/>
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/view/footer.jsp"/>
</definition>
For more on this refer here Tiles Expression Language Support

Related

Spring checkbox parameters

I have a problem with checkbox. I have such jsp page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All Photos</title>
</head>
<body>
<form action="/photos/deletePhotos">
<c:forEach var="photo" items="${photoList}">
<p><input type="checkbox" name="id" value="${photo.key}">${photo.key}</p>
<img src="/photos/photo/${photo.key}" width="300" height="200">
<br/><br/>
</c:forEach>
<input type="submit" value="Delete" />
</form>
</body>
</html>
and such controller:
#RequestMapping("/deletePhotos")
public ModelAndView deleteSomePhotos(#PathVariable(name = "id", required = false) long[] id) {
System.out.println(id);
return new ModelAndView("all", "photoList", photos);
}
problem is id==null, no matter checked checkbox or not. Where is my mistake?
#PathVariable is for path variable, like #RuquestMapping("/deletePhotos/{id}").
Use #RequestParam instead of #PathVariable.
Refer here : #RequestParam vs #PathVariable

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userData' available as request attribute

I am newbie in spring mvc. I am trying to make simple crud in spring using MySQL jdbc. For datamapping I have used spring form. Whenever I try to use spring form it shows an Error
Error is here
Whenever i remove spring form and use normal form it looks ok but shows an error when used spring form. The error says java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userData' available as request attribute
header.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">SpringCRUDDemo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>Home</li>
<li>View</li>
<li>Update</li>
<li>Delete</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
index.jsp
<%#include file="./shared/header.jsp" %>
<div class="container">
<form:form commandName="userData" action="#" method="post" enctype="multipart/form-data">
<label for="firstname" class="label">Enter your first name</label>
<form:input path="firstName"/>
</form:form>
</div>
servlet class
package com.nishan.springcruddemo.servlet;
import com.nishan.springcruddemo.daoimp.CustomerDaoImp;
import com.nishan.springcruddemo.entity.Customer;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
*
* #author Dell
*/
#Controller
public class DefaultController {
#Autowired
CustomerDaoImp customerDaoImp;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value = "/insert", method = RequestMethod.POST)
public String save(#ModelAttribute("userData") Customer customer) {
try {
customerDaoImp.insert(customer);
} catch (ClassNotFoundException | SQLException ex) {
System.out.println(ex.getMessage());
}
return "redirect:/index";
}
#RequestMapping(value = "/view", method = RequestMethod.GET)
public String viewCustomer() {
return "view-customer";
}
}
You have to Use #RequestParam to get single value.
To Bind form data with model class You need to create Model(POJO) as userData commandName="userData".CommandName and ModelClass Name both same.
Fields of class firstName and both same. Then Your Form Data Bind with Pojo It will come at your controller Class.
I hope it will help.

Passing parameter from controller to jsp in spring

I have a controller method as follow.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
in which i am passing the jobId to get the instance of the job by id and returning "edit" string so that it maps to edit.jsp as per the InternalResourceViewResolver. But when i click on the link it goes to /edit/44 in which case 44 would be the id of the job for which the edit link belongs to. Finally i got the error stating no resource found.
home.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page session="false"%>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<title>Home</title>
</head>
<body id="main">
<div class="container">
<h2 style="color:white">All posted jobs</h2>
<c:if test="${empty jobList}">
<h6>No Job Post Yet</h6>
</c:if>
<c:if test="${!empty jobList}">
<c:forEach items="${jobList}" var="job">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">${job.title }</h3>
</div>
<div class="panel-body">${job.description }</div>
<div class="panel-footer">
<a id="link" href="delete/${job.id }">Delete</a>
<a id="link" href="edit/${job.id}">Edit</a>
</div>
</div>
</c:forEach>
</c:if>
<section>
<form:form method="post" action="add" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title:</form:label>
<form:input class="form-control" path="title"/>
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
<a id="addJob" href="add">+</a>
</form:form>
</section>
</div>
JobController.java
package com.job.src;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.job.src.model.Job;
import com.job.src.services.JobService;
#Controller
public class JobController {
#Autowired
private JobService jobService;
#RequestMapping(value= "/")
public String listJobs(Map<String,Object> map){
map.put("job", new Job());
map.put("jobList", jobService.listJobs());
return "home";
}
#RequestMapping(value= "/add", method=RequestMethod.POST)
public String addJob(Job job){
jobService.addJob(job);
return "redirect:/";
}
#RequestMapping("/delete/{jobId}")
public String deleteJob(#PathVariable("jobId") Integer jobId){
jobService.removeJob(jobId);
return "redirect:/";
}
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# 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>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="post" action="editSuccess" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title: </form:label>
<form:input class="form-control" path="title" />
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
</form:form>
In editJob method your are returning only id of job with model attribute to edit.jsp. But actually on edit.jsp page you need job object so you need to get job object by id add it as model attribute.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
//model.addAttribute("id",jobId); this is wrong
Job job = jobService.getJobById(jobId);
//write method in jobservice to get job by id i.e. getJobById(Integer jobId);
model.addAttribute("job",job)
return "edit";
}

Control over where a form display the output from your submission

In my web application, I have a home page where the options available to the user are placed in a fixed sidebar in the top of the screen, and each one of this options are opened inside of a tag <div> in this same page.
My problem is: when this content is a form, and I submit it to the server, after the processing, the output page isn't opened in this <div>, but in the entire navigation space. What I want is a way of capture this return and display it in the same <div> it was originated.
the code for my home page is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>HorarioLivre</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-fixed-top.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onload="close_page()">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HorarioLivre</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Evento</li>
<li>Lista Horarios</li>
<li>Cadastra Horarios</li>
<li>Usuarios</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
${usuario.nome} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Perfil</li>
<li>Configurações</li>
<li>Sair</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="page-header">
<h1></h1>
</div>
<div class="panel panel-default" id="results">
<div class="panel-heading">
<div align="right"><button type="button" class="btn btn-lg btn-danger" onclick="close_page()">Fechar</button></div>
</div>
<div class="panel-body" id="content">
Panel content
</div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function load_page(url){
$('#results').css("display", "block");
$('#content').load(url);
$('#container').draggable();
}
function close_page(){
$('#results').css("display", "none");
$('#content').empty();
}
</script>
</body>
</html>
I am using Spring, and the pages linked here are handled by Controller. By example,the page "cadastra_evento.html" is:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title>Lista de Eventos</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="alert alert-info">
<strong>Eventos</strong> Segue a lista de eventos cadastrados.
</div>
<div class="container">
<div class="row">
<div class="col-md-3">Nome</div>
<div class="col-md-3">Descrição</div>
<div class="col-md-3">Periodo</div>
<div class="col-md-3">Duração</div>
</div>
<c:forEach var="item" items="${lista}">
<div class="row">
<div class="col-md-3"><c:out value="${item.nome}"/></div>
<div class="col-md-3"><c:out value="${item.descricao}"/></div>
<div class="col-md-3"><c:out value="${item.data_inicial}"/> - <c:out value="${item.data_final}"/></div>
<div class="col-md-3"><c:out value="${item.duracao}"/></div>
</div>
</c:forEach>
</div>
<div class="alert alert-info">
<strong>Novo</strong> Cadastre um novo evento.
</div>
<form method="post" action="cad_evento.html">
<input type="text" name="nome" placeholder="Nome" size=20 maxlength=40> <br/>
<input type="text" name="descricao" placeholder="Descrição" size=30 maxlength=100> <br/>
<h3>Periodo da Data</h3>
inicio: <input name="data_inicial" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
final: <input name="data_final" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
<h3>Periodo do Horário</h3>
inicio: <input name="hora_inicial" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
final: <input name="hora_final" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
<input type="text" name="duracao" placeholder="duração" size=20 maxlength=2> <br/>
<button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
</form>
</body>
</html>
To finish, the page "cad_evento.html" used as action for the form above, is handled by method of same name from Controller:
#RequestMapping(value="/cad_evento", method=RequestMethod.POST)
public ModelAndView cadastra_evento(#RequestParam("nome") String nome, #RequestParam("descricao") String descricao, #RequestParam("data_inicial") String data_inicial, #RequestParam("hora_inicial") String hora_inicial, #RequestParam("data_final") String data_final, #RequestParam("hora_final") String hora_final, #RequestParam("duracao") int duracao) {
if(sessao != null)
{
if(sessao.getUsuario().temAutorizacao("cad_evento"))
{
Date d_inicio = new Date(Date.parse(data_inicial));
Date d_final = new Date(Date.parse(data_final));
Time h_inicio = new Time(Time.parse(hora_inicial));
Time h_final = new Time(Time.parse(hora_final));
EventoDAO evento = new EventoDAO(nome, descricao, d_inicio, d_final, h_inicio, h_final, duracao, sessao.getUsuario());
int saida = evento.cadastra();
if(saida == 0)
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Erro ao cadastrar o evento");
return mav;
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/listagem_evento");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Usuário sem permissão de acesso");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/usuario_login_page");
return mav;
}
}
Someone have any thoughts about how to do that?
Well, spring mvc just open new page with a content you set in ModelAndView. If you want to load somthing just in some part of page ( in this case ) there pure javascript / jquery ajax is needed. So steps needed here:
Add javascript which will do ajax request to controller
Controller need to return JSON ( #ResponseBody can help you )
You have to do some DOM manipulation using javascript/jquery to put JSON answer to your div.

how to persist value in text field after refresh?

I am uploading a file in a form, that form also contains some textfields I enter some values in the textfields. I want this value to remain when I click upload button. And there is also a save button, when I click this button uploaded file should get saved in database. Can any one help me out?
JSP file is here:
<body>
<form action="./upload" enctype="multipart/form-data" >ID: <input type="text" name="id" value="" />Name: <input type="text" name="name" value="" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
I need the bussiness logic in a servlet..
Your options are:
Persist the data to your back-end and re-populate the form
Persist the data to the the in-browser Storage (http://www.w3schools.com/html/html5_webstorage.asp)
Put the upload form in an IFRAME
The easiest option is the IFRAME.
Hey you are saying the text field values should be there while clicking Upload button. You don't have to do this thing. By default it will be there. You should it will venish man? Please mention your exact requirement.
See there is no provision to keep the file field data using value attribute.
See this link
package comunity.stackoverflow.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestController
*/
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestController() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,
HttpServletResponse response) {
storeInRequest(request, "id");
storeInRequest(request, "name");
storeInRequest(request, "uploaded");
// write your upload logic here then navigate to the same page;
try {
request.getRequestDispatcher("/test.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void storeInRequest(HttpServletRequest request,String param){
String val = request.getParameter(param);
if(param!=null && !param.isEmpty()){
System.out.println(val);
request.setAttribute(param, val);
}
}
}
Use standard.jat and jstl.jar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/>
Name: <input type="text" name="name" value="${name}" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
</html>
Use this JSP file. It might solve your problem.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/><br/>
Name: <input type="text" name="name" value="${name}" /><br/>
<input type="file" id="selectedFile" style="display: none;" />
<input type="text" name="uploaded" id="uploaded" value="${uploaded}" readonly="readonly" size="60">
<input type="button" value="Browse..." onclick="mymethod()" /><br/>
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
<script type="text/javascript">
function mymethod(){
document.getElementById('selectedFile').click();
var val = document.getElementById('selectedFile').value;
document.getElementById('uploaded').value = val;
}
</script>
</html>

Categories

Resources